<template>
  <div class="app-container pageSediment">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="规则属性" prop="itemConfictType">
        <el-select
          v-model="queryParams.itemConfictType"
          clearable
          placeholder="请选择规则属性"
          size="small"
        >
          <el-option
            v-for="dict in itemConfictTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="cyan"
          @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button>
        <el-button
          v-hasPermi="['basis:itemConfict:add']"
          icon="el-icon-plus"
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增
        </el-button>
        <el-button
          v-hasPermi="['basis:itemConfict:edit']"
          :disabled="single"
          icon="el-icon-edit"
          size="mini"
          type="success"
          @click="handleUpdate"
        >修改
        </el-button>
        <el-button
          v-hasPermi="['basis:itemConfict:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          size="mini"
          type="danger"
          @click="handleDelete"
        >删除
        </el-button>
        <el-button v-if="false" icon="el-icon-plus"
                   size="mini"
                   type="primary"
                   @click="openSetItemGroupRelation"
        >
          互斥组设置
        </el-button>
        <el-dialog v-dialog-drag
                   :close-on-click-modal="false"
                   :destroy-on-close="true"
                   :visible.sync="relationData.visible"
                   class="r-dialog"
                   custom-class="dialog"
                   title="互斥组设置"
                   width="900px"
        >
          <el-transfer v-model="relationData.list"
                       v-loading="relationData.loading"
                       :data="relationData.dict"
                       :filter-method="filterMethod"
                       :titles="['未添加项目','已添加项目']"
                       filter-placeholder="输入项目名称搜索"
                       filterable
                       target-order="unshift"
          >
            <span slot-scope="{ option }" :title="option.label">{{ option.label }}</span>
          </el-transfer>
          <span slot="footer" class="dialog-footer">
            <el-button v-loading="relationData.loading" type="primary" @click="saveRelationData">保 存</el-button>
          </span>
        </el-dialog>
      </el-form-item>
    </el-form>
    <!--    <el-tabs v-model:value="activeTab" type="card">
          <el-tab-pane label="项目规则" name="item" />
          <el-tab-pane label="组内规则" name="groupIn" />
          <el-tab-pane label="组间规则" name="groupOut" />
        </el-tabs>-->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="itemConfictList" border stripe tooltip-effect="light" @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column v-if="false" align="center" label="主键" prop="id"/>
      <el-table-column :formatter="firstItemFormatter" align="left" fixed="left" label="项目一"
                       min-width="160"
                       prop="firstItem" show-overflow-tooltip
      />
      <el-table-column :formatter="secondItemFormatter" align="left" fixed="left" label="项目二"
                       min-width="160" prop="secondItem" show-overflow-tooltip
      />
      <el-table-column
        :formatter="itemConfictTypeFormat"
        align="center"
        label="规则属性"
        prop="itemConfictType"
        width="100"
      />
      <el-table-column align="center" label="间隔时间" prop="intervalTime" width="100"/>
      <el-table-column
        :formatter="isValidFormat"
        align="center"
        label="状态"
        prop="isValid"
        width="100"
      />
    </el-table>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改项目规则对话框 -->
    <el-dialog v-dialogDrag :title="title" :visible.sync="open" append-to-body width="700px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目一(前)" prop="firstItem">
          <el-select v-model="form.firstItem"
                     allow-create
                     default-first-option
                     filterable
                     placeholder="请选择项目一"
                     style="width: 500px"
          >
            <el-option
              v-for="item in inExamItemOptions"
              :key="item.id"
              :label="`【${item.itemCode}】${item.outExamItemName}`"
              :value="item.itemCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目二(后)" prop="secondItem">
          <el-select v-model="form.secondItem"
                     allow-create
                     default-first-option
                     filterable
                     placeholder="请选择项目二"
                     style="width: 500px"
          >
            <el-option
              v-for="item in inExamItemOptions"
              :key="item.id"
              :label="`【${item.itemCode}】${item.outExamItemName}`"
              :value="item.itemCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则属性" prop="itemConfictType">
          <el-select
            v-model="form.itemConfictType"
            placeholder="请选择规则属性"
          >
            <el-option
              v-for="dict in itemConfictTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :rules="form.itemConfictType ==='互斥'?timeRules:[]" label="间隔时间" prop="intervalTime">
          <el-input v-model="form.intervalTime" placeholder="请输入间隔时间" style="width: 217px">
            <template slot="append">小时</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="isValid">
          <el-select v-model="form.isValid" placeholder="请选择状态">
            <el-option
              v-for="dict in isValidOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listItemConfict,
  getItemConfict,
  delItemConfict,
  addItemConfict,
  updateItemConfict,
  exportItemConfict
} from '@/api/basis/itemConfict'
import { listInExamItem } from '@/api/basis/inExamItem'
import { listOutexamitem } from '@/api/basis/outexamitem'
import { getItemGroupRelation, saveItemGroupRelation } from '@/api/resource/itemGroup'

export default {
  name: 'ItemConfict',
  data() {
    return {
      activeTab: 'item',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目规则表格数据
      itemConfictList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态字典
      isValidOptions: [],
      // 规则属性字典
      itemConfictTypeOptions: [],
      //检查项目绑定
      inExamItemOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        itemConfictType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        firstItem: [
          { required: true, message: '项目一不能为空', trigger: 'change' }
        ],
        secondItem: [
          { required: true, message: '项目二不能为空', trigger: 'change' }
        ],
        itemConfictType: [
          { required: true, message: '规则属性不能为空', trigger: 'change' }
        ]
      },
      timeRules: [ // 互斥时间校验
        { required: true, message: '互斥规则下时间必填', trigger: 'blur' }
      ],
      relationData: { // 互斥组设置dialog
        visible: false,
        list: [],
        dict: [],
        loading: false
      }
    }
  },
  mounted() {
    this.getList()
    this.getDicts('state_type').then((response) => {
      this.isValidOptions = response.data
    })
    this.getDicts('exam_item_config').then((response) => {
      this.itemConfictTypeOptions = response.data
    })
    listOutexamitem().then((response) => {
      this.inExamItemOptions = response.rows
      this.relationData.dict = response.rows.map(item => {
        return {
          key: item.itemCode,
          label: item.outExamItemName
        }
      })
    })
  },
  methods: {
    ruleChange(val) {
      console.log('操作', 13213131213)
    },
    firstItemFormatter(row) {
      return `【${row['firstItemCode']}】${row.firstItem}`
    },
    secondItemFormatter(row) {
      return `【${row['secondItemCode']}】${row.secondItem}`
    },
    openSetItemGroupRelation() {
      this.relationData.visible = true
      this.relationData.loading = true
      getItemGroupRelation({ id: '1' })
        .then(res => {
          this.relationData.list = res.data.map(item => item.itemCode)
        }).finally(_ => {
        this.relationData.loading = false
      })
    },
    filterMethod(query, item) {
      return item.label.indexOf(query) > -1
    },
    saveRelationData() {
      console.log(this.relationData.list)
      this.relationData.loading = true
      saveItemGroupRelation({
        groupId: '1',
        itemCode: this.relationData.list.join(',')
      }).then(res => {
        this.relationData.visible = false
        this.relationData.loading = false
        this.$message.success('修改成功')
      }).finally(_ => {
        this.relationData.loading = false
      })
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /** 查询项目规则列表 */
    getList() {
      this.loading = true
      listItemConfict(this.queryParams).then((response) => {
        this.itemConfictList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 状态字典翻译
    isValidFormat(row, column) {
      return this.selectDictLabel(this.isValidOptions, row.isValid)
    },
    // 规则属性字典翻译
    itemConfictTypeFormat(row, column) {
      return this.selectDictLabel(
        this.itemConfictTypeOptions,
        row.itemConfictType
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        firstItem: null,
        secondItem: null,
        intervalTime: null,
        isValid: null,
        itemConfictType: null,
        unit: null,
        createdById: null,
        createdByName: null,
        createdAt: null,
        updatedById: null,
        updatedByName: null,
        updatedAt: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加项目规则'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getItemConfict(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改项目规则'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateItemConfict(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addItemConfict(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm(
        '是否确认删除项目规则编号为"' + ids + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delItemConfict(ids)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有项目规则数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return exportItemConfict(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.r-dialog {
  ::v-deep .el-transfer-panel {
    width: 350px;
  }

  ::v-deep .el-transfer-panel__list {
    height: 350px;
  }

  ::v-deep .el-transfer-panel__body {
    height: 400px;
  }
}
</style>
