<template>
  <ele-modal
    :title="dialogTitle"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
    :maxable="true"
  >
    <el-form
      label-width="115px"
      :model="formData"
      :rules="formRules"
      ref="formRef"
    >
      <el-row style="margin-bottom: 10px">
        <el-col :span="8">
          <el-form-item label="记录规则类型" prop="classify" required>
            <el-select
              style="width: 100%"
              v-model="formData.classify"
              placeholder="请选择"
            >
              <el-option
                v-for="item in recordSheet"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录规则编码" prop="code">
            <el-input
              v-model="formData.code"
              size="small"
              :disabled="true"
              placeholder="系统自动生成"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录规则版本" prop="version">
            <el-input
              :value="versionText"
              size="small"
              disabled
              placeholder="系统自动生成"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="8">
          <el-form-item label="记录规则名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="启用日期" required prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              placeholder="请选择启用日期"
              size="small"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="停用日期" required prop="stopDate">
            <el-date-picker
              v-model="formData.stopDate"
              type="date"
              placeholder="请选择停用日期"
              size="small"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.classify == 3" :span="8">
          <el-form-item label="关联设备" prop="deviceName" required>
            <el-input
              v-model="formData.deviceName"
              placeholder="请选择设备"
              size="small"
              :readonly="true"
            >
              <template #append>
                <el-button size="small" @click="selectDeviceId"
                  >选择设备</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="24">
          <el-form-item label="周期" prop="frequencyValue" required>
            <rule-cycle
              ref="cycleMultipleRef"
              :formData="formData"
              pageType="add"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <ele-pro-table
        ref="table"
        :columns="bankColumns"
        :datasource="formData.recordRulesDetailList"
        :need-page="false"
        row-key="id"
        class="table_list"
      >
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="addRow"
          >
            新建
          </el-button>
        </template>

        <template v-slot:paramType="{ row }">
          <el-select
            v-model="row.paramType"
            placeholder="请选择参数类型"
            size="mini"
            required
          >
            <el-option label="数值" :value="1" />
            <el-option label="选择" :value="2" />
            <el-option label="上下限" :value="3" />
            <el-option label="规格" :value="4" />
            <el-option label="时间" :value="5" />
            <el-option label="范围" :value="6" />
            <el-option label="文本" :value="7" />
            <!-- <el-option label="枚举" :value="8" /> -->
          </el-select>
        </template>

        <template v-slot:paramValue="{ row }">
          <!-- 根据参数类型渲染不同的输入组件 -->
          <el-link
            v-if="formData.classify == '4'"
            :underline="false"
            style="cursor: pointer"
          >
            <div class="ele-cell">
              <div @click="selectProduct(row)">
                {{ row.productName ? row.productName : '请选择产品' }}
              </div>
              <i
                v-if="row.tools.length == 0"
                class="el-icon-arrow-down"
                @click="selectProduct(row)"
              ></i>
              <i v-else class="el-icon-close" @click="clearProduct(row)"></i>
            </div>
          </el-link>
          <el-input
            v-else
            v-model="row.paramValue"
            placeholder="请输入参数内容"
            size="mini"
          ></el-input>
        </template>
        <template v-slot:defaultValue="{ row }">
          <el-row>
            <el-col :span="12">
              <!-- <el-select
                v-if="row.paramType != 7"
                v-model="row.symbol"
                placeholder="请选择"
                size="mini"
              >
                <el-option label=">" value=">"> </el-option>
                <el-option label="<" value="<"> </el-option>
                <el-option label="!=" value="!="> </el-option>
                <el-option label=">=" value=">="> </el-option>
                <el-option label="<=" value="<="> </el-option>
                <el-option label="~~" value="~~"> </el-option>
                <el-option label="+-" value="+-"> </el-option>
                <el-option label="......" value="......"> </el-option>
              </el-select> -->
              <DictSelection
                v-if="row.paramType != 7"
                clearable
                dictName="数学字符"
                v-model="row.symbol"
                placeholder="请选择逻辑"
                size="mini"
              ></DictSelection>
            </el-col>
            <el-col :span="row.paramType != 7 ? 12 : 24">
              <el-input
                v-model="row.defaultValue"
                placeholder="请输入默认值"
                size="mini"
              ></el-input>
            </el-col>
          </el-row>
        </template>
        <template v-slot:maxValue="{ row }">
          <el-input
            v-if="row.paramType == 3 || row.paramType == 6"
            v-model="row.maxValue"
            placeholder="请输入参数上限"
            size="mini"
          ></el-input>
        </template>
        <template v-slot:minValue="{ row }">
          <el-input
            v-if="row.paramType == 3 || row.paramType == 6"
            v-model="row.minValue"
            placeholder="请输入参数下限"
            size="mini"
          ></el-input>
        </template>
        <template v-slot:unitName="{ row }">
          <!-- <el-input
            v-model="row.unitName"
            placeholder="请输入参数单位"
            size="mini"
          ></el-input> -->
          <DictSelection
            v-if="row.paramType != 7"
            dictName="工艺参数单位"
            clearable
            filterable
            v-model="row.unitName"
            size="mini"
          >
          </DictSelection>
        </template>
        <template v-slot:toolName="{ row }">
          <el-link :underline="false" style="cursor: pointer">
            <div class="ele-cell">
              <div @click="handleAdd(row)">
                {{
                  row.tools && row.tools.length > 0
                    ? row.tools.map((i) => i.toolName).join(',')
                    : '请选择'
                }}
              </div>
              <i
                v-if="row.tools.length == 0"
                class="el-icon-arrow-down"
                @click="handleAdd(row)"
              ></i>
              <i v-else class="el-icon-close" @click="clearTool(row)"></i>
            </div>
          </el-link>
        </template>
        <template v-slot:toolCodes="{ row }">
          <el-input
            :value="
              row.tools && row.tools.length > 0
                ? row.tools.map((i) => i.toolCode).join(',')
                : ''
            "
            placeholder="工具自动带出"
            disabled
            size="mini"
          ></el-input>
        </template>
        <template v-slot:remark="{ row }">
          <el-input
            v-model="row.remark"
            placeholder="请输入"
            size="mini"
          ></el-input>
        </template>
        <template v-slot:action="{ row }">
          <el-link
            type="danger"
            :underline="false"
            icon="el-icon-delete"
            @click="deleteRow(row)"
          >
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </el-form>
    <template v-slot:footer>
      <el-button :loading="btnLoading" type="primary" @click="saveAndPublish">
        保存并发布
      </el-button>
      <el-button :loading="btnLoading" type="primary" @click="confirm">
        保存
      </el-button>
      <el-button :loading="btnLoading" @click="handleClose">取消</el-button>
    </template>

    <toolModal ref="toolModalRef" @chooseModal="chooseModal" />

    <MaterialAdd
      ref="deviceSelectDialog"
      selectType="single"
      @chooseEquipment="chooseEquipment"
    />

    <ProductModal
      ref="ProductModalRef"
      @changeProduct="changeProduct"
    ></ProductModal>
  </ele-modal>
</template>

<script>
  import { getByCode } from '@/api/system/dictionary-data';
  // import RuleCycle from '../../matterRules/components/rule-cycle.vue';
  import RuleCycle from './rule-cycle.vue';
  import OperationGuideDialog from '@/views/rulesManagement/matterRules/components/operationGuideDialog.vue';
  import Details from './details.vue';
  import dictMixins from '@/mixins/dictMixins';
  import toolModal from './toolModal.vue';
  import MaterialAdd from '../../components/MaterialAdd.vue';
  import {
    recordrulesSave,
    recordrulesDetailPage,
    recordrulesUpdate,
    recordrulesPublish,
    recordrulesSaveAndPublish,
    recordrulesUpdateVersion,
    recordrulesCyclePage
  } from '@/api/recordrules/index';
  import ProductModal from './ProductModal.vue';

  export default {
    components: {
      OperationGuideDialog,
      RuleCycle,
      Details,
      ProductModal,
      MaterialAdd,
      toolModal
    },
    mixins: [dictMixins],
    computed: {
      bankColumns() {
        return [
          {
            width: 110,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号'
          },
          {
            prop: 'paramType',
            label: '参数类型',
            align: 'center',
            slot: 'paramType',
            minWidth: 110
          },
          {
            prop: 'paramValue',
            label: '参数内容',
            align: 'center',
            slot: 'paramValue',
            minWidth: 180
          },
          {
            prop: 'defaultValue',
            label: '默认值',
            align: 'center',
            slot: 'defaultValue',
            minWidth: 150
          },
          {
            prop: 'maxValue',
            label: '参数上限',
            align: 'center',
            slot: 'maxValue',
            minWidth: 110
          },
          {
            prop: 'minValue',
            label: '参数下限',
            align: 'center',
            slot: 'minValue',
            minWidth: 110
          },
          {
            prop: 'unitName',
            label: '参数单位',
            align: 'center',
            slot: 'unitName',
            minWidth: 110
          },
          {
            prop: 'toolName',
            label: '工具名称',
            align: 'center',
            slot: 'toolName',
            minWidth: 110
          },
          {
            prop: 'toolCodes',
            label: '工具编码',
            align: 'center',
            slot: 'toolCodes',
            minWidth: 110
          },
          {
            prop: 'remark',
            label: '备注',
            align: 'center',
            slot: 'remark',
            minWidth: 110
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 110,
            align: 'center',
            resizable: false,
            slot: 'action'
          }
        ];
      },
      versionText() {
        return this.formData.version
          ? `V${this.formData.version.toFixed(1)}`
          : 'V1.0';
      }
    },
    data() {
      return {
        dialogTitle: '',
        visible: false,
        formData: {
          id: null,
          classify: null,
          deviceId: null,
          deviceName: '',
          frequencyUnit: 2,
          frequencyValue: null,
          name: '',
          recordRulesDetailList: [
            {
              id: 0,
              defaultValue: '',
              maxValue: null,
              minValue: null,
              paramType: null,
              paramValue: null,
              remark: '',
              symbol: null,
              tools: [],
              unitName: null,
              productName: '',
              productCode: ''
            }
          ],
          recordRulesCycleList: [],
          startDate: null,
          stopDate: null,
          version: 1,
          code: '',
          fromId: null
        },
        formRules: {
          name: [
            { required: true, message: '请输入规则名称', trigger: 'blur' }
          ],
          frequencyValue: [
            { required: true, message: '请选择周期', trigger: 'blur' },
            { required: true, message: '请选择周期', trigger: 'change' }
          ],
          frequencyUnit: [
            { required: true, message: '请选择频率单位', trigger: 'change' }
          ],
          classify: [
            { required: true, message: '请选择规则类型', trigger: 'change' }
          ],
          // startDate 启用日期要大于当前时间
          // stopDate 停用时间要大于当前时间并且大于启用日期
          startDate: [
            { required: true, message: '请选择启用日期', trigger: 'blur' },
            { required: true, message: '请选择启用日期', trigger: 'change' },
            { validator: this.validateStartDate, trigger: 'change' }
          ],
          stopDate: [
            { required: true, message: '请选择停用时间', trigger: 'change' },
            { validator: this.validateStopDate, trigger: 'change' }
          ],
          deviceName: [
            { required: true, message: '请输入选择设备', trigger: 'blur' }
          ]
        },
        recordSheet: [], // 记录表
        current: {},
        dataIndex: null,
        showEdit: false,
        btnLoading: false,
        currentRow: null
      };
    },
    mounted() {
      this.getByCodeData();
    },
    methods: {
      open(row, type, title) {
        this.visible = true;
        this.dialogTitle = title;
        this.type = type;
        console.log('type', type, row);

        if (type == 'edit') {
          this.$util.assignObject(this.formData, row);

          this.formData.startDate = new Date(row.startDate);
          this.formData.stopDate = new Date(row.stopDate);
          this.formData.classify = this.formData.classify + '';

          this.recordrulesDetailPage(row);
          this.recordrulesCyclePage(row);

          console.log('this.formData', this.formData, this.formData.version);
        }

        if (type == 'clone') {
          this.$util.assignObject(this.formData, row);

          this.formData.name = this.formData.name + '-副本';
          this.formData.version += 1;

          this.formData.fromId = row.id;
          this.formData.id = null;
          this.formData.startDate = new Date(row.startDate);
          this.formData.stopDate = new Date(row.stopDate);
          this.formData.classify = this.formData.classify + '';

          this.recordrulesDetailPage(row);
          this.recordrulesCyclePage(row);
        }

        if (type == 'add') {
          this.formData.version = 1;

          // 停用日期 默认为 2099-12-31
          this.formData.stopDate = new Date('2099-12-31 00:00:00');
        }
      },
      async getByCodeData() {
        let res = await getByCode('record_sheet');
        let list = res.data.map((item) => {
          let values = Object.keys(item);
          return {
            value: values[0],
            label: item[values[0]]
          };
        });
        this.recordSheet = list;
      },
      itemDel(index) {
        this.formData.recordRulesDetailList.splice(index, 1);
      },
      /* 打开操作手册编辑款 */
      openOperationGuideDialogDialog(row, index) {
        this.$refs.operationGuideDialog.open(row, index);
      },
      handleClose() {
        this.visible = false;
        this.$refs['formRef'].resetFields();
        // 清空表单数据
        this.formData = {
          id: null,
          classify: null,
          deviceId: null,
          deviceName: '',
          frequencyUnit: null,
          frequencyValue: null,
          name: '',
          recordRulesDetailList: [
            {
              id: 0,
              defaultValue: '',
              maxValue: null,
              minValue: null,
              paramType: null,
              paramValue: null,
              remark: '',
              symbol: null,
              toolCodes: null,
              tools: [],
              unitName: null,
              productName: '',
              productCode: ''
            }
          ],
          recordRulesCycleList: [],
          startDate: null,
          stopDate: null,
          version: 1,
          code: '',
          fromId: null
        };
      },
      // 保存
      confirm() {
        console.log('this.formData', this.formData);

        // 验证表单规则
        this.$refs.formRef.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          if (this.formData.recordRulesDetailList.length == 0) {
            return this.$message.warning('至少条件一条规则项');
          }

          try {
            this.btnLoading = true;

            this.formData.recordRulesCycleList =
              this.$refs.cycleMultipleRef.recordRulesCycleList.map(
                (i, index) => {
                  return { ...i, sortNum: index + 1 };
                }
              );

            const body = { ...this.formData };

            body.startDate = this.$util.toDateString(
              body.startDate,
              'yyyy-MM-dd HH:mm:ss'
            );

            body.stopDate = this.$util.toDateString(
              body.stopDate,
              'yyyy-MM-dd HH:mm:ss'
            );

            if (this.type == 'add') {
              await recordrulesSave(body);
            } else if (this.type == 'clone') {
              await recordrulesUpdateVersion(body);
            } else {
              // 编辑
              body.fromId = null;
              await recordrulesUpdate(body);
            }

            this.btnLoading = false;
            this.$message.success('操作成功');

            this.handleClose();
            this.$emit('reload');
          } catch (error) {
            this.btnLoading = false;
          }
        });
      },
      // 保存并发布
      saveAndPublish() {
        // 验证表单规则
        this.$refs.formRef.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          if (this.formData.recordRulesDetailList.length == 0) {
            return this.$message.warning('至少条件一条规则项');
          }

          try {
            this.btnLoading = true;
            this.formData.recordRulesCycleList =
              this.$refs.cycleMultipleRef.recordRulesCycleList.map(
                (i, index) => {
                  return { ...i, sortNum: index + 1 };
                }
              );

            const body = { ...this.formData };

            body.startDate = this.$util.toDateString(
              body.startDate,
              'yyyy-MM-dd HH:mm:ss'
            );

            body.stopDate = this.$util.toDateString(
              body.stopDate,
              'yyyy-MM-dd HH:mm:ss'
            );

            await recordrulesSaveAndPublish(body);

            this.btnLoading = false;
            this.$message.success('操作成功');

            this.handleClose();
            this.$emit('reload');
          } catch (error) {
            this.btnLoading = false;
          }
        });
      },
      // startDate 启用日期要大于当前时间
      validateStartDate(rule, value, callback) {
        const startDate = this.formData.startDate;
        if (!startDate) {
          return callback(new Error('启用日期不能为空'));
        }

        // 启用日期大于等于今天
        const today = new Date();
        today.setHours(0, 0, 0, 0); // 设置为当天的开始时间
        if (new Date(startDate) < today) {
          return callback(new Error('启用日期必须大于等于当前日期'));
        }

        callback();
      },
      // stopDate 停用时间要大于当前时间并且大于启用日期
      validateStopDate(rule, value, callback) {
        const startDate = this.formData.startDate;
        const stopDate = this.formData.stopDate;
        if (
          stopDate &&
          startDate &&
          new Date(stopDate) <= new Date(startDate)
        ) {
          return callback(new Error('停用时间必须大于启用日期'));
        }

        callback();
      },
      // 去选择设备
      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 || '';
      },
      // 添加
      addRow() {
        this.formData.recordRulesDetailList.push({
          id: new Date().getTime(),
          defaultValue: '',
          maxValue: null,
          minValue: null,
          paramType: null,
          paramValue: null,
          remark: '',
          symbol: null,
          tools: [],
          unitName: null,
          productName: '',
          productCode: ''
        });
      },
      deleteRow(row) {
        const index = this.formData.recordRulesDetailList.indexOf(row);
        if (index !== -1) {
          this.formData.recordRulesDetailList.splice(index, 1);
        }
      },
      handleAdd(row) {
        this.currentRow = row;
        this.$refs.toolModalRef.open(row.toolCodes);
      },
      chooseModal(data) {
        console.log('data', data);
        this.currentRow.tools = data.map((i) => {
          return {
            toolCode: i.code,
            toolName: i.name
            // rulesDetailId: this.currentRow.id,
            // rulesId: this.formData.id
          };
        });
      },
      // 规则明细表
      async recordrulesDetailPage(row) {
        const { list } = await recordrulesDetailPage({
          // deptId: row.deptId,
          pageNum: 1,
          rulesId: row.id,
          size: 9999
        });
        console.log('list 数据', list);
        this.formData.recordRulesDetailList = list;
      },
      // 清空工具
      clearTool(row) {
        row.tools = [];
      },
      // 查询 recordrulesCyclePage
      async recordrulesCyclePage(row) {
        const { list } = await recordrulesCyclePage({
          pageNum: 1,
          size: 9999,
          recordRulesId: row.id,
          orderBy: 'descending'
        });
        console.log('list 周期数据', list);
        this.formData.recordRulesCycleList = list;
        this.$nextTick(() => {
          this.$refs.cycleMultipleRef.setRecordRulesCycleList(list);
        });
      },
      // 去选择产品
      selectProduct(row) {
        this.currentRow = row;
        this.$refs.ProductModalRef.open();
      },
      // 选择产品
      changeProduct(current) {
        console.log('current', current);
        this.currentRow.productName = current.name;
        this.currentRow.productCode = current.code;
      },
      // 清空产品
      clearProduct(row) {
        row.productName = '';
        row.productCode = '';
      }
    }
  };
</script>

<style scoped lang="scss">
  .operationGuide_box {
    width: 100%;
    height: 48px;
    display: flex;
    overflow: hidden;
    cursor: pointer;
    box-sizing: border-box;
    padding: 5px 10px;

    .left_content {
      width: 50%;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #c0c4cc;
      border-radius: 10px;
      margin-right: 10px;
      overflow-y: auto;
    }
    .right_content {
      flex: 1;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #c0c4cc;
      border-radius: 10px;
      overflow-y: auto;
    }
  }

  ::v--deep .table_list {
    .el-form-item {
      .el-form-item__content {
        margin-left: 0;
      }
    }
  }
</style>
