<template>
  <div class="page-wrapper page-tabs">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <!--  @change="callback" -->
        <a-tabs @change="changeTab">
          <a-tab-pane key="1" :tab="$t('BASIC_DATA')">
            <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" type="flex">
                  <a-col :span="8">
                    <a-form-model-item
                      :label="$t('EQP') + $t('CODE')"
                      prop="eqpCode"
                    >
                      <a-input
                        v-model="form.eqpCode"
                        disabled
                        :placeholder="$t('PLACEENTER')"
                        @change="
                          form.eqpCode = form.eqpCode.slice(0, 50).trim()
                        "
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('assetsCode')" :span="8">
                    <a-form-model-item
                      :label="$t('EPMS_ASSETS_CODE')"
                      prop="assetsCode"
                    >
                      <a-input
                        v-model="form.assetsCode"
                        :placeholder="$t('PLACEENTER')"
                        @change="
                          form.assetsCode = form.assetsCode.slice(0, 50).trim()
                        "
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('eqpName')" :span="8">
                    <a-form-model-item
                      :label="$t('EQUIPMENT_NAME')"
                      prop="eqpName"
                    >
                      <a-input
                        v-model="form.eqpName"
                        :placeholder="$t('PLACEENTER')"
                        @change="
                          form.eqpName = form.eqpName.slice(0, 50).trim()
                        "
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('eqpTypeId')" :span="8">
                    <a-form-model-item
                      :label="$t('EQP_TYPE')"
                      prop="eqpTypeId"
                      style="position: relative"
                    >
                      <a-select
                        ref="eqpTypeRef"
                        v-model="form.eqpTypeId"
                        :filter-option="false"
                        :placeholder="$t('PLACESELECT')"
                        show-search
                        @popupScroll="handlePopScroll"
                        @search="handleSearch"
                        @change="eqpTypeChange"
                        @focus="onFocus"
                      >
                        <a-select-option
                          v-for="(item, index) in eqpTypeList"
                          :key="index"
                          :disabled="item.enableFlag === 'N'"
                          :value="item.id"
                        >
                          {{ item.eqpTypeName }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    v-if="form.hasOwnProperty('locationFirstId')"
                    :span="8"
                  >
                    <a-form-model-item
                      :label="$t('CURRENT_LOCATION')"
                      prop="locationFirstIdArr"
                    >
                      <a-cascader
                        v-model="form.locationFirstIdArr"
                        disabled
                        :placeholder="$t('PLACESELECT')"
                        :options="currentOptions"
                        :field-names="fieldNames"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('assetsStatus')" :span="8">
                    <a-form-model-item
                      :label="$t('STATUS_OF_ASSETS')"
                      prop="assetsStatus"
                    >
                      <a-select
                        key="assetsStatus"
                        v-model="form.assetsStatus"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="item in assetsStatusList"
                          :key="item.value"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('owner')" :span="8">
                    <a-form-model-item :label="$t('CUSTODIAN')" prop="owner">
                      <template>
                        <div style="position: relative">
                          <select-user
                            ref="selectUser"
                            v-model="form.owner"
                            :multiple="false"
                            show-key="name"
                            :default-selected-rows="selectedUser"
                            @confirm="getReturnData"
                          />
                        </div>
                      </template>
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('assetsSource')" :span="8">
                    <a-form-model-item
                      :label="$t('SOURCE_OF_ASSETS')"
                      prop="assetsSource"
                    >
                      <a-select
                        key="assetsSource"
                        v-model="form.assetsSource"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="item in assetsSourceList"
                          :key="item.value"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('eqpModel')" :span="8">
                    <a-form-model-item :label="$t('EQP_MODEL')" prop="eqpModel">
                      <a-input
                        v-model="form.eqpModel"
                        :placeholder="$t('PLACEENTER')"
                        @change="
                          form.eqpModel = form.eqpModel.slice(0, 30).trim()
                        "
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('purchaseDate')" :span="8">
                    <a-form-model-item
                      :label="$t('PURCHASE_DATE')"
                      prop="purchaseDate"
                    >
                      <a-date-picker
                        v-model="form.purchaseDate"
                        style="width: 100%"
                        :placeholder="$t('PLACESELECT')"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('brand')" :span="8">
                    <a-form-model-item :label="$t('EQP_BRAND')" prop="brand">
                      <a-input
                        v-model="form.brand"
                        :placeholder="$t('PLACEENTER')"
                        @change="form.brand = form.brand.slice(0, 30).trim()"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.locationFirstId" :span="8">
                    <a-form-model-item
                      :label="$t('EQUIPMENT_SERIALNUM')"
                      prop="serialNum"
                    >
                      <a-input
                        v-model="form.serialNum"
                        :placeholder="$t('PLACEENTER')"
                        @keyup="
                          form.serialNum = form.serialNum.match(/\d+/)
                            ? form.serialNum.match(/\d+/)[0]
                            : ''
                        "
                        @blur="(e) => handleBlur(e, 'serialNum')"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('eqpShortName')" :span="8">
                    <a-form-model-item
                      :label="$t('EQUIPMENT_ABBREVIATION')"
                      prop="eqpShortName"
                    >
                      <a-input
                        v-model="form.eqpShortName"
                        :placeholder="$t('PLACEENTER')"
                        @change="
                          form.eqpShortName = form.eqpShortName
                            .slice(0, 50)
                            .trim()
                        "
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('eqpSpec')" :span="8">
                    <a-form-model-item
                      :label="$t('EQUIPMENT_SIZE')"
                      prop="eqpSpec"
                    >
                      <a-input
                        v-model="form.eqpSpec"
                        :placeholder="$t('PLACEENTER')"
                      />
                    </a-form-model-item>
                  </a-col>
                  <!-- 扩展字段 -->
                  {{
                    fieldExRenderFn($createElement, {
                      layout: "col",
                      itemSpan: 8,
                    })
                  }}
                  <slot name="RenderFieldExtendDom"></slot>
                </a-row>
                <a-row :gutter="24">
                  <a-col v-if="form.hasOwnProperty('imgUrl')" :span="8">
                    <a-form-model-item
                      :label="$t('EQUIPMENT_PICTURE')"
                      prop="imgUrl"
                    >
                      <SingleUpload v-model="form.imgUrl" />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
          <a-tab-pane key="2" :tab="$t('TECHNICAL_DATA')">
            <a-collapse
              v-model="activeKeyH"
              expand-icon-position="right"
              class="collapse-header-divide"
            >
              <a-collapse-panel key="h" :header="$t('TECHNICAL_DATA')">
                <a-row :gutter="24">
                  <a-col :span="24">
                    <a-form-model-item
                      :label-col="{ span: 0 }"
                      :wrapper-col="{ span: 24 }"
                      prop="techUrl"
                    >
                      <MultipleUploadFile
                        v-model="form.techUrl"
                        :file-url-list="form.techUrlList"
                        @canSave="(val) => (confirmLoading = val)"
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
          <a-tab-pane key="3" :tab="$t('EQUIPMENT_BOM')">
            <a-collapse
              v-model="activeKeyI"
              expand-icon-position="right"
              class="collapse-header-divide"
            >
              <a-collapse-panel key="i" :header="$t('EQUIPMENT_BOM')">
                <MomTable
                  ref="MomTable"
                  row-key="id"
                  :action-buttons="actionButtons"
                  :columns="columns"
                  :data-source="eqpMatFormParamList"
                  :pagination="false"
                  :whole="false"
                  @delete="handleDelete"
                >
                  <div slot="toolbar" class="button-top-table">
                    <a-button @click="handleAdd">
                      <a-icon type="plus" />
                      {{ $t("ADD_TO") }}{{ $t("SPARE_PART") }}
                    </a-button>
                  </div>
                  <template slot="realImgUrl" slot-scope="text, record">
                    <img class="eqp_picture" :src="record.realImgUrl || defaultImg" alt="" />
                  </template>
                  <div slot="matNumRequired" slot-scope="text, record">
                    <a-input-number
                      v-model="record.matNumRequired"
                      :min="1"
                      @change="handleChangeInput"
                    />
                  </div>
                </MomTable>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
          <a-tab-pane key="4" :tab="$t('EQP_ATTRIBUTE_INFO')">
            <a-collapse
              v-model="activeKeyC"
              expand-icon-position="right"
              class="collapse-header-divide"
            >
              <a-collapse-panel
                key="c"
                :header="`${$t('EQUIPMENT_CONDITION_MGMT')}${$t(
                  'RELEVANT_INFORMATION'
                )}`"
              >
                <a-row :gutter="24" type="flex">
                  <a-col
                    v-if="form.hasOwnProperty('changeStatusFlag')"
                    :span="8"
                  >
                    <a-form-model-item
                      :label="$t('CHANGEABLE_STATUS')"
                      prop="changeStatusFlag"
                    >
                      <a-radio-group v-model="form.changeStatusFlag">
                        <a-radio
                          v-for="item in yesNoList"
                          :key="item.value"
                          :value="item.value"
                          >{{ item.label }}</a-radio
                        >
                      </a-radio-group>
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('oeeFlag')" :span="8">
                    <a-form-model-item :label="$t('USE_OEE')" prop="oeeFlag">
                      <a-radio-group v-model="form.oeeFlag">
                        <a-radio
                          v-for="item in yesNoList"
                          :key="item.value"
                          :value="item.value"
                          >{{ item.label }}</a-radio
                        >
                      </a-radio-group>
                    </a-form-model-item>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('keyEqpFlag')" :span="8">
                    <a-form-model-item
                      :label="$t('KEY_LINE')"
                      prop="keyEqpFlag"
                    >
                      <a-select
                        v-model="form.keyEqpFlag"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="(item, index) in keyEqpFlagList"
                          :key="index"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-collapse-panel>
            </a-collapse>
            <a-collapse
              v-model="activeKeyD"
              expand-icon-position="right"
              class="collapse-header-divide"
            >
              <a-collapse-panel
                key="d"
                :header="`${$t('EPMS_CALL_REPAIR')}${$t(
                  'RELEVANT_INFORMATION'
                )}`"
              >
                <a-row :gutter="24" type="flex">
                  <a-col v-if="form.hasOwnProperty('eqpCategory')" :span="8">
                    <a-form-model-item
                      :label="$t('ACCOUNT_TYPE')"
                      prop="eqpCategory"
                    >
                      <a-select
                        v-model="form.eqpCategory"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="(item, index) in eqpCategoryList"
                          :key="index"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    v-if="
                      form.locationFirstIdArr &&
                      form.locationFirstIdArr.length &&
                      form.locationFirstIdArr[0] === 'LINE'
                    "
                    :span="8"
                  >
                    <a-form-model-item :label="$t('STATION')" prop="stationId">
                      <a-select
                        v-model="form.stationId"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="(item, index) in stationList"
                          :key="index"
                          :value="item.id"
                        >
                          {{ item.stationName }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                    <a-tooltip placement="top" :title="$t('STATION_TIPS')">
                      <span class="station-tips">{{ $t("STATION_TIPS") }}</span>
                    </a-tooltip>
                  </a-col>
                  <a-col v-if="form.hasOwnProperty('autoCallFlag')" :span="8">
                    <a-form-model-item
                      :label="$t('AUTOMATIC_REPAIR')"
                      prop="autoCallFlag"
                    >
                      <a-radio-group v-model="form.autoCallFlag">
                        <a-radio
                          v-for="item in yesNoList"
                          :key="item.value"
                          :value="item.value"
                          >{{ item.label }}</a-radio
                        >
                      </a-radio-group>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-collapse-panel>
            </a-collapse>
            <a-collapse
              v-model="activeKeyE"
              expand-icon-position="right"
              class="collapse-header-divide"
            >
              <a-collapse-panel
                key="e"
                :header="`${$t('PM')}${$t('RELEVANT_INFORMATION')}`"
              >
                <a-row :gutter="24" type="flex">
                  <a-col v-if="form.hasOwnProperty('lifeRemain')" :span="8">
                    <a-form-model-item
                      :label="$t('EQUIPMENT_LIFE')"
                      prop="lifeRemain"
                    >
                      <a-input-number
                        v-model="form.lifeRemain"
                        class="relative"
                        style="width: 94%"
                        :min="1"
                        :placeholder="$t('PLACEENTER')"
                      />
                      <div class="input_right_text">{{ $t("MONTH") }}</div>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button :loading="confirmLoading" type="primary" @click="confirm">
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("CANCEL") }}
      </a-button>
    </div>
    <!-- 选择备件清单组件 -->
    <select-eqp-bom
      ref="SelectSparePart"
      show-key="id"
      :show-slot="false"
      @confirm="getReturnDataSpare"
    />
    <MegaDrawer
      width="1000"
      :title="`${$t('PFM4010')}`"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model slot="main" ref="formAuth" :model="formAuth">
        <a-tabs v-model="activeKeyAuth">
          <a-tab-pane
            v-for="(table, tableIndex) in formAuth.tableList"
            :key="table.tableName"
            :tab="table.tableComment"
          >
            <MomTable
              ref="TableInfo"
              :visible="infoTableVisible"
              :row-key="rowKeySet"
              :columns="infoColumns"
              :data-source="table.fieldList"
              :show-util-operator="false"
              :pagination="false"
              :mega-extend="{
                rowAction: false,
              }"
            >
              <span slot="i18nCode" slot-scope="item">{{ $t(item) }}</span>
              <span slot="enableFlag" slot-scope="item, record">
                <a-switch
                  :checked="item === 'Y'"
                  @change="onChangeFlag($event, record, tableIndex)"
                />
              </span>
            </MomTable>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import moment from "moment";
import { mapGetters, mapState } from "vuex";
import { deleteLeafArray } from "@mega-apps/utils";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { fetchFileUrl } from "@/utils/file";
import FieldExtendMixin from "@/mixins/fieldExtend";
import SingleUpload from "@/components/uploadPicture/singleUpload";
import MultipleUploadFile from "@/components/uploadFile/multipleUpload";
import SelectEqpBom from "@/components/epms/SelectEqpBom";
import SelectUser from "@/components/epms/SelectUser";
import breadcrumb from "@/components/breadcrumb";

export default {
  components: {
    SelectEqpBom,
    SelectUser,
    MegaDrawer,
    SingleUpload,
    breadcrumb,
    MultipleUploadFile,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      // eslint-disable-next-line
      defaultImg: require("@/assets/img/attachmentImg.png"),
      breadcrumbData: [
        {
          name: this.$t("EQUIPMENT_LEDGER"),
          url: "/eam/account_management/equipment_account",
        },
        { name: this.$t("EDIT"), url: "" },
      ],
      activeKey: "a",
      activeKeyB: "b",
      activeKeyC: "c",
      activeKeyD: "d",
      activeKeyE: "e",
      activeKeyH: "h",
      activeKeyI: "i",
      activeKeyAuth: "",
      confirmLoading: false,
      fileUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file`,
      fieldNames: { label: "label", value: "code", children: "children" },
      selectedUser: [],
      uploaderOptions: {
        allowDuplicateUploads: true,
        target: `${ApiConstant.PREFIX_CORE}/api/mom-file/update-one`,
        testChunks: true,
        chunkSize: 10 * 1024 * 1024,
      },
      currentProps: {
        value: "code",
        label: "label",
      },
      currentOptions: [
        {
          code: "LINE",
          label: "车间",
          children: [],
        },
        {
          code: "WAREHOUSE",
          label: "仓库",
          children: [],
        },
      ],
      techUrlList: [], // 设备类型绑定的技术资料
      form: {
        id: "",
        assetsCode: "", // 资产编码
        eqpCode: "", // 设备编码
        eqpName: "", // 设备名称
        eqpCategory: "", // 台账类型
        eqpTypeId: "", // 设备类型
        eqpModel: "", // 规格型号
        assetsSource: "", // 资产来源
        assetsStatus: "UNPURCHASED", // 资产状态
        eqpShortName: "", // 设备简称
        purchaseDate: "", // 采购日期
        brand: "", // 设备品牌
        eqpSpec: "", // 设备尺寸
        owner: "", // 负责人
        ownerName: "", // 负责人
        locationFirstIdArr: [], // 当前位置
        stationId: "", // 工位
        locationFirstId: "",
        serialNum: "", // 设备序号
        lifeRemain: "", // 设备寿命
        imgUrl: "", // 设备图片地址
        changeStatusFlag: "Y", // 可变更状态
        oeeFlag: "Y", // 使用oee
        autoCallFlag: "Y", // 是否自动叫修
        keyEqpFlag: "", // 生产线关键设备
        techUrl: [],
      },
      formBack: {
        assetsCode: "", // 资产编码
        eqpCode: "", // 设备编码
        eqpName: "", // 设备名称
        eqpCategory: "", // 台账类型
        eqpTypeId: "", // 设备类型
        eqpModel: "", // 规格型号
        assetsSource: "", // 资产来源
        assetsStatus: "UNPURCHASED", // 资产来源
        eqpShortName: "", // 设备简称
        purchaseDate: "", // 采购日期
        brand: "", // 设备品牌
        eqpSpec: "", // 设备尺寸
        owner: "", // 负责人
        ownerName: "", // 负责人
        locationFirstIdArr: [], // 当前位置
        stationId: "", // 工位
        locationFirstId: "",
        serialNum: "", // 设备序号
        lifeRemain: "", // 设备寿命
        imgUrl: "", // 设备图片地址
        changeStatusFlag: "Y", // 可变更状态
        oeeFlag: "Y", // 使用oee
        autoCallFlag: "Y", // 是否自动叫修
        keyEqpFlag: "", // 生产线关键设备
        techUrl: [],
      },
      treeProps: {
        value: "code",
        children: "children",
        label: "label",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      eqpCategoryList: [], // 台账类型
      eqpTypeList: [], // 设备类型
      assetsSourceList: [], // 资产来源
      assetsStatusList: [], // 资产状态
      keyEqpFlagList: [], // 生产线关键设备
      tableNameList: [
        {
          key: "epm_eqp",
          tab: "设备管理",
        },
      ],
      dataAttr: {
        form: "form",
      },
      fielfNameArr: [],
      userArr: [],
      yesNoList: [],
      drawerVisible: false,
      infoTableVisible: false,
      moduleList: [],
      infoDataSource: [],
      infoColumns: [
        {
          dataIndex: "fieldName", // 字段名
          sorter: false,
          title: () => `${this.$t("FIELD")}${this.$t("NAME")}`,
        },
        {
          dataIndex: "i18nCode", // 国际化
          sorter: false,
          title: () => `${this.$t("I18N")}`,
          scopedSlots: { customRender: "i18nCode" },
        },
        // {
        //   dataIndex: "fieldComment", // 字段说明
        //   sorter: false,
        //   title: () => `${this.$t("FIELD")}${this.$t("DESCRIBE")}`,
        // },
        {
          dataIndex: "enableFlag", // 是否显示
          sorter: false,
          title: () => this.$t("IS_SHOW"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
      ],
      formAuth: {
        tableList: [],
      },
      timer: null,
      eqpTypePage: 1,
      eqpTypeTotal: 0,
      eqpTypeName: "",
      eqpTypeNameEdit: "",
      stationList: [],
      actionButtons: ["delete"],
      columns: [
        {
          dataIndex: "realImgUrl",
          width: 100,
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "realImgUrl" },
          title: () => this.$t("CORE_PICTURE"), // 图片
        },
        {
          dataIndex: "matCode", // 备件料号
          title: () => this.$t("SPARE_PART_ITEM_NO"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "matName", // 备件名称
          title: () => this.$t("SPARE_PART_NAME"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "matTypeName", // 备件类型
          width: 150,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("SPARE_PART_TYPE"),
        },
        {
          dataIndex: "matSpec", // 规格型号
          title: () => this.$t("EQP_MODEL"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "matNumRequired", // 备件需上机数量
          width: 300,
          sorter: false,
          title: () => this.$t("QUANTITY_OF_SPARE_PARTS_TO_BE_INSTALLED"),
          scopedSlots: { customRender: "matNumRequired" },
        },
      ],
      eqpMatFormParamList: [], // 备件清单
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapGetters(["modules"]),
    rules() {
      return {
        eqpCode: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        // assetsCode: [
        //   {
        //     required: true,
        //     max: 50,
        //     message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
        //     trigger: "blur",
        //   },
        // ],
        assetsStatus: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        eqpName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        eqpCategory: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        eqpTypeId: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        // eqpModel: [
        //   {
        //     required: true,
        //     max: 30,
        //     message: this.$t("PLACEENTER") + 30 + this.$t("LENGTH_TIP"),
        //     trigger: "blur",
        //   },
        // ],
        locationFirstIdArr: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        // stationId: [
        //   {
        //     required: true,
        //     message: this.$t("PLACESELECT"),
        //     trigger: "change",
        //   },
        // ],
        owner: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        changeStatusFlag: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        oeeFlag: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        autoCallFlag: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
  },
  watch: {
    "form.imgUrl": {
      handler(newVal, oldVal) {
        if (!newVal) return;
        if (newVal !== oldVal) {
          const params = {
            funcKeys: ["equipment-picture"],
            type: "USE",
            clientCode: ApiConstant.clientCode,
          };
          this.handleFuncUseRate(params);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // 数据详情
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp/get-by-id/${id}`)
        .then((res) => {
          const { eqpTechBPOList, eqpMatBPOList } = { ...res.data?.data };
          const techUrlList = eqpTechBPOList.map((item) => {
            const { techName, techUrl } = item;
            return {
              name: techName,
              fileUrl: techUrl,
            };
          });
          const techUrlListCus =
            techUrlList && techUrlList.length
              ? techUrlList.filter((item) => item.fileUrl)
              : [];
          if (eqpMatBPOList && eqpMatBPOList.length > 0) {
            eqpMatBPOList.map((item, index) => {
              if (item.imgUrl) {
                eqpMatBPOList[index].realImgUrl = fetchFileUrl(item.imgUrl?.split(",")[1], this);
              }
              return item;
            });
          }
          this.eqpMatFormParamList = [...eqpMatBPOList];
          const { data = {} } = res.data;
          const form = {
            ...data,
            techUrlList: techUrlListCus,
            techUrl: techUrlListCus,
          };
          this.form = this.fieldExResDataFn(form);
          this.formBack = this.fieldExResDataFn(form);
          this.form.id = id;
          this.selectedUser = [
            { userName: this.form.owner, name: this.form.ownerName },
          ];
          this.form.locationFirstIdArr = [
            this.form.locationType,
            this.form.locationFirstId,
            this.form.locationSecondId,
            this.form.locationThirdId,
          ];
          if (this.form.locationType === "LINE") {
            this.getStationList(this.form.locationThirdId);
          }
          this.eqpTypeList = [
            {
              id: res.data?.data?.eqpTypeId,
              eqpTypeName: res.data?.data?.eqpTypeName,
            },
          ];
          this.eqpTypeName = res.data?.data?.eqpTypeName;
          this.getEqpType();
          // 扩展字段
          this.init();
        });
    }
  },
  mounted() {
    this.$axios
      .get(`${ApiConstant.PREFIX_CORE}/api/mdm/user/search-with-site`)
      .then((res) => {
        if (res.data.data.records.length > 0) {
          this.userArr = res.data.data.records;
        }
      });
  },
  methods: {
    // 监听input数据变化
    handleChangeInput() {
      this.$forceUpdate();
    },
    // 监听新增点击事件
    handleAdd() {
      this.$refs.SelectSparePart.openDialog();
    },
    // 监听删除点击事件
    handleDelete(row) {
      const index = this.eqpMatFormParamList.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.eqpMatFormParamList.splice(index, 1);
        },
      });
    },
    // 获取返回数据，备件清单
    getReturnDataSpare(selectedKeys, selectedRows) {
      if (selectedRows && selectedRows.length > 0) {
        selectedRows.forEach((item) => {
          // eslint-disable-next-line no-param-reassign
          item.matNumRequired = 1;
        });
        if (selectedRows && selectedRows.length > 0) {
          selectedRows.map((item, index) => {
            if (item.imgUrl) {
              selectedRows[index].realImgUrl = fetchFileUrl(item.imgUrl?.split(",")[1], this);
            }
            return item;
          });
        }
        this.eqpMatFormParamList =
          this.eqpMatFormParamList.concat(selectedRows);
        this.handleItemList();
      }
    },
    // 监听列表
    handleItemList() {
      // eslint-disable-next-line array-callback-return
      this.eqpMatFormParamList.map((item, index) => {
        // eslint-disable-next-line no-param-reassign
        item.fieldExtendList = this.fieldExtendList;
      });
      this.eqpMatFormParamList = uniqBy(this.eqpMatFormParamList, "matCode"); // 去重
    },
    init() {
      // 扩展字段
      this.queryFieldExtend().then((res) => {
        this.form = {
          ...this.formBack,
          ...this.form,
        };
        /* eslint-disable */
        if (res.data.data.fieldHiddenConfigList?.length) {
          const arr = [];
          res.data.data.fieldHiddenConfigList.forEach((item) => {
            arr.push(item.fieldName);
          });
          arr.forEach((item) => {
            this.hasFunction(this.form, item);
          });
        }
        this.$forceUpdate();
        /* eslint-enable */
      });
      // 获取当前位置的三级树
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp/location-tree`)
        .then((res) => {
          deleteLeafArray(res.data.data.lineTree, "children");
          deleteLeafArray(res.data.data.warehouseTree, "children");
          this.currentOptions[0].children = res.data.data.lineTree;
          this.currentOptions[1].children = res.data.data.warehouseTree;
        });
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:EQP_CATEGORY`
        ), // 是否
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ASSETS_SOURCE`
        ), // 资产来源
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ASSETS_STATUS`
        ), // 资产状态
      ]).then(
        ([yesNoRes, eqpCategoryRes, assetsSourceRes, assetsStatusRes]) => {
          this.yesNoList = yesNoRes.data.data;
          this.keyEqpFlagList = yesNoRes.data.data;
          this.eqpCategoryList = eqpCategoryRes.data.data;
          this.assetsSourceList = assetsSourceRes.data.data;
          this.assetsStatusList = assetsStatusRes.data.data;
        }
      );
    },
    // 清除数据
    clearData() {
      this.eqpTypeName = "";
      this.eqpTypePage = 1;
      this.eqpTypeList = [];
      this.eqpTypeTotal = 0;
    },
    onFocus() {
      if (this.eqpTypeName) {
        this.clearData();
        this.getEqpType();
      }
    },
    handleBlur(e, key) {
      const val = +e.target.value;
      if (val > 999999) {
        this.form[key] = 999999;
      } else {
        this.form[key] = Number(val);
      }
    },
    changeTab(key) {
      if (key === "2") {
        // 技术资料字段重新赋值
        const { techUrl, techUrlList } = this.form;
        this.form.techUrl = [];
        this.form.techUrlList = [];
        this.$nextTick(() => {
          this.form.techUrl = techUrl;
          this.form.techUrlList = techUrlList;
        });
      }
    },
    handleSearch(value) {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.clearData(); // 清除数据
        this.eqpTypeName = value;
        this.getEqpType(); // 调用接口
        clearTimeout(this.timer);
      }, 100);
    },
    handlePopScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target;
      if (scrollHeight - scrollTop === clientHeight) {
        this.eqpTypePage += 1;
        this.getEqpType();
      }
    },
    // 设备类型改变
    eqpTypeChange(val) {
      this.eqpTypeNameEdit = "";
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-type/${val}`, {
          params: { isCancelApiLoad: true },
        })
        .then((res) => {
          const {
            autoCallFlag,
            oeeFlag,
            imgUrl,
            eqpCategory,
            keyEqpFlag,
            owner,
            ownerName,
            eqpTypeTechBPOList = [],
            eqpTypeMatBPOList,
          } = res.data.data;
          const techUrlList = eqpTypeTechBPOList.length
            ? eqpTypeTechBPOList.map((item) => {
                const { techName, techUrl } = item;
                return {
                  name: techName,
                  fileUrl: techUrl,
                };
              })
            : [];
          this.form.oeeFlag = oeeFlag;
          this.form.autoCallFlag = autoCallFlag;
          this.form.eqpCategory = eqpCategory;
          this.form.keyEqpFlag = keyEqpFlag;
          this.form.owner = owner;
          this.form.ownerName = ownerName;
          this.selectedUser = [{ userName: owner, name: ownerName }];
          // 去除上一个设备类型的技术资料
          const techUrl = this.form.techUrl ? this.form.techUrl : [];
          this.techUrlList
            .filter((item) => item.fileUrl)
            .forEach((itemA) => {
              if (!techUrl.length) return;
              const result = techUrl.findIndex(
                (itemB) => itemB.fileUrl === itemA.fileUrl
              );
              if (result > -1) {
                techUrl.splice(result, 1);
              }
            });
          // 技术资料字段重新赋值
          const hash = {};
          const fileList = [...techUrl, ...techUrlList].reduceRight(
            (item, next) => {
              // eslint-disable-next-line no-unused-expressions
              hash[next.fileUrl]
                ? ""
                : (hash[next.fileUrl] = true && item.push(next));
              return item;
            },
            []
          );
          this.form.techUrl = [...fileList];
          this.form.techUrlList = [...fileList];
          // 当前设备类型的技术资料
          this.techUrlList = [...techUrlList];
          if (this.form.imgUrl) return;
          this.form.imgUrl = imgUrl;
          this.$confirm({
            title: this.$t("PROMPTING"),
            content: this.$t("SYNCHRONIZE_EQUIPMENT_BOM_DETAILS"),
            okText: this.$t("CONFIRM"),
            cancelText: this.$t("CANCEL"),
            centered: false,
            onOk: () => {
              this.eqpMatFormParamList = [...eqpTypeMatBPOList];
            },
          });
        });
    },
    // 获取设备类型列表
    getEqpType() {
      if (this.eqpTypeTotal <= this.eqpTypeList.length && this.eqpTypeTotal)
        return;
      const params = {
        eqpTypeName: this.eqpTypeName || "",
        size: 20,
        sortRule: "DESC",
        sortColumn: "enableFlag",
        page: this.eqpTypePage,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-type/search`, {
          params,
        })
        .then((res) => {
          this.eqpTypeList = [...this.eqpTypeList, ...res.data.data.records];
          this.eqpTypeTotal = res.data.data.total;
        });
    },
    // 字段授权
    hanldeFieldAuth() {
      const params = {
        tableNameList: "epm_eqp",
        moduleCode: this.$store.state.activatedModule,
      };
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-column-batch-by-module`,
          {
            params,
          }
        )
        .then((res) => {
          if (res?.data?.data && res?.data?.data.length > 0) {
            this.activeKeyAuth = res.data.data[0].tableName;
            this.formAuth.tableList = res.data.data;
          }
        });
      this.drawerVisible = true;
    },
    // 开关
    onChangeFlag(e, data, tableIndex) {
      // 获取表单下的数据
      this.formAuth.tableList[tableIndex].fieldList.forEach((item, index) => {
        if (item.fieldName === data.fieldName) {
          this.formAuth.tableList[tableIndex].fieldList[index].enableFlag = e
            ? "Y"
            : "N";
        }
      });
    },
    // 设置rowkey
    rowKeySet(record) {
      return `${this.form.tableName} ${record.fieldName}`;
    },
    getStationList(id) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/mdm/fac-station/list-by-line-id?lineIdList=${id}`
        )
        .then((res) => {
          this.stationList = res.data.data;
        });
    },
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, {
          ...data,
          isCancelApiLoad: true,
        })
        .then(() => {});
    },
    // 负责人弹框显示
    selectUser() {
      this.$refs.selectUser.openDialog();
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      this.form.owner = selectedRows[0]?.userName;
      this.selectedUser = selectedRows;
    },
    hasFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        delete this.form[val];
        delete this.fieldExForm[val];
      }
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/eam/account_management/equipment_account" },
        vm: this,
      });
    },
    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const arr = this.form.locationFirstIdArr;
          [
            this.form.locationType,
            this.form.locationFirstId,
            this.form.locationSecondId,
            this.form.locationThirdId,
          ] = arr;
          const bomArr = this.eqpMatFormParamList.map((item) => {
            return {
              id: item.id,
              matCode: item.matCode,
              matNumRequired: item.matNumRequired,
            };
          });
          const { purchaseDate, techUrl } = this.form;
          let req = {
            ...this.form,
            purchaseDate: purchaseDate ? moment(purchaseDate).format("YYYY-MM-DD") : "",
            eqpMatFormParamList: bomArr,
            techUrlList: techUrl.length
              ? techUrl.map((item) => item.fileUrl)
              : [],
          };
          req = this.fieldExReqDataFn(req);
          this.confirmLoading = true;
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp`, req)
            .then((res) => {
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.confirmLoading = false;
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/eam/account_management/equipment_account" },
                vm: this,
              });
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        } else {
          this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
    },
    // 字段授权 保存
    handleSave() {
      const { tableList } = this.formAuth;
      const data = {
        moduleCode: this.$store.state.activatedModule,
        paramList: tableList,
      };
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/save-batch-by-module`,
          data
        )
        .then(() => {
          this.$message.success(this.$t("EDIT_SUCCESS"));
          this.drawerVisible = false;
          this.init();
        });
    },
    // 字段扩展刷新
    handleRefresh() {
      this.fieldExForm = {};
      this.queryFieldExtend();
    },
    // 字段授权弹框 取消
    handleCancel() {
      const params = {
        tableNameList: "epm_eqp",
        moduleCode: this.$store.state.activatedModule,
      };
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-column-batch-by-module`,
          {
            params,
          }
        )
        .then((res) => {
          if (res?.data?.data && res?.data?.data.length > 0) {
            this.activeKeyAuth = res.data.data[0].tableName;
            this.formAuth.tableList = res.data.data;
          }
        });
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="less">
.page-wrapper.page-tabs {
  margin: -11px -12px;
  .ant-tabs {
    .ant-tabs-bar.ant-tabs-top-bar {
      margin: 0;
      padding-left: 12px;
      border-bottom: 12px solid #f0f2f5;
      background: #fff;
    }
    .ant-tabs-content.ant-tabs-top-content {
      .ant-tabs-tabpane {
        margin: 0 12px !important;
        width: calc(100% - 24px);
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.el-select-tree {
  width: 100%;
}
.equipment-add {
  /deep/ .el-input-number,
  .el-date-editor {
    min-width: 100%;
  }
}
.eqp_type_name {
  pointer-events: none;
  width: 80%;
  height: 34px;
  position: absolute;
  top: -7px;
  left: 9px;
  background: #fff;
  line-height: 34px;
  overflow: hidden;
}
.input_right_text {
  position: absolute;
  top: -10px;
  right: -20px;
}
.station-tips {
  position: absolute;
  display: inline-block;
  width: 66.5%;
  top: 42px;
  left: 33.5%;
  font-size: 14px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
