<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"
    append-to-body
    destroy-on-close
  >
    <el-form
      label-width="115px"
      :model="formData"
      :rules="formRules"
      ref="formRef"
      v-loading="loading"
      :disabled="type == 'detail'"
    >
      <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"
              :disabled="true"
              placeholder="系统自动生成"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录规则版本">
            <el-input
              :value="versionText"
              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="请输入"></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="请选择启用日期"
              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="请选择停用日期"
              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="请选择设备"
              :readonly="true"
            >
              <template #append>
                <el-button @click="selectDeviceId">选择设备</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="8">
          <el-form-item label="模块分类" required prop="reportWorkType">
            <dict-selection
              v-model="formData.reportWorkType"
              dictName="记录规则报工类型"
              placeholder="请选择模块"
              :clearable="false"
            ></dict-selection>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.reportWorkType == 2" :span="8">
          <el-form-item label="关联工序">
            <el-input
              v-model="formData.produceTaskConfigBatchSavePo.produceTaskName"
              @click.native="openProduceTaskDialog"
              readonly
              placeholder="关联工序"
              clearable
            >
              <i
                v-if="formData.produceTaskConfigBatchSavePo.produceTaskName"
                slot="suffix"
                class="el-input__icon el-icon-close"
                size="24"
                @click.stop="clearProductTask"
              ></i>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.reportWorkType == 2" :span="8">
          <el-form-item label="是否有执行方式" label-width="130px">
            <el-radio-group
              v-model="formData.isExecuteMethod"
              @change="executeMethodChange"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        v-if="
          formData.reportWorkType != 0 &&
          formData.produceTaskConfigBatchSavePo.produceTaskId
        "
        style="margin-bottom: 10px"
      >
        <el-col
          v-if="
            formData.reportWorkType == 2 &&
            formData.produceTaskConfigBatchSavePo.produceTaskId
          "
          :span="8"
        >
          <el-form-item
            label="关联产品方式"
            required
            prop="relateProductMethod"
          >
            <el-select
              v-model="formData.relateProductMethod"
              placeholder="请选择关联产品方式"
              style="width: 100%"
            >
              <el-option
                v-for="item in relateProductMethodOpeions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="formData.relateProductMethod == 1" :span="8">
          <el-form-item label="关联产品分类" required prop="categoryLevels">
            <ele-tree-select
              multiple
              clearable
              :data="productCategory"
              v-model="formData.categoryLevels"
              placeholder="请选择关联产品分类"
              default-expand-all
              labelKey="name"
              valueKey="id"
            />
          </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="type"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <template v-if="formData.relateProductMethod == 2">
        <div style="margin-bottom: 20px">
          <header-title title="关联产品">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="relateProductSelect"
            >
              添加产品
            </el-button>
          </header-title>

          <ele-pro-table
            ref="productTableRef"
            :columns="productColumns"
            :datasource="formData.categories"
            :needPage="false"
            row-key="id"
          >
            <template v-slot:action="{ row }">
              <el-link
                type="danger"
                :underline="false"
                icon="el-icon-delete"
                @click="productColumnsDeleteRow(row)"
              >
                删除
              </el-link>
            </template>
          </ele-pro-table>
        </div>
      </template>

      <header-title title="规则明细">
        <el-button
          v-if="formData.isExecuteMethod"
          type="primary"
          @click="addExecuteMethod"
          >添加执行方式</el-button
        >
      </header-title>

      <el-tabs
        v-if="formData.isExecuteMethod"
        v-model="formData.executeMethodTitle"
        type="card"
        closable
        @tab-remove="deleteExecuteMethod"
      >
        <el-tab-pane
          :key="item"
          v-for="item in formData.executeMethodList"
          :label="item"
          :name="item"
        >
          {{ item.content }}
        </el-tab-pane>
      </el-tabs>

      <ele-pro-table
        ref="table"
        :columns="bankColumns"
        :datasource="detailsList"
        :need-page="false"
        row-key="id"
        class="table_list"
        :cache-key="cacheKeyUrl"
      >
        <template v-slot:toolbar>
          <el-button
            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="selectChooseModalProduct(row)">
                {{ row.productName ? row.productName : '请选择产品' }}
              </div>
              <i
                v-if="row.tools.length == 0"
                class="el-icon-arrow-down"
                @click="selectChooseModalProduct(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"
            type="textarea"
            rows="1"
            autosize
          ></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:executeMethodTitle="{ row }">
          <el-select v-model="row.executeMethodTitle" clearable size="mini">
            <el-option
              v-for="item in formData.executeMethodList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </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
        v-if="type != 'detail'"
        :loading="btnLoading"
        type="primary"
        @click="saveAndPublish"
      >
        保存并发布
      </el-button>
      <el-button
        v-if="type != 'detail'"
        :loading="btnLoading"
        type="primary"
        @click="confirm"
      >
        保存
      </el-button>
      <el-button :loading="btnLoading" @click="handleClose">取消</el-button>
    </template>

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

    <toolModal ref="toolModalTowRef" @chooseModal="chooseModalProduct" />

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

    <ProductModal
      ref="ProductModalRef"
      @changeProduct="changeProduct"
    ></ProductModal>

    <ProductModal
      ref="ProductModalCorrelationRef"
      @changeProduct="changeRelateProduct"
      multiple
    ></ProductModal>

    <processModal
      ref="processModalRef"
      @chooseProcess="processChooseProcess"
    ></processModal>
  </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,
    recordrulesGetById
  } from '@/api/recordrules/index';
  import ProductModal from '@/components/selectProduct/ProductModal.vue';
  import { getTreeByPid } from '@/api/classifyManage';
  import processModal from './processModal.vue';

  export default {
    components: {
      OperationGuideDialog,
      RuleCycle,
      Details,
      ProductModal,
      MaterialAdd,
      toolModal,
      processModal
    },
    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: 261
          },
          {
            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
          },
          {
            prop: 'executeMethodTitle',
            label: '执行方式',
            align: 'center',
            slot: 'executeMethodTitle',
            minWidth: 180
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 110,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ];
      },
      versionText() {
        if (this.type == 'clone') {
          return '系统自动生成';
        }
        return (
          this.formData.bigVersion +
          this.formData.versionMark +
          this.formData.smallVersion
        );
      },
      productColumns() {
        return [
          {
            columnKey: 'index',
            type: 'index',
            width: 45,
            align: 'center',
            reserveSelection: true
          },
          {
            prop: 'code',
            label: '产品编码'
          },
          {
            prop: 'name',
            label: '产品名称',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号'
          },
          {
            prop: 'modelType',
            label: '型号'
          },
          {
            prop: 'measuringUnit',
            label: '计量单位'
          },
          {
            prop: 'packingUnit',
            label: '包装单位'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 110,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ];
      },
      cacheKeyUrl() {
        return `main-permit-add-2510181429-reportWorkType`;
      },
      detailsList() {
        if (this.formData.isExecuteMethod) {
          return this.formData.details.filter(
            (i) => i.executeMethodTitle == this.formData.executeMethodTitle
          );
        } else {
          return this.formData.details;
        }
      }
    },
    data() {
      const formDateBase = {
        id: null,
        classify: null,
        deviceId: null,
        deviceName: '',
        frequencyUnit: 2,
        frequencyValue: null,
        name: '',
        details: [],
        recordRulesCycleList: [],
        startDate: null,
        stopDate: null,
        version: 1,
        code: '',
        fromId: null,
        // 模块分类 参考字典项：record_rules_report_work_type
        reportWorkType: '1',
        // 关联产品方式，0-不关联，1-关联分类，2-关联产品
        relateProductMethod: 0,
        // 关联分类
        categoryLevels: [],
        // 关联产品
        categories: [],
        // 执行方式
        isExecuteMethod: 0,
        produceTaskConfigs: [],
        // 关联工序
        produceTaskConfigBatchSavePo: {
          addPOs: [],
          deletedIds: [],
          produceTaskId: '',
          produceTaskName: '',
          updatePOs: []
        },
        // 执行方式列表
        executeMethodList: [],
        // 执行方式 活跃项
        executeMethodTitle: '',
        bigVersion: '',
        versionMark: '',
        smallVersion: ''
      };

      return {
        dialogTitle: '',
        visible: false,
        formDateBase,
        formData: JSON.parse(JSON.stringify(formDateBase)),
        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' }
          ],
          reportWorkType: [
            { required: true, message: '请选择模块分类', trigger: 'change' },
            { required: true, message: '请选择模块分类', trigger: 'blur' }
          ],
          categoryLevels: [
            {
              required: true,
              message: '请选择关联产品分类',
              trigger: 'change'
            },
            { required: true, message: '请选择关联产品分类', trigger: 'blur' }
          ]
        },
        recordSheet: [], // 记录表
        current: {},
        dataIndex: null,
        showEdit: false,
        btnLoading: false,
        currentRow: null,
        type: '',
        relateProductMethodOpeions: [
          { label: '不关联', value: 0 },
          // { label: '关联分类', value: 1 },
          { label: '关联产品', value: 2 }
        ],
        // 产品分类
        productCategory: [],
        loading: false
      };
    },
    mounted() {
      this.getByCodeData();
      this.getProductCategory();
      console.log('this.formData 2233', this.formData);
    },
    methods: {
      open(row, type, title) {
        this.dialogTitle = title;
        this.type = type;
        console.log('type', type, row);

        if (type == 'edit' || type == 'detail') {
          this.getDetils(row.id);
        }

        if (type == 'clone') {
          this.getDetils(row.id);
        }

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

          // 启用日期 默认为 今天
          this.formData.startDate = new Date();
          // 停用日期 默认为 2099-12-31
          this.formData.stopDate = new Date('2099-12-31 00:00:00');
        }

        this.visible = true;

        console.log('this.formData', this.formData);
      },
      async getDetils(id) {
        this.loading = true;
        try {
          const data = await recordrulesGetById(id);

          if (data.relateProductMethod == 1) {
            data.categoryLevels = data.produceTaskConfigs
              .map((i) => i.categoryLevelId)
              .filter((i) => i != null);
          } else {
            data.categoryLevels = [];
          }

          if (data.relateProductMethod == 2) {
            // 产品
            data.categories = data.produceTaskConfigs.map((i) => {
              return {
                id: i.productId,
                code: i.productCode,
                name: i.productName,
                brandNum: i.brandNum,
                modelType: i.modelType,
                measuringUnit: i.measuringUnit,
                packingUnit: i.packingUnit
              };
            });
          } else {
            data.categories = [];
          }

          data.produceTaskConfigBatchSavePo = {
            addPOs: [],
            deletedIds: [],
            produceTaskId: data.produceTaskConfigs[0]?.produceTaskId,
            produceTaskName: data.produceTaskConfigs[0]?.produceTaskName,
            updatePOs: []
          };

          if (data.isExecuteMethod) {
            data.executeMethodList = Object.keys(data.detailMap).map((i) => {
              return i === '' ? '无执行方式' : i;
            });

            if (data.executeMethodList.includes('无执行方式')) {
              // 将无执行方式 放到第一个
              data.executeMethodList = data.executeMethodList.filter(
                (i) => i !== '无执行方式'
              );
              data.executeMethodList.unshift('无执行方式');
            } else {
              // 添加一个 无执行方式
              data.executeMethodList.unshift('无执行方式');
            }

            data.details = Object.values(data.detailMap)
              .flat()
              .map((i) => {
                if (i.executeMethodTitle == '') {
                  i.executeMethodTitle = '无执行方式';
                }
                return i;
              });
            data.executeMethodTitle = data.executeMethodList[0] || '';
          } else {
            data.executeMethodList = [];
            data.details = data.details || [];
            data.executeMethodTitle = '';
          }

          this.$util.assignObject(this.formData, data);

          this.$nextTick(() => {
            this.$refs.cycleMultipleRef?.setRecordRulesCycleList(
              this.formData.recordRulesCycleList
            );
          });

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

          if (this.type == 'clone') {
            this.formData.name = this.formData.name + '-副本';

            this.formData.fromId = id;
            this.formData.id = null;
          }
          this.loading = false;
        } catch (error) {
          this.loading = false;
        }
      },
      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.details.splice(index, 1);
      },
      /* 打开操作手册编辑款 */
      openOperationGuideDialogDialog(row, index) {
        this.$refs.operationGuideDialog.open(row, index);
      },
      handleClose() {
        // 清空表单数据
        this.formData = JSON.parse(JSON.stringify(this.formDateBase));
        this.$refs['formRef'].resetFields();
        this.visible = false;
      },
      // 保存
      confirm() {
        console.log('this.formData', this.formData);

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

          if (this.formData.isExecuteMethod) {
            // 判断 formData.executeMethodList中的item 是否在details中有一条executeMethodTitle的数据

            if (this.formData.executeMethodList.length == 0) {
              return this.$message.warning(`请添加执行方式`);
            }

            for (const item of this.formData.executeMethodList) {
              const exists = this.formData.details.some(
                (detail) => detail.executeMethodTitle === item
              );
              if (!exists) {
                this.$message.warning(
                  `请为执行方式 "${item}" 添加至少一条规则项`
                );
                return false;
              }
            }
          }

          if (this.formData.relateProductMethod == 2) {
            // 关联产品
            if (this.formData.categories.length == 0) {
              return this.$message.warning('请选择关联产品');
            }
          }

          try {
            this.btnLoading = true;

            const body = this.formatBody();

            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.details.length == 0) {
            return this.$message.warning('至少条件一条规则项');
          }

          if (this.formData.isExecuteMethod) {
            // 判断 formData.executeMethodList中的item 是否在details中有一条executeMethodTitle的数据

            if (this.formData.executeMethodList.length == 0) {
              return this.$message.warning(`请添加执行方式`);
            }

            for (const item of this.formData.executeMethodList) {
              const exists = this.formData.details.some(
                (detail) => detail.executeMethodTitle === item
              );
              if (!exists) {
                this.$message.warning(
                  `请为执行方式 "${item}" 添加至少一条规则项`
                );
                return false;
              }
            }
          }

          if (this.formData.relateProductMethod == 2) {
            // 关联产品
            if (this.formData.categories.length == 0) {
              return this.$message.warning('请选择关联产品');
            }
          }

          try {
            this.btnLoading = true;

            const body = this.formatBody();

            await recordrulesSaveAndPublish(body);

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

            this.handleClose();
            this.$emit('reload');
          } catch (error) {
            this.btnLoading = false;
          }
        });
      },
      // 数据格式化
      formatBody() {
        this.formData.recordRulesCycleList =
          this.$refs.cycleMultipleRef.recordRulesCycleList
            .map((i) => {
              // 根据月日时分排序计算权重排序
              let sortNum = 0;
              if (i.month) {
                sortNum += i.month * 60 * 24 * 30;
              }
              if (i.day) {
                sortNum += i.day * 60 * 24;
              }
              if (i.hour) {
                sortNum += i.hour * 60;
              }

              if (i.minute) {
                sortNum += i.minute * 1;
              }

              return { ...i, sortNum };
            })
            .sort((a, b) => a.sortNum - b.sortNum)
            .map((i, index) => {
              return { ...i, sortNum: index + 1 };
            });

        const body = JSON.parse(JSON.stringify(this.formData));

        body.details = body.details.map((i) => {
          if (i.executeMethodTitle == '无执行方式') {
            i.executeMethodTitle = '';
          }
          return i;
        });

        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 == 'edit') {
          if (body.produceTaskConfigBatchSavePo.produceTaskId) {
            // 修改工序
            if (body.relateProductMethod == 1) {
              // 分类
              body.categoryLevels.forEach((categoryId) => {
                // 判断是否已经存在
                const exist = body.produceTaskConfigs.find(
                  (i) => i.categoryLevelId == categoryId
                );

                if (!exist) {
                  body.produceTaskConfigBatchSavePo.addPOs.push({
                    executeMethod: 2,
                    itemType: 1,
                    produceTaskId:
                      body.produceTaskConfigBatchSavePo.produceTaskId,
                    produceTaskName:
                      body.produceTaskConfigBatchSavePo.produceTaskName,
                    categoryLevelId: categoryId,
                    reportWorkType: this.formData.reportWorkType
                  });
                }
              });

              // 删除取消的分类
              body.produceTaskConfigs.forEach((config) => {
                if (
                  !body.categoryLevels.includes(config.categoryLevelId) &&
                  config.id
                ) {
                  body.produceTaskConfigBatchSavePo.deletedIds.push(config.id);
                }
              });
            }

            if (body.relateProductMethod == 2) {
              // 产品
              body.categories.forEach((product) => {
                // 判断是否已经存在
                const exist = body.produceTaskConfigs.find(
                  (i) => i.productId == product.id
                );
                if (!exist) {
                  body.produceTaskConfigBatchSavePo.addPOs.push({
                    executeMethod: 2,
                    itemType: 2,
                    produceTaskId:
                      body.produceTaskConfigBatchSavePo.produceTaskId,
                    produceTaskName:
                      body.produceTaskConfigBatchSavePo.produceTaskName,
                    productCode: product.code,
                    productId: product.id || product.productId,
                    productName: product.name || product.productName,
                    reportWorkType: this.formData.reportWorkType
                  });
                }
              });

              // 删除取消的产品
              body.produceTaskConfigs.forEach((config) => {
                const exist = body.categories.find((product) => {
                  return product.id == config.productId;
                });

                if (!exist && config.id) {
                  body.produceTaskConfigBatchSavePo.deletedIds.push(config.id);
                }
              });
            }

            if (body.relateProductMethod == 0) {
              // 不关联产品 但存在工序
              // 判断是否已经存在
              const item = body.produceTaskConfigs.find(
                (i) =>
                  i.produceTaskId ==
                  body.produceTaskConfigBatchSavePo.produceTaskId
              );

              if (item) {
                // 修改
                body.produceTaskConfigBatchSavePo.updatePOs.push({
                  ...item,
                  produceTaskId:
                    body.produceTaskConfigBatchSavePo.produceTaskId,
                  produceTaskName:
                    body.produceTaskConfigBatchSavePo.produceTaskName,
                  reportWorkType: this.formData.reportWorkType
                });
              } else {
                // 新增
                body.produceTaskConfigBatchSavePo.deletedIds =
                  this.formData.produceTaskConfigs.map((i) => i.id);

                body.produceTaskConfigBatchSavePo.addPOs.push({
                  executeMethod: 2,
                  itemType: 2,
                  produceTaskId:
                    body.produceTaskConfigBatchSavePo.produceTaskId,
                  produceTaskName:
                    body.produceTaskConfigBatchSavePo.produceTaskName,
                  reportWorkType: this.formData.reportWorkType
                });
              }
            }
          } else {
            // 删除工序 全删
            body.produceTaskConfigBatchSavePo.deletedIds =
              this.formData.produceTaskConfigs.map((i) => i.id);
          }
        } else {
          // 新增工序
          if (
            body.reportWorkType != 0 &&
            body.produceTaskConfigBatchSavePo.produceTaskId
          ) {
            if (body.relateProductMethod == 1) {
              // 分类
              body.categoryLevels.forEach((categoryId) => {
                body.produceTaskConfigBatchSavePo.addPOs.push({
                  executeMethod: 2,
                  itemType: 1,
                  produceTaskId:
                    body.produceTaskConfigBatchSavePo.produceTaskId,
                  produceTaskName:
                    body.produceTaskConfigBatchSavePo.produceTaskName,
                  categoryLevelId: categoryId,
                  reportWorkType: this.formData.reportWorkType
                });
              });
            }

            if (body.relateProductMethod == 2) {
              // 产品
              body.categories.forEach((product) => {
                body.produceTaskConfigBatchSavePo.addPOs.push({
                  executeMethod: 2,
                  itemType: 2,
                  produceTaskId:
                    body.produceTaskConfigBatchSavePo.produceTaskId,
                  produceTaskName:
                    body.produceTaskConfigBatchSavePo.produceTaskName,
                  productCode: product.code,
                  productId: product.id || product.productId,
                  productName: product.name || product.productName,
                  reportWorkType: this.formData.reportWorkType
                });
              });
            }

            if (body.relateProductMethod == 0) {
              // 不关联
              body.produceTaskConfigBatchSavePo.addPOs.push({
                executeMethod: 2,
                itemType: 2,
                produceTaskId: body.produceTaskConfigBatchSavePo.produceTaskId,
                produceTaskName:
                  body.produceTaskConfigBatchSavePo.produceTaskName,
                reportWorkType: this.formData.reportWorkType
              });
            }
          }

          body.produceTaskConfigBatchSavePo.updatePOs = [];
        }

        return body;
      },
      // 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.details.push({
          id: new Date().getTime(),
          defaultValue: '',
          maxValue: null,
          minValue: null,
          paramType: null,
          paramValue: null,
          remark: '',
          symbol: null,
          tools: [],
          unitName: null,
          productName: '',
          productCode: '',
          executeMethodTitle: this.formData.executeMethodTitle
        });
        console.log('this.formData.details', this.formData.details);
      },
      deleteRow(row) {
        const index = this.formData.details.indexOf(row);
        if (index !== -1) {
          this.formData.details.splice(index, 1);
        }
      },
      // 删除关联产品
      productColumnsDeleteRow(row) {
        this.formData.categories = this.formData.categories.filter((i) => {
          return i.id !== row.id;
        });
      },
      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.details = 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;
      },
      // 选择物品 产品、物料等
      selectChooseModalProduct(row) {
        this.currentRow = row;
        this.$refs.toolModalTowRef.open([], '选择物品');
      },
      chooseModalProduct(current) {
        console.log('current', current);
        this.currentRow.productName = current[0].name;
        this.currentRow.productCode = current[0].code;
        console.log('this.currentRow', this.currentRow);
      },
      // 清空产品
      clearProduct(row) {
        row.productName = '';
        row.productCode = '';
      },
      // 关联产品
      relateProductSelect() {
        this.$refs.ProductModalCorrelationRef.open();
      },
      changeRelateProduct(array) {
        console.log('this.formData.categories ', array);

        const productList = array.filter(
          (i) => !this.formData.categories.some((cat) => cat.id === i.id)
        );

        this.formData.categories = [
          ...this.formData.categories,
          ...productList
        ];
      },
      // 获取产品分类
      async getProductCategory() {
        let { data } = await getTreeByPid(9);
        console.log('产品分类', data);
        this.productCategory = data;
      },
      // 选择工序
      openProduceTaskDialog() {
        if (this.formData.produceTaskConfigs) {
          // 其中包含 isUsing 为 true 则不能修改
          const some = this.formData.produceTaskConfigs.some((i) => i.isUsing);
          if (some) {
            return this.$message.warning(
              '当前规则关联的工序有执行中的记录，不能更改！'
            );
          }
        }
        this.$refs.processModalRef.open();
      },
      // 工序
      processChooseProcess(process) {
        console.log('选择的工序', process);
        this.formData.produceTaskConfigBatchSavePo.produceTaskId = process.id;
        this.formData.produceTaskConfigBatchSavePo.produceTaskName =
          process.name;
      },
      // 添加执行方式
      addExecuteMethod() {
        this.$prompt('', '请输入执行方式', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(({ value }) => {
            if (this.formData.executeMethodList.includes(value)) {
              return this.$message.warning('执行方式已存在！');
            }
            this.formData.executeMethodList.push(value);

            if (this.formData.executeMethodList.length == 1) {
              // 默认高亮
              this.formData.executeMethodTitle = value;
            }
          })
          .catch((err) => {});
      },
      // 删除执行方式
      deleteExecuteMethod(item) {
        // 如果this.formData.details总包含item 则不能删除
        const exists = this.formData.details.some(
          (detail) => detail.executeMethodTitle === item
        );
        if (exists) {
          return this.$message.warning(
            `执行方式 "${item}" 已被规则项使用，不能删除`
          );
        }
        this.formData.executeMethodList =
          this.formData.executeMethodList.filter((i) => i != item);
      },
      // 是否有执行方式改变
      executeMethodChange() {
        if (!this.formData.isExecuteMethod) {
          this.formData.details = this.formData.details.map((i) => {
            return {
              ...i,
              executeMethodTitle: '无执行方式'
            };
          });
        } else {
          if (this.formData.executeMethodList.length == 0) {
            // 添加一个默认执行方式
            this.formData.executeMethodList.push('无执行方式');

            this.formData.details = this.formData.details.map((i) => {
              return {
                ...i,
                executeMethodTitle: '无执行方式'
              };
            });

            this.formData.executeMethodTitle = '无执行方式';
          }
        }
      },
      clearProductTask() {
        // 如果有执行中的记录 则不能清空
        if (
          this.formData.produceTaskConfigs &&
          this.formData.produceTaskConfigs[0] &&
          this.formData.produceTaskConfigs[0].isUsing
        ) {
          return this.$message.warning(
            '当前规则关联的工序有执行中的记录，不能更改！'
          );
        }
        this.formData.produceTaskConfigBatchSavePo.produceTaskId = '';
        this.formData.produceTaskConfigBatchSavePo.produceTaskName = '';
        this.formData.relateProductMethod = 0;
        this.formData.categoryLevels = [];
        this.formData.categories = [];
      }
    }
  };
</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>
