<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>
        <el-col :span="8">
          <el-form-item label="行业类别" prop="industryType">
            <el-select
              v-model="formData.industryType"
              placeholder="请选择行业类别"
              style="width: 100%"
              @change="industryTypeChange"
            >
              <el-option
                v-for="item in industryTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务分类" prop="businessType">
            <el-select
              v-model="formData.businessType"
              placeholder="请选择业务分类"
              style="width: 100%"
              @change="businessTypeChange"
            >
              <el-option
                v-for="item in businessTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模块划分" prop="reportWorkType">
            <el-select
              v-model="formData.reportWorkType"
              placeholder="请选择模块划分"
              style="width: 100%"
              @change="reportWorkTypeChange"
            >
              <el-option
                v-for="item in reportWorkTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="应用场景" prop="classify">
            <el-select
              v-model="formData.classify"
              placeholder="请选择应用场景"
              style="width: 100%"
              @change="classifyChange"
            >
              <el-option
                v-for="item in classifyList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板样式" prop="recordTemplateStyle">
            <el-select
              v-model="formData.recordTemplateStyle"
              placeholder="请选择模板样式"
              style="width: 100%"
            >
              <el-option
                v-for="item in recordTemplateStyleList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </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-col :span="8">
          <el-form-item label="名称"  prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入"
              :disabled="type == 'processEdit'"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="启用日期"
            prop="startDate"
            :rules="
              !qmsReportWorkType.includes(formData.reportWorkType)
                ? [
                    {
                      required: true,
                      message: '请选择启用日期',
                      trigger: 'blur'
                    },
                    {
                      required: true,
                      message: '请选择启用日期',
                      trigger: 'change'
                    },
                    { validator: validateStartDate, trigger: 'change' }
                  ]
                : []
            "
          >
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              placeholder="请选择启用日期"
              style="width: 100%"
              :picker-options="{
                disabledDate: (time) =>
                  time.getTime() < new Date(new Date().toDateString()).getTime()
              }"
              :disabled="type == 'processEdit'"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="停用日期"
            prop="stopDate"
            :rules="
              !qmsReportWorkType.includes(formData.reportWorkType)
                ? [
                    {
                      required: true,
                      message: '请选择停用时间',
                      trigger: 'change'
                    },
                    { validator: validateStopDate, trigger: 'change' }
                  ]
                : []
            "
          >
            <el-date-picker
              v-model="formData.stopDate"
              type="date"
              placeholder="请选择停用日期"
              style="width: 100%"
              :disabled="type == 'processEdit'"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.recordTemplateStyle == '2'" :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-col v-if="formData.reportWorkType == 2" :span="8">
          <el-form-item label="关联工序">
            <el-input
              v-model="formData.produceTaskName"
              @click.native="openProduceTaskDialog"
              readonly
              placeholder="关联工序"
              clearable
              :disabled="type == 'processEdit'"
            >
              <i
                v-if="formData.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="isExecuteMethodChange"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col
          v-if="formData.isExecuteMethod == 1 && formData.reportWorkType == 2"
          :span="8"
        >
          <el-form-item label="执行方式" required prop="executeMethodId">
            <el-select
              v-model="formData.executeMethodId"
              filterable
              placeholder="请选择"
              style="width: 100%"
              @change="executeMethodIdChange"
            >
              <el-option
                v-for="item in executeMethodList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!qmsReportWorkType.includes(formData.reportWorkType)">
        <el-col :span="24">
          <el-form-item label="周期" prop="frequencyValue" required>
            <rule-cycle
              ref="cycleMultipleRef"
              :formData="formData"
              :pageType="type"
              :isBindPlan="type == 'processEdit'"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <header-title
        title="规则明细"
        v-if="!qmsReportWorkType.includes(formData.reportWorkType)"
      >
      </header-title>

      <el-tabs
        v-if="
          formData.recordTemplateStyle == '4' &&
          !qmsReportWorkType.includes(formData.reportWorkType)
        "
        v-model="statisticsType"
        type="card"
      >
        <el-tab-pane
          v-for="i in statisticsTypeList"
          :label="i.label"
          :name="i.value"
          :key="i.value"
        >
        </el-tab-pane>
      </el-tabs>

      <ele-pro-table
        v-if="!qmsReportWorkType.includes(formData.reportWorkType)"
        ref="table"
        :columns="bankColumns"
        :datasource="detialsDatasource"
        :need-page="false"
        row-key="id"
        class="table_list"
        :cache-key="cacheKeyUrl"
      >
        <template v-slot:toolbar>
          <div style="display: flex; align-items: center; gap: 10px">
            <el-button
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="addRow"
            >
              新建
            </el-button>
          </div>
        </template>

        <template v-slot:sortNum="{ row }">
          <el-input-number
            style="width: 80px"
            v-model.number="row.sortNum"
            placeholder="请输入排序"
            size="mini"
            type="number"
            :min="1"
            controls-position="right"
          ></el-input-number>
        </template>

        <template v-slot:paramType="{ row }">
          <el-select
            v-model="row.paramType"
            placeholder="请选择参数类型"
            size="mini"
            @change="paramTypeChange(row)"
          >
            <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-option label="计算" :value="9" />
          </el-select>
        </template>

        <template v-slot:paramValue="{ row }">
          <!-- 根据参数类型渲染不同的输入组件 -->
          <el-link
            v-if="formData.recordTemplateStyle == '3'"
            :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:formula="{ row }">
          <div v-if="row.paramType == 9" class="formula-builder">
            <div class="formula-builder__selects">
              <!-- 选择参数：从已填的非计算参数内容里取 -->
              <el-select
                v-model="row._paramSelect"
                placeholder="选择参数"
                size="mini"
                style="width: 100px; margin-right: 8px; flex-shrink: 0"
                @change="paramSelectChange($event, row)"
              >
                <el-option
                  v-for="item in getSelectOptionsByDetails(row.statisticsType)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <!-- 选择运算符 -->
              <el-select
                v-model="row._opSelect"
                :key="row._opSelect + '_opSelect'"
                placeholder="选择符号"
                size="mini"
                style="width: 100px; flex-shrink: 0"
                @change="opSelectChange($event, row)"
              >
                <el-option
                  v-for="op in opSelectOptions"
                  :key="op"
                  :label="op"
                  :value="op"
                />
              </el-select>

              <!-- 替换或者追加 -->
              <el-select
                v-if="row.activeIndex != undefined"
                v-model="row._replaceOrAppend"
                :key="row._replaceOrAppend + 'row._replaceOrAppend'"
                placeholder="选择"
                size="mini"
                style="width: 80px; margin-left: 8px; flex-shrink: 0"
              >
                <el-option key="append" label="追加" value="append" />
                <el-option key="replace" label="替换" value="replace" />
              </el-select>
            </div>

            <!-- 已组装公式标签展示 -->
            <div
              v-if="row.formulaParts && row.formulaParts.length"
              style="display: inline-flex; flex-wrap: wrap; max-width: 100%"
            >
              <el-tag
                v-for="(p, index) in row.formulaParts"
                :key="index"
                size="mini"
                closable
                :type="row.activeIndex === index ? 'primary' : 'info'"
                @click="formulaPartsTagClick(index, row)"
                @close="tagItemDelete(index, row)"
              >
                {{ p }}
              </el-tag>
            </div>

            <!-- 公式字符串展示（只读） -->
            <el-input
              v-if="row.formulaParts && row.formulaParts.length"
              :value="row.formulaParts.join('')"
              size="mini"
              type="textarea"
              disabled
              placeholder="公式"
              style="margin-top: 6px"
            />
          </div>
        </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
            v-if="type != 'detail'"
            type="danger"
            :underline="false"
            icon="el-icon-delete"
            @click="deleteRow(row)"
          >
            删除
          </el-link>
        </template>
      </ele-pro-table>

      <header-title
        :title="
          formData.reportWorkType == 5
            ? '实验过程'
            : formData.reportWorkType == 6
            ? '工艺要求'
            : formData.reportWorkType == 7
            ? '实验记录'
            : ''
        "
        v-if="qmsReportWorkType.includes(formData.reportWorkType)"
      >
      </header-title>
      <experimentationProcess
        :edit="type!='detail'"
        v-if="qmsReportWorkType.includes(formData.reportWorkType)"
        ref="experimentationProcess"
      ></experimentationProcess>
    </el-form>
    <template v-slot:footer>
      <el-button
        v-if="type != 'detail' && type != 'processEdit'"
        :loading="btnLoading"
        type="primary"
        @click="saveAndPublish"
      >
        保存并发布
      </el-button>
      <el-button
        v-if="type != 'detail' && type != 'processEdit'"
        :loading="btnLoading"
        type="primary"
        @click="confirm"
      >
        保存
      </el-button>
      <el-button
        v-if="type == 'processEdit'"
        :loading="btnLoading"
        type="primary"
        @click="processEditSave"
      >
        保存
      </el-button>
      <el-button :loading="btnLoading" @click="handleClose">取消</el-button>
    </template>

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

    <toolModal
      ref="toolModalTowRef"
      @chooseModal="chooseModalProduct"
      :multiple="false"
    />

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

    <ProductModal
      ref="ProductModalRef"
      @changeProduct="changeProduct"
    ></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,
    recordrulesTypePage
  } from '@/api/recordrules/index';
  import ProductModal from '@/components/selectProduct/ProductModal.vue';
  import { getTreeByPid } from '@/api/classifyManage';
  import processModal from './processModal.vue';
  import experimentationProcess from './experimentationProcess.vue';
  import ProductModalCorrelation from './ProductModal.vue';
  import { recordrulesexecutemethodPage } from '@/api/recordrulesexecutemethod/index';
  import { businessTypeList } from '@/views/regulationManagement/components/util';

  export default {
    mixins: [dictMixins],
    components: {
      OperationGuideDialog,
      RuleCycle,
      Details,
      ProductModal,
      MaterialAdd,
      toolModal,
      processModal,
      ProductModalCorrelation,
      experimentationProcess
    },
    props: {
      typeInfo: {
        type: Object,
        default: () => null
      }
    },
    computed: {
      bankColumns() {
        const list = [
          {
            width: 110,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号'
          },
          {
            prop: 'sortNum',
            label: '排序',
            align: 'center',
            slot: 'sortNum',
            minWidth: 110
          },
          {
            prop: 'paramType',
            label: '参数类型',
            align: 'center',
            slot: 'paramType',
            minWidth: 110
          },
          {
            prop: 'paramValue',
            label: '参数内容',
            align: 'center',
            slot: 'paramValue',
            minWidth: 261
          },
          {
            prop: 'formula',
            label: '计算公式',
            align: 'center',
            slot: 'formula',
            minWidth: 300
          },
          {
            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',
            fixed: 'right'
          }
        ];
        if (this.formData.recordTemplateStyle != '4') {
          // 过滤掉 计算公式 列
          return list.filter((i) => i.prop != 'formula');
        }
        return list;
      },
      versionText() {
        if (this.type == 'change') {
          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: 'specification',
            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`;
      },
      detialsDatasource() {
        if (this.formData.recordTemplateStyle == '4') {
          // 根据 statisticsType 过滤
          return this.formData.details.filter(
            (i) => i.statisticsType == this.statisticsType
          );
        } else {
          return this.formData.details;
        }
      },
      // 根据typeList 计算行业类型列表
      //       {
      //     "id": "1991058936943173633",
      //     "createTime": "2025-11-19 16:20:17",
      //     "createUserId": "1881891196703911938",
      //     "industryType": 1,
      //     "industryName": "工程机械",
      //     "businessType": 1,
      //     "businessName": "生产",
      //     "reportWorkType": 1,
      //     "reportWorkName": "产前准备",
      //     "sceneType": 1,
      //     "sceneName": "清场清洁",
      //     "templateStyleType": 1,
      //     "templateStyleName": "通用模板",
      //     "tenantId": "1",
      //     "deptId": "1",
      //     "factoriesId": "1916747066214232065"
      // }
      industryTypeList() {
        const seen = new Set();
        const res = [];
        for (const i of this.typeList || []) {
          const key = String(i.industryType);
          if (!seen.has(key)) {
            seen.add(key);
            res.push({
              label: i.industryName,
              value: key
            });
          }
        }
        return res;
      },
      // 根据typeList和formData.industryType计算业务分类列表
      businessTypeList() {
        const seen = new Set();
        const res = [];
        const list = this.typeList.filter(
          (i) => i.industryType == this.formData.industryType
        );
        for (const i of list || []) {
          const key = String(i.businessType);
          if (!seen.has(key)) {
            seen.add(key);
            res.push({
              label: i.businessName,
              value: key
            });
          }
        }
        return res;
      },
      // 根据typeList和formData.industryType、formData.businessType计算模块划分列表
      reportWorkTypeList() {
        const seen = new Set();
        const res = [];
        const list = this.typeList.filter(
          (i) =>
            i.industryType == this.formData.industryType &&
            i.businessType == this.formData.businessType
        );
        for (const i of list || []) {
          const key = String(i.reportWorkType);
          if (!seen.has(key)) {
            seen.add(key);
            res.push({
              label: i.reportWorkName,
              value: key
            });
          }
        }
        return res;
      },
      // 根据typeList和formData.industryType、formData.businessType、formData.reportWorkType计算应用场景列表
      classifyList() {
        const seen = new Set();
        const res = [];
        const list = this.typeList.filter(
          (i) =>
            i.industryType == this.formData.industryType &&
            i.businessType == this.formData.businessType &&
            i.reportWorkType == this.formData.reportWorkType
        );
        for (const i of list || []) {
          const key = String(i.sceneType);
          if (!seen.has(key)) {
            seen.add(key);
            res.push({
              label: i.sceneName,
              value: key
            });
          }
        }
        return res;
      },
      // 根据typeList和formData.industryType、formData.businessType、formData.reportWorkType、formData.classify计算模板样式列表
      recordTemplateStyleList() {
        const seen = new Set();
        const res = [];
        const list = this.typeList.filter(
          (i) =>
            i.industryType == this.formData.industryType &&
            i.businessType == this.formData.businessType &&
            i.reportWorkType == this.formData.reportWorkType &&
            i.sceneType == this.formData.classify
        );
        for (const i of list || []) {
          const key = String(i.templateStyleType);
          if (!seen.has(key)) {
            seen.add(key);
            res.push({
              label: i.templateStyleName,
              value: key
            });
          }
        }
        return res;
      }
    },
    data() {
      const formDateBase = {
        id: null,
        deviceId: null,
        deviceName: '',
        frequencyUnit: 2,
        frequencyValue: null,
        name: '',
        details: [],
        recordRulesCycleList: [],
        startDate: null,
        stopDate: null,
        version: 1,
        code: '',
        fromId: null,
        // 行业类型
        industryType: null,
        // 业务分类
        businessType: null,
        // 记录规则类型|应用场景
        classify: null,
        // 模块分类 参考字典项：record_rules_report_work_type
        reportWorkType: null,
        // 模板样式
        recordTemplateStyle: null,
        // 执行方式
        isExecuteMethod: 0,
        executeMethodId: null,
        executeMethodName: '',
        produceTaskConfigs: [],
        bigVersion: '',
        versionMark: '',
        smallVersion: '',
        produceTaskId: '',
        produceTaskName: ''
      };

      return {
        qmsReportWorkType: ['5', '6', '7'],
        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' }
          ],
          businessType: [
            { required: true, message: '请选择业务分类', trigger: 'blur' },
            { required: true, message: '请选择业务分类', trigger: 'change' }
          ],
          industryType: [
            { required: true, message: '请选择业行业类别', trigger: 'blur' },
            { required: true, message: '请选择业行业类别', trigger: 'change' }
          ],
          reportWorkType: [
            { required: true, message: '请选择业模块划分', trigger: 'blur' },
            { required: true, message: '请选择业模块划分', trigger: 'change' }
          ],
          classify: [
            { required: true, message: '请选择应用场景', trigger: 'blur' },
            { required: true, message: '请选择应用场景', trigger: 'change' }
          ],
          recordTemplateStyle: [
            { required: true, message: '请选择模板样式', trigger: 'blur' },
            { required: true, message: '请选择模板样式', trigger: 'change' }
          ],
          executeMethodId: [
            { required: true, message: '请选择执行方式', trigger: 'change' },
            { required: true, message: '请选择执行方式', trigger: 'blur' }
          ]
        },
        recordSheet: [], // 记录表
        current: {},
        dataIndex: null,
        showEdit: false,
        btnLoading: false,
        currentRow: null,
        type: '',
        // 产品分类
        productCategory: [],
        loading: false,
        produceTaskCode: '',
        // 执行方式列表
        executeMethodList: [],
        // 1-成品统计，2-物料统计，3-工序统计"
        statisticsType: '1',
        statisticsTypeList: [
          { label: '成品统计', value: '1' },
          { label: '物料统计', value: '2' },
          { label: '工序统计', value: '3' }
        ],
        opSelectOptions: ['+', '-', '*', '/', '%', '(', ')'],
        typeList: []
      };
    },
    mounted() {
      this.getByCodeData();
      this.getProductCategory();
      console.log('this.formData 2233', this.formData);
      this.getTypeList();
    },
    methods: {
      open(row, type, title) {
        this.dialogTitle = title;
        this.type = type;
        console.log('type', type, row);

        this.getTypeList();

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

        // 过程控制临时修改
        if (type == 'processEdit') {
          this.processEditSetValue(row);
        }

        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');

          console.log('this.typeInfo', this.typeInfo);
          // 类型
          if (this.typeInfo) {
            const node = this.typeInfo;
            const item = node.item || node;

            switch (node.type) {
              case 'industry':
                this.formData.industryType = item.industryType + '';
                break;
              case 'business':
                this.formData.industryType = item.industryType + '';
                this.formData.businessType = item.businessType + '';
                break;
              case 'reportWork':
                this.formData.industryType = item.industryType + '';
                this.formData.businessType = item.businessType + '';
                this.formData.reportWorkType = item.reportWorkType + '';
                break;
              case 'scene':
                this.formData.industryType = item.industryType + '';
                this.formData.businessType = item.businessType + '';
                this.formData.reportWorkType = item.reportWorkType + '';
                this.formData.classify = item.sceneType + '';
                break;
              case 'templateStyle':
                this.formData.industryType = item.industryType + '';
                this.formData.businessType = item.businessType + '';
                this.formData.reportWorkType = item.reportWorkType + '';
                this.formData.classify = item.sceneType + '';
                this.formData.recordTemplateStyle = item.templateStyleType + '';
                break;
              default:
                // 直接赋值所有可用字段（兜底）
                if (item.industryType != null)
                  this.formData.industryType = item.industryType + '';
                if (item.businessType != null)
                  this.formData.businessType = item.businessType + '';
                if (item.reportWorkType != null)
                  this.formData.reportWorkType = item.reportWorkType + '';
                if (item.sceneType != null)
                  this.formData.classify = item.sceneType + '';
                if (item.templateStyleType != null)
                  this.formData.recordTemplateStyle =
                    item.templateStyleType + '';
                break;
            }
          }
        }

        this.visible = true;

        console.log('this.formData', this.formData);
      },
      // 过程控制 修改规则详情
      async processEditSetValue(row) {
        const data = await recordrulesGetById(row.rulesId);

        const info = JSON.parse(JSON.stringify(row));

        data.details = info.produceTaskConfigRuleDetails;

        // 处理详情的 公式 字段
        data.details.forEach((item) => {
          if (item.paramType == 9 && item.formula) {
            // formula格式为[A][+][b][*][C] 拆分 -> ['A','+','b','*','C']
            if (item.formula) {
              const matches = item.formula.match(/\[([^\]]+)\]/g);
              if (matches) {
                this.$set(
                  item,
                  'formulaParts',
                  matches.map((m) => m.slice(1, -1)).filter(Boolean)
                );
              }
            } else {
              this.$set(item, 'formulaParts', []);
            }
          }
        });

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

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

        this.formData.executeMethodId = info.recordRulesExecuteMethodId;
        this.formData.executeMethodName = info.recordRulesExecuteMethodName;
        this.formData.startDate = new Date(info.startDate);
        this.formData.stopDate = new Date(info.stopDate);
        this.formData.classify = this.formData.classify + '';
        this.formData.reportWorkType = this.formData.reportWorkType + '';
        this.formData.industryType = this.formData.industryType + '';
        this.formData.businessType = this.formData.businessType + '';
        this.formData.reportWorkType = this.formData.reportWorkType + '';
        this.formData.recordTemplateStyle =
          this.formData.recordTemplateStyle + '';

        console.log('this.formData~~~~', this.formData);

        this.getExecuteMethodList();

        this.loading = false;
      },
      async getDetils(id) {
        this.loading = true;
        try {
          const data = await recordrulesGetById(id);

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

          this.$nextTick(() => {
            this.$refs.cycleMultipleRef?.setRecordRulesCycleList(
              this.formData.recordRulesCycleList
            );
            if (this.qmsReportWorkType.includes(this.formData.reportWorkType)) {
              this.$refs.experimentationProcess.init(data.tempJson.tempJson);
            }
          });

          this.formData.startDate = new Date(data.startDate);

          this.formData.stopDate = new Date(data.stopDate);
          this.formData.classify = this.formData.classify + '';
          this.formData.industryType = this.formData.industryType + '';
          this.formData.businessType = this.formData.businessType + '';
          this.formData.reportWorkType = this.formData.reportWorkType + '';
          this.formData.recordTemplateStyle =
            this.formData.recordTemplateStyle + '';

          if (this.type == 'change') {
            this.formData.fromId = id;
            this.formData.id = null;
          }

          if (this.type == 'clone') {
            this.formData.fromId = null;
            this.formData.id = null;
            this.formData.produceTaskId = null;
            this.formData.produceTaskName = null;
            this.formData.executeMethodId = null;
            this.formData.executeMethodName = '';
            this.executeMethodList = [];

            // startDate 小于当前日期则取当前日期
            const now = new Date();
            if (this.formData.startDate < now) {
              this.formData.startDate = now;
            }
          } else {
            this.getExecuteMethodList();
          }

          // 处理详情的 公式 字段
          this.formData.details.forEach((item) => {
            if (item.paramType == 9 && item.formula) {
              // formula格式为[A][+][b][*][C] 拆分 -> ['A','+','b','*','C']
              if (item.formula) {
                const matches = item.formula.match(/\[([^\]]+)\]/g);
                if (matches) {
                  this.$set(
                    item,
                    'formulaParts',
                    matches.map((m) => m.slice(1, -1)).filter(Boolean)
                  );
                }
              } else {
                this.$set(item, 'formulaParts', []);
              }
              this.$set(item, '_paramSelect', null);
              this.$set(item, '_opSelect', null);
              this.$set(item, '_replaceOrAppend', '');
            }
          });

          this.loading = false;
        } catch (error) {
          console.log(error, '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;
        console.log('this.recordSheet', this.recordSheet);
      },
      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.executeMethodList = [];
        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 &&
            !this.qmsReportWorkType.includes(this.formData.reportWorkType)
          ) {
            return this.$message.warning('至少条件一条规则项');
          }

          try {
            const valid = this.validateFormula();
            if (!valid) {
              return;
            }

            this.btnLoading = true;

            const body = this.formatBody();

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

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

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

            if (this.formData.reportWorkType == 4) {
              // 生产统计过滤掉非成品统计的明细
              this.formData.details = this.formData.details.filter(
                (i) => i.statisticsType
              );
            }

            // 判断参数类型是否选择
            for (const detail of this.formData.details) {
              if (!detail.paramType) {
                console.log('detail', detail);
                return this.$message.warning('请选择规则明细中的参数类型！');
              }
            }
          }

          try {
            this.btnLoading = true;

            const body = this.formatBody();

            if (this.type != 'saveAndPublish') {
              await recordrulesSaveAndPublish(body);
            } else {
              this.$emit('processSave', body);
            }

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

            this.handleClose();
            this.$emit('reload');
          } catch (error) {
            console.log(error, 'error');
            this.btnLoading = false;
          }
        });
      },
      // 保存或发布时验证公式是否正确
      validateFormula() {
        let invalid = false;
        this.formData.details.forEach((detail) => {
          if (invalid) return; // 已发现无效，后续直接跳过避免重复提示
          if (detail.paramType == 9) {
            const formula = detail.formula;
            if (!formula || !formula.trim()) {
              console.log('formula', formula);
              this.$message.warning('规则明细中计算类型的公式不能为空！');
              invalid = true;
            }
            // 解析公式为 token 列表
            const rawTokens = (formula.match(/\[([^\]]+)\]/g) || [])
              .map((m) => m.slice(1, -1))
              .filter(Boolean);
            if (!rawTokens.length) {
              console.log('rawTokens', rawTokens, formula);
              this.$message.warning('规则明细中计算类型的公式不能为空！');
              invalid = true;
              return;
            }

            const operators = new Set(this.opSelectOptions);
            const availableParams = this.formData.details
              .filter((d) => d !== detail && d.paramType != 9 && d.paramValue)
              .map((d) => d.paramValue);
            const varsSet = new Set();

            let parenBalance = 0;
            let lastWasOperator = true; // 开头不能是普通数字/变量
            let expression = '';

            for (let i = 0; i < rawTokens.length; i++) {
              const t = rawTokens[i];
              if (invalid) break;

              if (operators.has(t)) {
                // 括号
                if (t === '(') {
                  parenBalance++;
                  lastWasOperator = true;
                } else if (t === ')') {
                  parenBalance--;
                  if (parenBalance < 0) {
                    this.$message.warning('公式括号不匹配');
                    invalid = true;
                    break;
                  }
                  lastWasOperator = false;
                } else {
                  // 普通运算符不能连续出现
                  if (lastWasOperator) {
                    this.$message.warning('公式存在连续运算符或位置不合法');
                    invalid = true;
                    break;
                  }
                  lastWasOperator = true;
                }
                expression += t;
              } else {
                // 变量
                if (!t.trim()) {
                  this.$message.warning('公式中存在空变量');
                  invalid = true;
                  break;
                }
                // 变量前必须是运算符或者开头或左括号
                if (!lastWasOperator) {
                  this.$message.warning('公式中变量之间缺少运算符');
                  invalid = true;
                  break;
                }
                varsSet.add(t);
                // 校验变量是否存在于其他明细 排除要求生产数量
                if (!availableParams.includes(t) && t != '要求生产数量') {
                  this.$message.warning(
                    `公式中引用的参数 "${t}" 未在非计算类型的明细中定义`
                  );
                  invalid = true;
                  break;
                }
                // 用顺序数字替换变量
                expression += varsSet.size; // 1,2,3...
                lastWasOperator = false;
              }
            }

            if (invalid) return;

            if (parenBalance !== 0) {
              this.$message.warning('公式括号不匹配');
              invalid = true;
              return;
            }
            if (lastWasOperator) {
              this.$message.warning('公式不能以运算符结尾');
              invalid = true;
              return;
            }

            // 最终表达式字符合法性校验
            if (!/^[0-9+\-*/%() ]+$/.test(expression)) {
              this.$message.warning('公式包含非法字符');
              invalid = true;
              return;
            }

            // 计算测试
            try {
              const result = Function(`"use strict";return (${expression})`)();
              if (Number.isNaN(result) || !isFinite(result)) {
                this.$message.warning('公式计算结果非法');
                invalid = true;
                return;
              }
            } catch (e) {
              this.$message.warning('公式计算失败，请检查语法');
              invalid = true;
              return;
            }

            // 回填拆分后的 parts
            detail.formulaParts = rawTokens;
          }
        });
        if (invalid) {
          return false;
        }
        return true;
      },
      // 数据格式化
      formatBody() {
        this.formData.recordRulesCycleList =
          this.$refs.cycleMultipleRef &&
          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.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.qmsReportWorkType.includes(body.reportWorkType)) {
          let tempJson = this.$refs.experimentationProcess.getValue();
          if (tempJson) {
            body.tempJson = {
              tempJson: JSON.stringify(tempJson)
            };
          }
        }
        // details 根据下标添加 sortNum
        body.details = body.details.map((item, index) => {
          return { ...item };
        });

        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?.id || null;
        this.formData.deviceName = data?.name || '';
      },
      // 添加
      addRow() {
        // 最大sortNum 值 +1
        let sortNum = 1;
        if (this.formData.details.length > 0) {
          const maxSortNum = Math.max(
            ...this.formData.details.map((item) => item.sortNum || 0)
          );
          sortNum = maxSortNum + 1;
        }

        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: '',
          // 1-成品统计，2-物料统计，3-工序统计"
          statisticsType:
            this.formData.recordTemplateStyle == '4'
              ? this.statisticsType
              : null,
          // 公式
          formula: '',
          _paramSelect: null,
          _opSelect: null,
          _replaceOrAppend: '',
          formulaParts: [],
          sortNum
        });
        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);
        }
      },
      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
          };
        });
      },
      // 规则明细表
      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.name;
        this.currentRow.productCode = current.code;
        this.currentRow.unitName = current.weightUnit;
        console.log('this.currentRow', this.currentRow);
      },
      // 清空产品
      clearProduct(row) {
        row.productName = '';
        row.productCode = '';
      },
      // 获取产品分类
      async getProductCategory() {
        let { data } = await getTreeByPid(9);
        console.log('产品分类', data);
        this.productCategory = data;
      },
      // 选择工序
      openProduceTaskDialog() {
        this.$refs.processModalRef.open();
      },
      // 工序
      processChooseProcess(process) {
        console.log('选择的工序', process);
        this.formData.produceTaskId = process.id;
        this.formData.produceTaskName = process.name;
        this.formData.executeMethodId = null;
        this.formData.executeMethodName = '';
        // 查询工序下的执行方式
        this.getExecuteMethodList();
      },
      clearProductTask() {
        this.formData.produceTaskId = '';
        this.formData.produceTaskName = '';
        this.formData.executeMethodId = null;
        this.formData.executeMethodName = '';
        this.executeMethodList = [];
      },
      // 查询执行方式
      async getExecuteMethodList() {
        if (
          this.formData.produceTaskId == '' &&
          this.formData.reportWorkType == 2
        ) {
          this.executeMethodList = [];
          return;
        }
        const data = await recordrulesexecutemethodPage({
          pageNum: 1,
          size: 9999,
          enable: 1,
          produceTaskId: this.formData.produceTaskId
        });
        this.executeMethodList = data.list;
        // 有执行方式
        if (
          this.executeMethodList.length &&
          this.formData.reportWorkType == 2
        ) {
          this.formData.isExecuteMethod = 1;
        }
      },
      // 过程控制修改 保存
      processEditSave() {
        // 只验证详情内容
        if (!this.qmsReportWorkType.includes(this.formData.reportWorkType)) {
          if (this.formData.details.length == 0) {
            return this.$message.warning('至少条件一条规则项');
          }

          // 判断参数类型是否选择
          for (const detail of this.formData.details) {
            if (!detail.paramType) {
              return this.$message.warning('请选择规则明细中的参数类型！');
            }
          }
        }

        this.$emit('processSave', this.formatBody());
        this.handleClose();
      },
      // 执行方式改变 同步执行方式名称
      executeMethodIdChange() {
        const selected = this.executeMethodList.find(
          (item) => item.id === this.formData.executeMethodId
        );
        if (selected) {
          this.formData.executeMethodName = selected.name;
        } else {
          this.formData.executeMethodName = '';
        }
      },
      isExecuteMethodChange() {
        if (this.formData.isExecuteMethod == 0) {
          this.formData.executeMethodId = null;
          this.formData.executeMethodName = '';
        }
      },
      classifyChagne() {
        // 生产统计
        if (this.formData.recordTemplateStyle == '4') {
          // 模块分类- 生产统计
          this.formData.reportWorkType = '4';
          // 清空规则明细
          this.formData.details = [];
          // 重置统计类型
          this.statisticsType = '1';
        } else {
          if (this.formData.reportWorkType == '4') {
            this.formData.reportWorkType = '1';
          }
        }
      },
      // 基于详情返回selectOptions
      getSelectOptionsByDetails(statisticsType) {
        let paramTypeOptions = [];
        for (const detail of this.formData.details.filter(
          (i) => i.statisticsType == statisticsType
        )) {
          if (detail.paramType != 9 || !detail.paramType) {
            paramTypeOptions.push({
              value: detail.paramValue,
              label: detail.paramValue
            });
          }
        }
        // 过滤空值
        paramTypeOptions = paramTypeOptions.filter((i) => i.value);
        // 追加一个 （要求生产数量）
        paramTypeOptions.push({
          value: '要求生产数量',
          label: '要求生产数量'
        });
        return paramTypeOptions;
      },
      paramSelectChange(val, row) {
        if (!val) return;
        row.formulaParts = row.formulaParts || [];
        if (row.activeIndex != undefined) {
          if (!row._replaceOrAppend || row._replaceOrAppend === 'replace') {
            row.formulaParts.splice(row.activeIndex, 1, val);
          } else if (row._replaceOrAppend === 'append') {
            row.formulaParts.splice(row.activeIndex + 1, 0, val);
            // 追加后activeIndex后移一位
            this.$set(row, 'activeIndex', row.activeIndex + 1);
          }
          // row.activeIndex = undefined;
        } else {
          row.formulaParts.push(val);
        }
        row.formula = row.formulaParts.map((p) => `[${p}]`).join('');
        row._paramSelect = null;
      },
      opSelectChange(val, row) {
        if (!val) return;
        row.formulaParts = row.formulaParts || [];
        if (row.activeIndex != undefined) {
          if (!row._replaceOrAppend || row._replaceOrAppend === 'replace') {
            row.formulaParts.splice(row.activeIndex, 1, val);
          } else if (row._replaceOrAppend === 'append') {
            row.formulaParts.splice(row.activeIndex + 1, 0, val);
            // 追加后activeIndex后移一位
            this.$set(row, 'activeIndex', row.activeIndex + 1);
          }
          // row.activeIndex = undefined;
        } else {
          row.formulaParts.push(val);
        }
        row.formula = row.formulaParts.map((p) => `[${p}]`).join('');
        row._opSelect = null;
      },
      tagItemDelete(index, row) {
        if (this.type == 'detail') return;
        row.formulaParts.splice(index, 1);
        row.formula = row.formulaParts.map((p) => `[${p}]`).join('');
      },
      formulaPartsTagClick(index, row) {
        if (this.type == 'detail') return;

        if (!row._replaceOrAppend) {
          // 默认追加
          row._replaceOrAppend = 'append';
        }

        if (row.activeIndex && row.activeIndex === index) {
          this.$set(row, 'activeIndex', undefined);
        } else {
          this.$set(row, 'activeIndex', index);
        }
      },
      // 类型变化
      paramTypeChange(row) {
        if (row.pageType != 9) {
          // 清空
          row.formulaParts = [];
          row.formula = '';
        }
      },
      // 类型列表
      async getTypeList() {
        const { list = [] } = await recordrulesTypePage({
          pageNum: 1,
          size: 99999
        });

        this.typeList = list;
        console.log('this.typeList', this.typeList);
      },
      industryTypeChange() {
        this.formData.businessType = '';
        this.formData.reportWorkType = '';
        this.formData.classify = '';
        this.formData.recordTemplateStyle = '';
      },
      businessTypeChange() {
        this.formData.reportWorkType = '';
        this.formData.classify = '';
        this.formData.recordTemplateStyle = '';
      },
      reportWorkTypeChange() {
        this.formData.classify = '';
        this.formData.recordTemplateStyle = '';
      },
      classifyChange() {
        this.formData.recordTemplateStyle = '';
      }
    }
  };
</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;
      }
    }
  }

  .formula-builder {
    .formula-builder__selects {
      margin-bottom: 6px;
      display: flex;
      flex-shrink: 0;
    }
  }

  :deep(.el-dialog:not(.ele-dialog-form) .el-dialog__body .el-form) {
    .el-form-item:last-child {
      margin-bottom: 22px;
    }
  }
</style>
