<template>
  <div class="page-wrapper">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <a-collapse
          v-model="activeKey"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('CHECK_FORM_CODE')"
                  prop="pcFrmCode"
                  allow-clear
                >
                  <a-input
                    v-model="form.pcFrmCode"
                    disabled
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.pcFrmCode = form.pcFrmCode.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('FORM_NAME')"
                  prop="pcFrmName"
                  allow-clear
                >
                  <a-input
                    v-model="form.pcFrmName"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.pcFrmName = form.pcFrmName.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('pcCategoryId')" :span="8">
                <a-form-model-item
                  :label="$t('CHECK_TYPE')"
                  prop="pcCategoryId"
                >
                  <SelectCheckType
                    :pc-category-id="form.pcCategoryId"
                    :pc-category-name="form.pcCategoryName"
                    @change="onSelectSearchChange"
                  >
                  </SelectCheckType>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="form.hasOwnProperty('opUrl')" :gutter="24">
              <a-col :span="8">
                <a-form-model-item :label="$t('CHECK_SOP')" prop="opUrl">
                  <SingleUploadFile
                    v-model="form.opUrl"
                    :accept="'.mp4, .pdf, .PDF'"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse
          v-model="activeKeyB"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('EQP_CHECK_METHOD')">
            <MomTable
              ref="MomTable"
              row-key="itemName"
              :action-buttons="actionButtons"
              :columns="columns"
              :data-source="pcFrmItemList"
              :pagination="false"
              @edit="handleEdit"
              @delete="handleDelete"
            >
              <div slot="toolbar" class="button-top-table">
                <a-button @click="handleAdd">
                  <a-icon type="plus" /> {{ $t("ADD") }}
                </a-button>
                <a-button @click="handleSelectCheckContent()">{{
                  `${$t("SELECT_CHECK_ITEM")}`
                }}</a-button>
                <a-button @click="handleSelectHistoryForm()">
                  <i class="iconfont icon-zhengque"></i>
                  {{ $t("USE_HISTORY_FORM") }}
                </a-button>
              </div>
              <div slot="itemType" slot-scope="text, record">
                <span>{{ getAttrValue(itemTypeList, record.itemType) }}</span>
              </div>
              <div slot="imgFlag" slot-scope="text, record">
                <span>{{ getAttrValue(yesNoList, record.imgFlag) }}</span>
              </div>
              <div slot="checkStyle" slot-scope="text, record">
                <span>{{
                  getAttrValue(checkStyleList, record.checkStyle)
                }}</span>
              </div>
            </MomTable>
          </a-collapse-panel>
        </a-collapse>
        <!-- 扩展字段 -->
        {{ fieldExRenderFn($createElement, { layout: "grid", itemSpan: 8 }) }}
        <slot name="RenderFieldExtendDom"></slot>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <!-- <slot name="RenderFieldButton"></slot> -->
      <!-- 字段授权 -->
      <!-- <FieldAuth
        ref="fieldAuthRef"
        :form-data="formOld"
        :table-name-list="tableNameList"
        @formBack="onFormBack"
      /> -->
      <a-button type="primary" :loading="confirmLoading" @click="handleSave">
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("CANCEL") }}
      </a-button>
    </div>
    <MegaDrawer
      width="520"
      :title="
        isEdit
          ? $t('EQP_CHECK_METHOD') + $t('EDIT')
          : $t('EQP_CHECK_METHOD') + $t('ADD')
      "
      :visible="drawerVisible"
      :confirm-loading="confirmLoading"
      @close="handleCloseDrawer"
      @cancel="handleCloseDrawer"
      @ok="handleSaveDrawer"
    >
      <a-form-model
        slot="main"
        ref="ruleFormDrawer"
        layout="vertical"
        :model="drawerForm"
        :rules="rulesDrawer"
      >
        <a-form-model-item
          :label="`${$t('CHECK_CONTENT')}${$t('NAME')}`"
          prop="itemName"
        >
          <a-input
            v-model="drawerForm.itemName"
            :placeholder="$t('PLACEENTER')"
            @change="
              drawerForm.itemName = drawerForm.itemName.slice(0, 50).trim()
            "
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('IMG_FLAG')" prop="imgFlag">
          <a-radio-group v-model="drawerForm.imgFlag">
            <a-radio
              v-for="imgFlagItem in yesNoList"
              :key="imgFlagItem.value"
              :value="imgFlagItem.value"
              >{{ imgFlagItem.label }}</a-radio
            >
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          :label="$t('EQP_CHECK_METHOD')"
          prop="checkStyle"
          allow-clear
        >
          <div class="flex">
            <div
              v-for="ele in checkStyleList"
              :key="ele.value"
              class="epms-status-box flex flex-wrap"
              @click="handleMethodChange(ele.value)"
            >
              <div
                class="status-btn"
                :style="{
                  color:
                    ele.value === drawerForm.checkStyle ? '#005583' : '#666666',
                  borderColor:
                    ele.value === drawerForm.checkStyle ? '#005583' : '#f0f0f0',
                }"
              >
                {{ ele.label }}
                <div
                  v-show="ele.value === drawerForm.checkStyle"
                  class="icon-box"
                  :style="{
                    color: '#005583',
                    backgroundColor: '#005583',
                  }"
                >
                  <div class="iconfont icon-gougou"></div>
                </div>
              </div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'NUMBER'"
          allow-clear
          prop="itemType"
          :label="$t('PROJECT_TYPE')"
        >
          <a-select
            v-model="drawerForm.itemType"
            :placeholder="$t('PLACESELECT')"
          >
            <a-select-option
              v-for="(itemType, itemTypeIndex) in itemTypeList"
              :key="itemTypeIndex"
              :value="itemType.value"
            >
              {{ itemType.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'NUMBER'"
          :label="`${$t('COMPARISON_MODE')}`"
          allow-clear
          prop="compareType"
        >
          <a-select
            v-model="drawerForm.compareType"
            :placeholder="$t('PLACESELECT')"
            @change="handleChangeCompare()"
          >
            <a-select-option
              v-for="(compareType, compareTypeIndex) in compareTypeList"
              :key="compareTypeIndex"
              :value="compareType.value"
            >
              {{ compareType.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'NUMBER' && !drawerForm.noShowLow"
          :label="`${$t('STANDARD_LOWER_LIMIT')}`"
          allow-clear
          prop="lowerLimit"
        >
          <a-input-number v-model="drawerForm.lowerLimit" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'NUMBER' && !drawerForm.noShowUp"
          :label="`${$t('STANDARD_UPPER_LIMIT')}`"
          allow-clear
          prop="upperLimit"
        >
          <a-input-number v-model="drawerForm.upperLimit" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item
          v-if="
            drawerForm.checkStyle === 'NUMBER' && drawerForm.itemType === 'AUTO'
          "
          :label="`${$t('AUTO_MATCH_KEY')}`"
          allow-clear
          prop="autoMatchKey"
        >
          <a-input
            v-model="drawerForm.autoMatchKey"
            :placeholder="$t('PLACEENTER')"
            @change="
              drawerForm.autoMatchKey = drawerForm.autoMatchKey
                .slice(0, 32)
                .trim()
            "
          />
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'TEXT'"
          :label="`${$t('STANDARD_VALUE')}`"
          allow-clear
          prop="textValue"
        >
          <a-input
            v-model="drawerForm.textValue"
            :placeholder="$t('PLACEENTER')"
            @change="
              drawerForm.textValue = drawerForm.textValue.slice(0, 255).trim()
            "
          />
        </a-form-model-item>
        <a-form-model-item
          :label="`${$t('OPERATING_INSTRUCTION')}`"
          allow-clear
          prop="opDescription"
        >
          <a-input
            v-model="drawerForm.opDescription"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item
          :label="`${$t('IMPORT')}${$t('OPERATION')}${$t('CORE_PICTURE')}`"
          allow-clear
          prop="opUrl"
        >
          <SingleUpload
            v-model="drawerForm.opUrl"
            :is-show-button="isShowButton"
          />
        </a-form-model-item>
        <!-- 扩展字段 -->
        <a-form-model-item
          v-for="(fileItem, fileIndex) in drawerForm.fieldExtendList"
          :key="fileIndex"
          :label="$t(fileItem.i18nCode)"
          :prop="fileItem.fieldName"
          allow-clear
        >
          <a-input
            v-model="drawerForm[fileItem.fieldName]"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
    <!-- 选择点检项目组件 -->
    <select-check-content
      ref="selectCheckContent"
      show-key="id"
      :pc-category-id="form.pcCategoryId"
      :show-slot="false"
      @confirm="getReturnData"
    />
    <!-- 选择历史点检表单组件 -->
    <select-history-form
      ref="selectHistoryForm"
      show-key="id"
      :pc-category-id="form.pcCategoryId"
      :show-slot="false"
      @confirm="getReturnDataForm"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";
import { uniqBy } from "lodash";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
// import FieldAuth from "@/components/FieldAuth";
import { fieldExReqDataFn } from "@/utils/fieldExtend";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";
import SelectCheckContent from "@/components/SelectCheckContent";
import SelectCheckType from "@/components/SelectCheckType";
import SelectHistoryForm from "@/components/SelectHistoryForm";
import SingleUpload from "@/components/uploadPicture/singleUpload";
import SingleUploadFile from "@/components/uploadFile/singleUpload";

export default {
  components: {
    // FieldAuth,
    breadcrumb,
    MegaDrawer,
    SelectCheckContent,
    SelectCheckType,
    SelectHistoryForm,
    SingleUpload,
    SingleUploadFile,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("CHECK_FORM"),
          url: "/eam/eqp_check/check_form",
        },
        { name: this.$t("CHECK_FORM_EDIT"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_pc_frm",
          tab: "点检表单",
        },
      ],
      dataAttr: {
        form: "form",
      },
      activeKey: "a",
      activeKeyB: "b",
      isShowButton: false,
      confirmLoading: false,
      dataSource: [],
      form: {
        id: "",
        pcFrmName: "", // 点检表单名称
        pcCategoryId: "", // 点检分类
        opUrl: "", // 图片或视频地址
        confirmNum: "",
      },
      formOld: {
        id: "",
        pcFrmCode: "", // 点检表单编码
        pcFrmName: "", // 点检表单名称
        pcCategoryId: "", // 点检分类
        opUrl: "", // 图片或视频地址
        confirmNum: "",
      },
      pcFrmItemList: [],
      drawerForm: {
        itemName: "", // 	点检项名称
        itemType: "", // 点检项类型
        checkStyle: "", // 点检方式
        compareType: "", // 比较方式
        lowerLimit: "", // 标准下限
        textValue: "", // 文本标准值
        autoMatchKey: "", // 自动匹配的Key
        opDescription: "", // 操作说明
        opUrl: "", // 操作说明地址：图片或视频
        imgFlag: "Y", // 是否上传点检图片
        noShowLow: true,
        noShowUp: true,
        fieldExtendList: [],
      },
      checkStyleList: [], // 点检方式列表
      itemTypeList: [], // 项目类型列表
      compareTypeList: [], // 点检项比较方式列表
      yesNoList: [], // 是否列表
      fieldExtendList: [], // 字段扩展列表
      dynamicFieldList: [], // 字段扩展列表动态
      drawerVisible: false,
      isEdit: false,
      editIndex: 0,
      actionButtons: ["edit", "delete"],
      defaultList: [
        {
          dataIndex: "itemName", // 点检项名称
          sorter: false,
          ellipsis: true,
          title: () => this.$t("CHECK_CONTENT"),
        },
        {
          dataIndex: "pcCategoryName", // 点检分类
          title: () => `${this.$t("CHECK_TYPE")}${this.$t("NAME")}`,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "imgFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("IMG_FLAG"), // 是否上传图片
          scopedSlots: { customRender: "imgFlag" },
        },
        {
          dataIndex: "checkStyle", // 点检方式
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EQP_CHECK_METHOD"),
          scopedSlots: { customRender: "checkStyle" },
        },
        {
          dataIndex: "itemType", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("PROJECT_TYPE"),
          scopedSlots: { customRender: "itemType" },
        },
        {
          dataIndex: "compareType", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("COMPARISON_MODE"),
          scopedSlots: { customRender: "compareType" },
        },
        {
          dataIndex: "upperLimit", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STANDARD_UPPER_LIMIT"),
        },
        {
          dataIndex: "lowerLimit", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STANDARD_LOWER_LIMIT"),
        },
        {
          dataIndex: "autoMatchKey", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("AUTO_MATCH_KEY"),
        },
        {
          dataIndex: "textValue", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STANDARD_VALUE"),
        },
        {
          dataIndex: "opDescription", // 操作说明
          sorter: false,
          ellipsis: true,
          title: () => this.$t("OPERATING_INSTRUCTION"),
        },
      ],
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      columnsList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    rules() {
      return {
        pcFrmCode: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        pcFrmName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    rulesDrawer() {
      return {
        itemName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        imgFlag: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkStyle: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        itemType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        compareType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        upperLimit: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        lowerLimit: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        autoMatchKey: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        textValue: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
      };
    },
    columns() {
      return [...this.defaultList, ...this.columnsList];
    },
  },
  watch: {},
  mounted() {
    this.queryFieldExtend().then(() => {
      // this.$refs.fieldAuthRef.init();
    });
    // 初始化数据
    this.init();
  },
  methods: {
    // 获取返回数据，点检项目
    getReturnData(selectedKeys, selectedRows) {
      if (selectedRows && selectedRows.length > 0) {
        this.pcFrmItemList = this.pcFrmItemList.concat(selectedRows);
        this.checkItemList();
      }
    },
    // 获取返回数据，点检表单
    getReturnDataForm(selectedKeys, selectedRows) {
      if (selectedKeys && selectedKeys.length > 0) {
        const params = {
          ids: selectedKeys.join(","),
        };
        this.$axios
          .get(
            `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-frm/get-item-by-ids`,
            {
              params,
            }
          )
          .then((res) => {
            if (res.data?.data && res.data.data.length > 0) {
              this.pcFrmItemList = this.pcFrmItemList.concat(res.data.data);
              this.checkItemList();
            }
          });
      }
    },
    // 获取返回数据，点检分类
    onSelectSearchChange(pcCategoryId, pcCategoryName) {
      this.form.pcCategoryId = pcCategoryId;
      this.form.pcCategoryName = pcCategoryName;
    },
    // 获取返回数据，字段扩展
    onFormBack(formBackData) {
      this.$nextTick(() => {
        Object.keys(this.form).forEach((key) => {
          // eslint-disable-next-line no-prototype-builtins
          if (!formBackData.hasOwnProperty(key)) {
            delete this.form[key];
          }
        });
        Object.keys(formBackData).forEach((key1) => {
          // eslint-disable-next-line no-prototype-builtins
          if (!this.form.hasOwnProperty(key1)) {
            this.form[key1] = "";
          }
        });
        this.queryFieldExtend();
      });
    },
    // 初始化数据
    init() {
      const params = {
        tableNameList: "epm_pc_item",
        moduleCode: this.$store.state.activatedModule,
      };
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_CHECK_STYLE`
        ), // 点检方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_ITEM_TYPE`
        ), // 点检项类型
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_COMPARE_TYPE`
        ), // 点检项比较方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-frm/get-by-id/${this.$route.query.id}`
        ), // 点检对象来源配置详情
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/filed-extend-config/detail-batch`,
          {
            params,
          }
        ), // 扩展字段，点检项目
      ]).then(
        ([
          checkStyleRes,
          itemTypeRes,
          compareTypeRes,
          yesNoRes,
          detailRes,
          detailBatchRes,
        ]) => {
          this.checkStyleList = checkStyleRes.data.data;
          this.itemTypeList = itemTypeRes.data.data;
          this.compareTypeList = compareTypeRes.data.data;
          this.yesNoList = yesNoRes.data.data;
          // this.$refs.fieldAuthRef.init();
          /* eslint-disable */
          this.fieldExtendList =
            detailBatchRes.data?.data?.fieldExtendConfigList[0]?.items.filter(
              (item) => [1, "Y"].includes(item.enableFlag)
            ) || [];
          if (this.fieldExtendList?.length > 0) {
            this.fieldExtendList.forEach((item, index) => {
              if (detailBatchRes.data.data?.fieldHiddenConfigList?.length) {
                // eslint-disable-next-line array-callback-return
                detailBatchRes.data.data.fieldHiddenConfigList.forEach(
                  (ele) => {
                    if (ele.fieldName === item.fieldName) {
                      this.fieldExtendList.splice(index, 1);
                    }
                  }
                );
              }
            });
          }
          if (this.fieldExtendList?.length > 0) {
            this.fieldExtendList.forEach((item) => {
              this.drawerForm[item.fieldName] = "";
              if (item.type === "DYNAMIC") {
                this.dynamicFieldList.push(item.fieldName);
              }
              // 动态添加表格列
              const columnsItem = { ...this.columnsItem };
              columnsItem.dataIndex = item.fieldName;
              columnsItem.title = () => this.$t(`${item.i18nCode}`);
              if (["code"].includes(item.fieldName)) {
                this.defaultList[0].title = () => this.$t(`${item.i18nCode}`);
              }
              if (["name"].includes(item.fieldName)) {
                this.defaultList[1].title = () => this.$t(`${item.i18nCode}`);
              }
              if (!["code", "name"].includes(item.fieldName)) {
                this.columnsList.push(columnsItem);
              }
            });
          }
          /* eslint-enable */
          const { pcFrmItemList } = { ...detailRes.data?.data };
          this.form = { ...detailRes.data?.data };
          if (pcFrmItemList && pcFrmItemList.length > 0) {
            this.pcFrmItemList = pcFrmItemList.map((item) => {
              const req = this.fieldExResDataFn(item);
              return req;
            });
            this.checkItemList();
          }
        }
      );
    },
    // 监听选择点检项目
    handleSelectCheckContent() {
      this.$refs.selectCheckContent.openDialog();
    },
    // 监听选择历史表单组件
    handleSelectHistoryForm() {
      this.$refs.selectHistoryForm.openDialog();
    },
    // 监听点检项目名称是否重复
    handleBlurItemName(itemName, index) {
      if (this.pcFrmItemList.some((val) => val.itemName === itemName)) {
        this.$message.warning(
          `${this.$t("CANNOT_REPEAT")}${this.$t("CHECK_CONTENT")}${this.$t(
            "NAME"
          )}`
        );
      }
      this.pcFrmItemList[index].itemName = "";
    },
    // 点检方式切换
    handleMethodChange(e) {
      this.drawerForm.checkStyle = e;
    },
    // 检查点检项目列表
    checkItemList() {
      // eslint-disable-next-line array-callback-return
      this.pcFrmItemList.map((item, index) => {
        // eslint-disable-next-line no-param-reassign
        item.fieldExtendList = this.fieldExtendList;
        if (item.compareType) {
          this.handleChangeCompare(item.compareType, index);
        }
      });
      this.pcFrmItemList = uniqBy(this.pcFrmItemList, "itemName"); // 去重
    },
    // 比较方式切换
    handleChangeCompare() {
      this.drawerForm.noShowLow = false;
      this.drawerForm.noShowUp = false;
      switch (this.drawerForm.compareType) {
        case "<": // <: "点检值<上限"
          this.drawerForm.noShowLow = true;
          break;
        case ">": // >: "点检值>下限"
          this.drawerForm.noShowUp = true;
          break;
        default:
          break;
      }
    },
    // 监听新增点击事件
    handleAdd() {
      this.drawerForm = {
        itemName: "", // 	点检项名称
        itemType: "", // 点检项类型
        checkStyle: "", // 点检方式
        compareType: "", // 比较方式
        lowerLimit: "", // 标准下限
        textValue: "", // 文本标准值
        autoMatchKey: "", // 自动匹配的Key
        opDescription: "", // 操作说明
        opUrl: "", // 操作说明地址：图片或视频
        imgFlag: "Y", // 是否上传点检图片
        noShowLow: true,
        noShowUp: true,
        fieldExtendList: [],
      };
      this.drawerForm.fieldExtendList = this.fieldExtendList;
      this.isEdit = false;
      this.drawerVisible = true;
    },
    handleEdit(row) {
      const index = this.pcFrmItemList.findIndex(
        (item) => item.itemName === row.itemName
      );
      this.editIndex = index;
      this.isEdit = true;
      this.drawerForm = { ...row };
      this.pmItemCategoryName = row.pmItemCategoryName;
      this.drawerVisible = true;
    },
    handleDelete(row) {
      const index = this.pcFrmItemList.findIndex(
        (item) => item.itemName === row.itemName
      );
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.pcFrmItemList.splice(index, 1);
        },
      });
    },
    handleSaveDrawer() {
      this.$refs.ruleFormDrawer.validate((valid) => {
        if (valid) {
          if (this.drawerForm.checkStyle === "NUMBER") {
            if (this.drawerForm.compareType === "<=>=") {
              if (this.drawerForm.lowerLimit > this.drawerForm.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS1"));
                return;
              }
            } else if (this.drawerForm.compareType === "<=>") {
              if (this.drawerForm.lowerLimit >= this.drawerForm.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS2"));
                return;
              }
            } else if (this.drawerForm.compareType === "<>=") {
              if (this.drawerForm.lowerLimit >= this.drawerForm.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS2"));
                return;
              }
            } else if (this.drawerForm.compareType === "<>") {
              if (this.drawerForm.lowerLimit >= this.drawerForm.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS2"));
                return;
              }
              // if (this.form.upperLimit - this.form.lowerLimit < 2) {
              //   this.$message.success(this.$t("CHECK_COMPARE_TIPS3"));
              //   return;
              // }
            } else if (this.drawerForm.compareType === "=") {
              if (this.drawerForm.lowerLimit !== this.drawerForm.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS4"));
                return;
              }
            }
          }
          if (
            !this.isEdit &&
            this.pcFrmItemList.some(
              (val) => val.itemName === this.drawerForm.itemName
            )
          ) {
            this.$message.warning(
              `${this.$t("PM_ITEM_NAME")}${this.$t("CANNOT_REPEAT")}`
            );
            return;
          }
          this.handleCloseDrawer();
          this.handleClearFormDrawerData();
          if (!this.isEdit) {
            this.pcFrmItemList.push({ ...this.drawerForm });
          } else {
            this.pcFrmItemList[this.editIndex] = { ...this.drawerForm };
          }
          this.selectedRowKeys = [];
          this.selectedRows = [];
        }
      });
    },
    // 监听清除
    handleClearFormDrawerData() {
      /* eslint-disable */
      switch (this.drawerForm.checkStyle) {
        case "BOOL":
          this.drawerForm.itemType = "";
          this.drawerForm.compareType = "";
          this.drawerForm.upperLimit = "";
          this.drawerForm.lowerLimit = "";
          this.drawerForm.autoMatchKey = "";
          this.drawerForm.textValue = "";
          break;
        case "NUMBER":
          this.drawerForm.textValue = "";
          if (this.drawerForm.itemType === "NORMAL") {
            this.drawerForm.autoMatchKey = "";
          }
          if (this.drawerForm.compareType === "<") {
            this.drawerForm.lowerLimit = "";
          } else if (this.drawerForm.compareType === ">") {
            this.drawerForm.upperLimit = "";
          }
          break;
        case "TEXT":
          this.drawerForm.itemType = "";
          this.drawerForm.compareType = "";
          this.drawerForm.upperLimit = "";
          this.drawerForm.lowerLimit = "";
          this.drawerForm.autoMatchKey = "";
          break;
      }
    },
    handleCloseDrawer() {
      this.confirmLoading = false;
      this.$refs.ruleFormDrawer.clearValidate();
      this.drawerVisible = false;
    },
    // 监听保存按钮点击事件
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // const { id, pcFrmCode, pcFrmName, pcCategoryId, opUrl } = this.form;
          let pcFrmItemList = [];
          if (this.pcFrmItemList.length > 0) {
            // eslint-disable-next-line array-callback-return
            pcFrmItemList = this.pcFrmItemList.map((item) => {
              const req = fieldExReqDataFn(item, this.dynamicFieldList);
              return req;
            });
          }
          this.confirmLoading = true;
          const params = {
            ...this.form,
            pcFrmItemList,
          };
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-frm`, params)
            .then(() => {
              this.confirmLoading = false;
              this.$message.success(this.$t("SAVE_SUCCESS"));
              this.handleCancel();
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/eqp_check/check_form",
        },
        vm: this,
      });
    },
    // 页面埋点
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, data)
        .then(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/fault_repair.less";
/deep/ .mega-design-business-table .mega-design-pro-table {
  padding: 0 !important;
  margin-bottom: 24px;
}
/deep/ .ant-form-item-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

<style lang="less">
.icon-bianji2 {
  color: @primary-color !important;
}
.status-btn {
  cursor: pointer;
  margin-top: 0;
  margin-left: 6px;
  min-width: 100px;
  height: 36px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  text-align: center;
  line-height: 36px;
  position: relative;
  padding: 0 6px;
}
.statusActive {
  border: 1px solid #ff3250;
}
.icon-box {
  padding: 5px;
  position: absolute;
  right: -1px;
  bottom: -1px;
  border-radius: 4px;
  .icon-gougou {
    color: #fff;
    height: 4px;
    font-size: 12px;
  }
  .icon-gougou::before {
    position: relative;
    top: -16px;
  }
}
</style>
