<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"
    >
      <el-form-item label="类型" required prop="itemType">
        <DictSelection
          dictName="记录规则事项类型"
          clearable
          v-model="formData.itemType"
          @change="itemTypeChange"
        >
        </DictSelection>
      </el-form-item>

      <el-form-item label="执行方式" required prop="executeMethod">
        <DictSelection
          dictName="记录规则执行方式"
          clearable
          v-model="formData.executeMethod"
          isProhibit
        >
        </DictSelection>
      </el-form-item>

      <el-form-item
        v-if="formData.itemType == '1'"
        label="选择设备"
        required
        prop="deviceName"
      >
        <div class="mask-box" @click="selectDeviceId">
          <el-input
            v-model="formData.deviceName"
            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 == '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'"
        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 == '1'"
        label="关联事项规则"
        required
        prop="rulesId"
      >
        <div class="mask-box" @click="selectRulesId">
          <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>

    <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"
    ></material-add>

    <selectMatterRules
      ref="selectMatterRulesRef"
      @chooseRules="chooseRules"
      :filterType="[1, 2, 5]"
    ></selectMatterRules>

    <selectReleaseRules
      ref="selectReleaseRulesRef"
      @chooseRules="chooseReleaseRules"
      :notProduceTaskConfig="notProduceTaskConfig"
    ></selectReleaseRules>
  </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';

  export default {
    name: 'UserSettingMatter',
    mixins: [dictMixins, tableColumnsMixin],
    emits: ['addMatter', 'editMatter'],
    props: {
      // 记录规则 NotProduceTaskConfig bool 是否排除已配置的记录规则 过程监测传true
      notProduceTaskConfig: {
        type: Boolean,
        default: false
      }
    },
    components: {
      MaterialAdd,
      selectMatterRules,
      selectReleaseRules
    },
    data() {
      const formBaseData = {
        id: null,
        // 设备id
        deviceId: null,
        //设备名称
        deviceName: '',
        // 记录规则执行方式，参考字典项：record_rules_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
      };

      return {
        visible: false,
        type: 'add', // add新增 edit编辑
        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' }
          ],
          itemTaskName: [
            {
              required: true,
              message: '请输入关联任务名称',
              trigger: 'blur'
            },
            { required: true, message: '请输入关联任务名称', trigger: 'change' }
          ],
          rulesId: [
            {
              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.$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) {
        this.title = '编辑事项';
        console.log('row', row);
        this.type = 'edit';
        this.visible = true;
        this.$util.assignObject(this.formData, row);
        this.formData.executeMethod = row.executeMethod + '';
        this.formData.itemType = row.itemType + '';
        this.formData.reportWorkType = row.reportWorkType + '';
        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[0]?.id || null;
        this.formData.deviceName = data[0]?.name || '';
        if (this.rules && this.rules.length > 1) {
          // 提示用户选择的规则有多个事项规则
          this.$message.warning('所选设备包含多个设备，请注意选择');
        }
      },
      // 去选择事项规则
      selectRulesId() {
        this.$refs.selectMatterRulesRef.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() {
        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 || '';
      }
    }
  };
</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>
