<template>
  <div class="app-container">
    <el-tabs type="card">
      <el-tab-pane label="项目分组">
        <el-form :inline="true" :model="groupParams" label-width="68px">
          <el-form-item label="分组名称" prop="groupName">
            <el-input v-model="groupParams.groupName" clearable size="small"/>
          </el-form-item>
          <el-form-item>
            <el-button :loading="groupData.loading" icon="el-icon-search" size="mini"
                       type="cyan" @click="getGroupList"
            >搜索
            </el-button>
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="groupAdd">新增</el-button>
            <el-button :disabled="groupData.single" icon="el-icon-edit" size="mini"
                       type="success" @click="groupUpdate"
            >修改
            </el-button>
            <el-button :disabled="groupData.multiple" icon="el-icon-delete" size="mini"
                       type="danger" @click="groupDelete"
            >删除
            </el-button>
            <el-button :disabled="groupData.single" icon="el-icon-plus" size="mini"
                       type="primary" @click="openSetItemGroupRelation"
            >管理项目设置
            </el-button>
          </el-form-item>
        </el-form>
        <el-table ref="groupTable" v-loading="groupData.loading" :data="groupData.list" border stripe
                  tooltip-effect="light" @row-click="groupRowClick" @selection-change="groupSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="left" label="分组名称" min-width="160" prop="groupName"
                           show-overflow-tooltip
          />
          <el-table-column :formatter="exclusionFormatter" align="center" label="组内互斥" prop="exclusion"
                           show-overflow-tooltip width="220"
          />
          <el-table-column align="center" label="互斥时间" prop="intervalTime" show-overflow-tooltip
                           width="220"
          />
          <el-table-column :formatter="combineFormatter" align="center" label="组内合并" prop="combine"
                           show-overflow-tooltip width="220"
          />
          <el-table-column align="left" label="备注" min-width="300" prop="remarks"
                           show-overflow-tooltip
          />
        </el-table>
        <pagination
          v-show="groupParams.total > 0"
          :limit.sync="groupParams.pageSize"
          :page.sync="groupParams.pageNum"
          :total="groupParams.total"
          @pagination="getGroupList"
        />
        <el-dialog v-dialogDrag :title="groupDialog.title" :visible.sync="groupDialog.show" append-to-body
                   width="500px"
        >
          <el-form ref="groupDialogForm" :model="groupDialog.form" :rules="groupDialog.rules" label-width="100px">
            <el-form-item label="分组名称" prop="groupName">
              <el-input v-model="groupDialog.form.groupName" placeholder="请输入分组名称"/>
            </el-form-item>
            <el-form-item label="组内互斥" prop="exclusion">
              <el-select v-model="groupDialog.form.exclusion"
                         allow-create default-first-option
                         placeholder="请选择互斥规则"
              >
                <el-option :key="1" label="互斥" value="1"/>
                <el-option :key="0" label="不互斥" value="0"/>
              </el-select>
            </el-form-item>
            <el-form-item label="组内合并" prop="combine">
              <el-select v-model="groupDialog.form.combine"
                         allow-create default-first-option
                         placeholder="请选择合并规则"
              >
                <el-option :key="1" label="合并" value="1"/>
                <el-option :key="0" label="不合并" value="0"/>
              </el-select>
            </el-form-item>
            <el-form-item :rules="groupDialog.form.exclusion ==='1'?timeRules:[]" label="互斥时间" prop="intervalTime">
              <el-input v-model="groupDialog.form.intervalTime" placeholder="请输入互斥时间">
                <template #append>
                  小时
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="groupDialog.form.remarks" type="textarea"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitGroup">确 定</el-button>
            <el-button @click="cancelGroup">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog v-dialog-drag
                   :close-on-click-modal="false"
                   :destroy-on-close="true"
                   :visible.sync="relationDialogData.visible"
                   class="r-dialog"
                   custom-class="dialog"
                   title="项目关联设置"
                   width="1200px"
        >
          <el-transfer v-model="relationDialogData.list"
                       v-loading="relationDialogData.loading"
                       :data="relationDialogData.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="relationDialogData.loading" type="primary" @click="saveRelationData">保 存</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="项目组合规则">
        <el-form :inline="true" :model="ruleParams" label-width="68px">
          <el-form-item label="规则类型" prop="ruleType">
            <el-input v-model="ruleParams.ruleType" clearable size="small"/>
          </el-form-item>
          <el-form-item>
            <el-button :loading="ruleData.loading" icon="el-icon-search" size="mini"
                       type="cyan" @click="getRuleList"
            >搜索
            </el-button>
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="ruleAdd">新增</el-button>
            <el-button :disabled="ruleData.single" icon="el-icon-edit" size="mini"
                       type="success" @click="ruleUpdate"
            >修改
            </el-button>
            <el-button :disabled="ruleData.multiple" icon="el-icon-delete" size="mini"
                       type="danger" @click="ruleDelete"
            >删除
            </el-button>
          </el-form-item>
        </el-form>
        <el-table ref="ruleTable" v-loading="ruleData.loading" :data="ruleData.list" border stripe
                  tooltip-effect="light" @row-click="ruleRowClick" @selection-change="ruleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="left" label="分组(一)" min-width="160" prop="firstGroupName"
                           show-overflow-tooltip
          />
          <el-table-column align="left" label="分组(二)" min-width="160" prop="secondGroupName"
                           show-overflow-tooltip
          />
          <el-table-column align="center" label="组间规则" prop="ruleType" show-overflow-tooltip
                           width="220"
          />
          <el-table-column align="center" label="互斥时间" prop="intervalTime" show-overflow-tooltip
                           width="220"
          />
        </el-table>
        <pagination
          v-show="ruleParams.total > 0"
          :limit.sync="ruleParams.pageSize"
          :page.sync="ruleParams.pageNum"
          :total="ruleParams.total"
          @pagination="getRuleList"
        />
        <el-dialog v-dialogDrag :title="ruleDialog.title" :visible.sync="ruleDialog.show" append-to-body
                   width="500px"
        >
          <el-form ref="ruleDialogForm" :model="ruleDialog.form" :rules="ruleDialog.rules" label-width="100px">
            <el-form-item label="分组(一)" prop="firstGroup">
              <el-select v-model="ruleDialog.form.firstGroup"
                         placeholder="请选择分组"
              >
                <el-option v-for="item in groupDict" :key="item.id" :label="item.groupName" :value="item.id+''"/>
              </el-select>
            </el-form-item>
            <el-form-item label="分组(二)" prop="secondGroup">
              <el-select v-model="ruleDialog.form.secondGroup"
                         allow-create default-first-option
                         placeholder="请选择分组"
              >
                <el-option v-for="item in groupDict" :key="item.id" :label="item.groupName" :value="item.id+''"/>
              </el-select>
            </el-form-item>
            <el-form-item label="组间规则" prop="ruleType">
              <el-select v-model="ruleDialog.form.ruleType"
                         allow-create default-first-option
                         placeholder="请选择规则"
              >
                <el-option key="合并" label="合并" value="合并"/>
                <el-option key="互斥" label="互斥" value="互斥"/>
                <el-option key="先后" label="先后" value="先后"/>
              </el-select>
            </el-form-item>
            <el-form-item :rules="ruleDialog.form.ruleType ==='互斥'?timeRules:[]" label="互斥时间" prop="intervalTime">
              <el-input v-model="ruleDialog.form.intervalTime" placeholder="请输入互斥时间">
                <template #append>
                  小时
                </template>
              </el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitRule">确 定</el-button>
            <el-button @click="cancelRule">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import {
  deleteGroup, deleteGroupRule,
  getItemGroupList,
  getItemGroupRelation, getRuleList,
  saveItemGroupRelation,
  saveOrUpdateGroup, saveOrUpdateRule
} from '@/api/resource/itemGroup'
import { listOutexamitem } from '@/api/basis/outexamitem'

export default {
  name: 'ItemGroup',
  data() {
    return {
      timeRules: [ // 互斥时间校验
        { required: true, message: '互斥规则下时间必填', trigger: 'blur' }
      ],
      groupParams: {
        pageNum: 1,
        pageSize: 20,
        groupName: null,
        total: 0
      },
      groupData: {
        loading: false,
        list: [],
        selectIds: [],
        single: true,
        multiple: true
      },
      groupDialog: {
        title: '',
        show: false,
        form: {},
        rules: {
          groupName: [
            { required: true, message: '分组名称不能为空', trigger: 'blur' }
          ],
          exclusion: [
            { required: true, message: '请设置互斥规则', trigger: 'blur' }
          ],
          combine: [
            { required: true, message: '请设置合并规则', trigger: 'blur' }
          ]
        }
      },
      relationDialogData: { // 关联组设置dialog
        visible: false,
        list: [],
        dict: [],
        loading: false
      },
      groupDict: [],
      ruleParams: {
        pageNum: 1,
        pageSize: 20,
        ruleType: null,
        total: 0
      },
      ruleData: {
        loading: false,
        list: [],
        selectIds: [],
        single: true,
        multiple: true
      },
      ruleDialog: {
        title: '',
        show: false,
        form: {},
        rules: {
          firstGroup: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          secondGroup: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          ruleType: [
            { required: true, message: '规则不能为空', trigger: 'blur' }
          ]
        }
      }
    }
  },
  methods: {
    groupRowClick(row) {
      this.$refs.groupTable.toggleRowSelection(row)
    },
    groupSelectionChange(selection) {
      this.groupData.selectIds = selection.map((item) => item.id)
      this.groupData.single = selection.length !== 1
      this.groupData.multiple = !selection.length
    },
    exclusionFormatter(row) {
      return row.exclusion === '1' ? '互斥' : '不互斥'
    },
    combineFormatter(row) {
      return row.combine === '1' ? '合并' : '不合并'
    },
    getGroupList() {
      this.groupData.loading = true
      getItemGroupList(this.groupParams).then(res => {
        this.groupData.list = res.rows
        this.groupParams.total = res.total
      }).finally(_ => {
        this.groupData.loading = false
      })
    },
    groupDialogFromReset() {
      this.groupDialog.form = {}
      this.resetForm('groupDialogForm')
    },
    cancelGroup() {
      this.groupDialog.show = false
      this.groupDialogFromReset()
    },
    groupAdd() {
      this.groupDialogFromReset()
      this.groupDialog.show = true
      this.groupDialog.title = '添加项目分组'
    },
    groupUpdate() {
      this.groupDialogFromReset()
      this.groupDialog.show = true
      this.groupDialog.form = this.groupData.list.find(item => item.id === this.groupData.selectIds[0])
      this.groupDialog.title = '修改项目分组基本信息'
    },
    submitGroup() {
      this.$refs.groupDialogForm.validate((valid) => {
        if (valid) {
          saveOrUpdateGroup(this.groupDialog.form).then(res => {
            this.msgSuccess('提交成功')
            this.groupDialog.show = false
            this.getGroupList()
          })
        }
      })
    },
    groupDelete() {
      this.$confirm(
        '是否删除选中的项目组?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(res => {
        return deleteGroup({ ids: this.groupData.selectIds.join(',') })
      }).then(res => {
        this.msgSuccess('删除成功')
        this.getGroupList()
      })
    },
    filterMethod(query, item) {
      return item.label.indexOf(query) > -1
    },
    saveRelationData() {
      this.relationDialogData.loading = true
      saveItemGroupRelation({
        groupId: this.groupData.selectIds[0],
        itemCode: this.relationDialogData.list.join(',')
      }).then(res => {
        this.relationDialogData.visible = false
        this.relationDialogData.loading = false
        this.$message.success('修改成功')
      }).finally(_ => {
        this.relationDialogData.loading = false
      })
    },
    openSetItemGroupRelation() {
      this.relationDialogData.visible = true
      this.relationDialogData.loading = true
      getItemGroupRelation({ id: this.groupData.selectIds[0] })
        .then(res => {
          this.relationDialogData.list = res.data.map(item => item.itemCode)
        }).finally(_ => {
        this.relationDialogData.loading = false
      })
    },
    getRuleList() {
      this.ruleData.loading = true
      getRuleList(this.ruleParams).then(res => {
        this.ruleData.list = res.rows
        this.ruleParams.total = res.total
      }).finally(_ => {
        this.ruleData.loading = false
      })
    },
    ruleRowClick(row) {
      this.$refs.ruleTable.toggleRowSelection(row)
    },
    ruleSelectionChange(selection) {
      this.ruleData.selectIds = selection.map((item) => item.id)
      this.ruleData.single = selection.length !== 1
      this.ruleData.multiple = !selection.length
    },
    ruleDialogFromReset() {
      this.ruleDialog.form = {}
      this.resetForm('ruleDialogForm')
    },
    ruleAdd() {
      getItemGroupList({
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        this.groupDict = res.rows
        this.ruleDialogFromReset()
        this.ruleDialog.show = true
        this.ruleDialog.title = '添加组间规则'
      })
    },
    ruleUpdate() {
      getItemGroupList({
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        this.groupDict = res.rows
        this.ruleDialogFromReset()
        this.ruleDialog.show = true
        this.ruleDialog.form = this.ruleData.list.find(item => item.id === this.ruleData.selectIds[0])
        this.ruleDialog.title = '修改组间规则'
      })
    },
    cancelRule() {
      this.ruleDialog.show = false
      this.ruleDialogFromReset()
    },
    submitRule() {
      this.$refs.ruleDialogForm.validate((valid) => {
        if (valid) {
          saveOrUpdateRule(this.ruleDialog.form).then(res => {
            this.msgSuccess('提交成功')
            this.ruleDialog.show = false
            this.getRuleList()
          })
        }
      })
    },
    ruleDelete() {
      this.$confirm(
        '是否删除选中的组间规则?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(res => {
        return deleteGroupRule({ ids: this.ruleData.selectIds.join(',') })
      }).then(res => {
        this.msgSuccess('删除成功')
        this.getRuleList()
      })
    }
  },
  created() {
    this.getGroupList()
    this.getRuleList()
    listOutexamitem().then((response) => {
      this.relationDialogData.dict = response.rows.map(item => {
        return {
          key: item.itemCode,
          label: `【${item.itemCode}】${item.outExamItemName}`
        }
      })
    })
    getItemGroupList({
      pageNum: 1,
      pageSize: 999
    }).then(res => {
      this.groupDict = res.rows
    })
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  ::v-deep {
    .pagination-container {
      padding: 0 !important;
    }
  }
}

.r-dialog {
  ::v-deep .el-transfer-panel {
    width: 510px;
  }

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

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