<template>
  <ele-modal
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="title"
    @update:visible="updateVisible"
    :maxable="true"
    :before-close="handleClose"
    width="800px"
  >
    <el-form
      :model="formData"
      v-loading="dialogLoading"
      ref="formRef"
      label-width="120px"
      :rules="rules"
      :disabled="type == 'details'"
    >
      <el-form-item label="类型" required prop="itemType">
        <DictSelection
          dictName="记录规则事项类型"
          clearable
          v-model="formData.itemType"
          @change="itemTypeChange"
          :isProhibit="type == 'edit'"
        >
        </DictSelection>
      </el-form-item>

      <el-form-item label="执行方式" required prop="executeMethod">
        <!-- <DictSelection
          dictName="记录规则执行方式"
          clearable
          v-model="formData.executeMethod"
        >
        </DictSelection> -->
        <el-select v-model="formData.executeMethod" style="width: 100%">
          <el-option
            v-for="item in executeMethodDict"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="formData.itemType == '3'"
        label="关联任务"
        prop="itemTaskName"
      >
        <!-- 下拉选择 -->
        <!-- <el-select
          placeholder="请选择关联任务"
          filterable
          clearable
          style="width: 100%"
          v-model="formData.taskId"
        >
          <el-option
            v-for="task in []"
            :key="task.id"
            :label="task.name"
            :value="task.id"
          />
        </el-select> -->
        <el-input
          v-model="formData.itemTaskName"
          placeholder="请输入任务名称"
          size="small"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="formData.itemType == '2' && formData.executeMethod == '2'"
        label="关联记录规则"
        required
        prop="rulesName"
      >
        <div class="mask-box" @click="selectReleaseId">
          <el-input
            v-model="formData.rulesName"
            placeholder="请选择记录规则名称"
            size="small"
            :readonly="true"
          >
            <template #append>
              <el-button size="small">选择规则</el-button>
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item
        v-if="formData.itemType == '2' && formData.executeMethod == '1'"
        label="关联记录计划"
        required
        prop="planConfigName"
      >
        <div class="mask-box" @click="openSelectPlanRules">
          <el-input
            v-model="formData.planConfigName"
            placeholder="请选择记录计划配置"
            size="small"
            :readonly="true"
          >
            <template #append>
              <el-button size="small">记录计划配置</el-button>
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item
        v-if="formData.itemType == '1'"
        label="关联计划规则"
        required
        prop="planConfigName"
      >
        <div class="mask-box" @click="selectRulesId">
          <el-input
            v-model="formData.planConfigName"
            placeholder="请选择设备有关计划规则，巡点检规则"
            size="small"
            :readonly="true"
          >
            <template #append>
              <el-button size="small">选择规则</el-button>
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item
        v-if="formData.executeMethod == '1'"
        label="查询范围"
        required
        prop="dayRange"
      >
        <el-select v-model="formData.dayRange" style="width: 100%">
          <el-option label="当日" :value="1"></el-option>
          <el-option label="3日内" :value="3"></el-option>
          <el-option label="7日内" :value="7"></el-option>
          <el-option label="15日内" :value="15"></el-option>
          <el-option label="30日内" :value="30"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template v-slot:footer>
      <el-button type="primary" @click="confirm"> 确定 </el-button>

      <el-button @click="handleClose">取消</el-button>
    </template>

    <material-add
      ref="deviceSelectDialog"
      selectType="single"
      @chooseEquipment="chooseEquipment"
      :multiple="false"
    ></material-add>

    <selectReleaseRules
      ref="selectReleaseRulesRef"
      @chooseRules="chooseReleaseRules"
      :notProduceTaskConfig="notProduceTaskConfig"
    ></selectReleaseRules>

    <selectPlanRules
      ref="selectPlanRulesRef"
      @chooseRules="choosePlanRules"
    ></selectPlanRules>

    <selectRecordPlan
      ref="selectRecordPlanRef"
      @chooseRules="chooseRecordPlan"
    ></selectRecordPlan>
  </ele-modal>
</template>

<script>
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import dictMixins from '@/mixins/dictMixins';
  import rules from '@/components/bpmnProcessDesigner/src/modules/rules';
  import MaterialAdd from '@/views/rulesManagement/components/MaterialAdd.vue';
  import selectMatterRules from '@/components/selectMatterRules/select-matter-rules.vue';
  import selectReleaseRules from '@/components/selectReleaseRules/select-release-rules.vue';
  import selectPlanRules from '@/components/selectPlanRules/selectPlanRules.vue';
  import selectRecordPlan from '@/components/selectRecordPlan/selectRecordPlan.vue';

  export default {
    name: 'UserSettingMatter',
    mixins: [dictMixins, tableColumnsMixin],
    emits: ['addMatter', 'editMatter'],
    props: {
      // 记录规则 NotProduceTaskConfig bool 是否排除已配置的记录规则 过程控制传true
      notProduceTaskConfig: {
        type: Boolean,
        default: false
      }
    },
    components: {
      MaterialAdd,
      selectMatterRules,
      selectReleaseRules,
      selectPlanRules,
      selectRecordPlan
    },
    computed: {
      executeMethodDict() {
        const list = this.getDictListByName('记录规则执行方式') || [];

        if (this.formData.itemType == '1') {
          // 过程控制 只能选择按事项执行
          return list.map((item) => {
            if (item.label == '任务驱动' || item.label == '表单填写') {
              item.disabled = true;
            } else {
              item.disabled = false;
            }
            return item;
          });
        }

        if (this.formData.itemType == '2') {
          // 过程控制 只能选择按事项执行
          return list.map((item) => {
            if (item.label == '任务驱动') {
              item.disabled = true;
            } else {
              item.disabled = false;
            }
            return item;
          });
        }

        return list.map((item) => {
          if (item.label != '任务驱动') {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          return item;
        });
      }
    },
    data() {
      const formBaseData = {
        id: null,
        // 设备id
        deviceId: null,
        //设备名称
        deviceName: '',
        // 记录规则执行方式，参考字典项：produce_task_config_execute_method
        executeMethod: '2',
        // 记录规则事项类型，参考字典项：record_rules_item_type
        itemType: '2',
        // 工序ID
        produceTaskId: null,
        // 记录规则报工类型，参考字典项：record_rules_report_work_type
        reportWorkType: null,
        // 规则id，包括事项规则id，记录规则id，根据事项类型区分
        rulesId: null,
        // 	规则名称
        rulesName: '',
        // 任务id
        taskId: null,
        itemTaskName: '',
        // 是否执行中
        isUsing: 0,
        recordRulesClassify: '', // 记录规则分类
        planConfigId: null, // 计划配置id
        planConfigName: '', // 计划配置名称
        planConfigCode: '', // 计划配置名称
        dayRange: 1 // 查询范围
      };

      return {
        visible: false,
        type: 'add', // add新增 edit编辑 details 详情
        formBaseData,
        formData: JSON.parse(JSON.stringify(formBaseData)),
        // 表单验证规则
        rules: {
          // 验证类型、执行方式、设备、关联事项规则
          executeMethod: [
            { required: true, message: '请选择执行方式', trigger: 'change' }
          ],
          itemType: [
            { required: true, message: '请选择事项类型', trigger: 'change' },
            { required: true, message: '请选择事项类型', trigger: 'blur' }
          ],
          deviceName: [
            { required: true, message: '请选择设备', trigger: 'change' },
            { required: true, message: '请选择设备', trigger: 'blur' }
          ],
          rulesName: [
            {
              required: true,
              message: '请选择关联事项规则',
              trigger: 'change'
            },
            { required: true, message: '请选择关联事项规则', trigger: 'blur' }
          ],
          planConfigName: [
            {
              required: true,
              message: '请选择关联计划规则',
              trigger: 'change'
            },
            { required: true, message: '请选择关联计划规则', trigger: 'blur' }
          ],
          itemTaskName: [
            {
              required: true,
              message: '请输入关联任务名称',
              trigger: 'blur'
            },
            { required: true, message: '请输入关联任务名称', trigger: 'change' }
          ],
          rulesId: [
            {
              required: true,
              message: '请选择关联规则',
              trigger: 'change'
            },
            { required: true, message: '请选择关联规则', trigger: 'blur' }
          ],
          dayRange: [
            {
              required: true,
              message: '请选择查询范围',
              trigger: 'change'
            },
            { required: true, message: '请选择查询范围', trigger: 'blur' }
          ]
        },
        dialogLoading: false,
        title: '新增事项',
        // 选择的规则
        ruleInfo: null
      };
    },
    methods: {
      itemTypeChange() {
        this.formData.executeMethod = this.formData.itemType;
        this.formData.rulesId = null;
        this.formData.rulesName = '';
        this.formData.planConfigId = null;
        this.formData.planConfigName = '';
        this.formData.planConfigCode = '';

        this.$nextTick(() => {
          this.$refs.formRef.clearValidate();
        });
      },
      updateVisible(val) {
        this.visible = val;
      },
      openAdd(reportWorkType, produceTaskId) {
        this.type = 'add';
        this.title = '新增事项';
        this.visible = true;
        this.formData.reportWorkType = reportWorkType || '';
        this.formData.produceTaskId = produceTaskId || '';
        console.log(
          'this.formData.reportWorkType',
          this.formData.reportWorkType
        );
        console.log('this.formData.produceTaskId', this.formData.produceTaskId);
        if (reportWorkType === '2') {
          // 过程控制
          this.formData.itemType = '2';
          this.formData.executeMethod = '2';
        }
      },
      openEdit(row, type = 'edit') {
        console.log('type', type);
        this.title = type == 'edit' ? '编辑事项' : '事项详情';
        console.log('row', row);
        this.type = type;
        this.visible = true;
        this.$util.assignObject(this.formData, row);
        this.formData.executeMethod = row.executeMethod + '';
        this.formData.itemType = row.itemType + '';
        this.formData.reportWorkType = row.reportWorkType + '';
        this.formData.dayRange = row.dayRange;
        console.log('this.formData', this.formData);
      },
      // 去选择设备
      selectDeviceId() {
        this.$refs.deviceSelectDialog.open([]);
      },
      chooseEquipment(data, index, categoryId) {
        console.log('data', data, index, categoryId);
        this.formData.deviceId = data?.id || null;
        this.formData.deviceName = data?.name || '';
      },
      // 去选择计划规则
      selectRulesId() {
        if (this.type == 'details') {
          return;
        }
        this.$refs.selectPlanRulesRef.open();
      },
      confirm() {
        console.log('this.formData', this.formData);

        if (this.formData.isUsing) {
          this.$message.warning('当前事项正在执行中，无法修改');
          return;
        }

        // 验证表单
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            if (this.type == 'add') {
              this.$emit('addMatter', this.formData, this.ruleInfo);
            } else {
              this.$emit('editMatter', this.formData, this.ruleInfo);
            }
            this.handleClose();
          }
        });
      },
      // 选择规则
      chooseRules(rules) {
        console.log('rules', rules);
        this.formData.rulesId = rules[0]?.id || null;
        this.formData.rulesName = rules[0]?.name || '';
      },
      // 关闭清空formData
      handleClose() {
        this.formData = JSON.parse(JSON.stringify(this.formBaseData));
        this.$nextTick(() => {
          this.$refs.formRef.clearValidate();
          this.visible = false;
        });
      },
      // 去选择记录规则
      selectReleaseId() {
        if (this.type == 'details') {
          return;
        }

        this.$refs.selectReleaseRulesRef.open(
          this.formData.reportWorkType,
          this.formData.produceTaskId
        );
      },
      // 选择记录规则
      chooseReleaseRules(rules) {
        console.log('rules', rules);

        this.ruleInfo = rules;
        this.formData.rulesId = rules.id || null;
        this.formData.rulesName = rules.name || '';
        this.formData.recordRulesClassify = rules.classify;
      },
      // 打开选择计划规则
      openSelectPlanRules() {
        if (this.type == 'details') {
          return;
        }
        this.$refs.selectPlanRulesRef.open();
      },
      // 选择计划规则
      choosePlanRules(rules) {
        console.log('rules', rules);
        this.ruleInfo = rules;
        this.formData.planConfigId = rules.id || null;
        this.formData.planConfigName = rules.name || '';
        this.formData.planConfigCode = rules.code || '';
      },
      // 选择记录计划配置
      openSelectPlanRules() {
        if (this.type == 'details') {
          return;
        }
        this.$refs.selectRecordPlanRef.open();
      },
      // 选择记录计划配置
      chooseRecordPlan(rules) {
        console.log('rules', rules);
        this.formData.planConfigId = rules.id || null;
        this.formData.planConfigName = rules.name || '';
        this.formData.planConfigCode = rules.code || '';
      }
    }
  };
</script>

<style scoped lang="scss">
  .mask-box {
    &::after {
      content: '';
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0);
      cursor: pointer;
    }
  }
</style>
