<template>
  <a-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 16 }"
  >
    <a-collapse
      v-model="activeKey"
      expand-icon-position="right"
      class="collapse-header-divide"
      :class="{ 'show-red-border': showRedBorder === true }"
    >
      <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"
                :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">
              <SelectSearch
                :show-multiple="false"
                request-api="/api/epm/eam/eqp-type/search"
                :show-red-border="showRedBorder"
                option-label="eqpTypeName"
                :default-selected-keys="form.eqpTypeId"
                :default-selected-names="form.eqpTypeName"
                @change="onSelectSearchChange"
              >
              </SelectSearch>
            </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"
                :placeholder="$t('PLACESELECT')"
                :options="currentOptions"
                :field-names="fieldNames"
                @change="handleChangeLocation"
              />
            </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.locationFirstIdArr.length" :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>
          <slot></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-form-model>
</template>

<script>
import { mapState } from "vuex";
import { deleteLeafArray } from "@mega-apps/utils";
import ApiConstant from "@/api/ApiConstant";
import SingleUpload from "@/components/uploadPicture/singleUpload";

import SelectSearch from "@/components/epms/SelectSearch";

export default {
  name: "",
  components: { SingleUpload, SelectSearch },
  props: {
    // 是否显示slot
    showSlot: {
      type: Boolean,
      default: true,
    },
    form: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      isFirstOpen: true,
      activeKey: "a",
      activeKeyB: "b",
      activeKeyC: "c",
      activeKeyD: "d",
      fileUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file`,
      fieldNames: { label: "label", value: "code", children: "children" },
      selectedUser: [],
      currentOptions: [
        {
          code: "LINE",
          label: "车间",
          children: [],
        },
        {
          code: "WAREHOUSE",
          label: "仓库",
          children: [],
        },
      ],
      eqpTypeList: [], // 设备类型
      assetsSourceList: [], // 资产来源
      assetsStatusList: [], // 资产来源
      stationList: [],
      techUrlList: [], // 设备类型绑定的技术资料
    };
  },
  computed: {
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
    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",
          },
        ],
        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",
          },
        ],
        owner: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {
    "form.imgUrl": {
      handler(newVal, oldVal) {
        if (newVal) {
          const params = {
            funcKeys: ["equipment-picture"],
            type: "USE",
            clientCode: ApiConstant.clientCode,
          };
          this.handleFuncUseRate(params);
        }
        // ...
      },
      deep: true,
      immediate: true,
    },
    form: {
      handler(newVal, oldVal) {
        this.selectedUser = [];
        if (newVal.owner) {
          this.selectedUser = [
            { userName: newVal.owner, name: newVal.ownerName },
          ];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.isFirstOpen = true;
    this.init();
  },
  methods: {
    // 初始化数据
    init() {
      // 资产来源
      this.getDictByCode("DIC:EPM:ASSETS_SOURCE").then((res) => {
        this.assetsSourceList = res.data.data;
      });
      // 资产状态
      this.getDictByCode("DIC:EPM:ASSETS_STATUS").then((res) => {
        this.assetsStatusList = res.data.data;
      });
      // 获取当前位置的三级树
      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;
        });
    },
    handleBlur(e, key) {
      const val = +e.target.value;
      if (val > 999999) {
        this.form[key] = 999999;
      } else {
        this.form[key] = Number(val);
      }
    },
    getValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve({ valid, form: this.form });
          }
        });
      });
    },
    onSelectSearchChange(e) {
      this.form.eqpTypeId = e;
      this.eqpTypeChange(e);
    },
    // 设备类型改变
    eqpTypeChange(val) {
      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;
          // 去除上一个设备类型的技术资料
          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];
          // eslint-disable-next-line no-prototype-builtins
          if (this.form.hasOwnProperty("imgUrl")) {
            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.form.eqpMatFormParamList = [...eqpTypeMatBPOList];
            },
          });
        });
    },
    handleChangeLocation() {
      this.$forceUpdate();
      // 根据线别id获取工位列表
      const [locationType, locationFirstId, locationSecondId, locationThirdId] =
        this.form.locationFirstIdArr;
      if (locationType === "LINE") {
        this.form.stationId = "";
        // this.getStationList(locationThirdId);
      }
    },
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, {
          ...data,
          isCancelApiLoad: true,
        })
        .then(() => {});
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      // eslint-disable-next-line vue/no-mutating-props
      this.form.owner = selectedRows[0]?.userName;
      this.form.ownerName = selectedRows[0]?.name;
      this.selectedUser = selectedRows;
    },
  },
};
</script>

<style lang="less" scoped>
.show-red-border {
  border: 2px solid red !important;
  border-radius: 6px;
}
.app .ant-collapse + .ant-collapse {
  border-top: 8px solid #f0f2f5 !important;
}
.show-red-border-span {
  border: 2px solid red;
  border-radius: 6px;
  display: inline-block;
}
.show-red-border-select {
  border: 2px solid red;
  border-radius: 6px;
  display: block;
}
.el-select-tree {
  width: 100%;
}
.equipment-add {
  /deep/ .el-input-number,
  .el-date-editor {
    min-width: 100%;
  }
}
.input_right_text {
  position: absolute;
  top: -10px;
  right: -20px;
}
</style>
