<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('CODE')" prop="code" allow-clear>
                  <a-input
                    v-model="form.code"
                    disabled
                    :placeholder="$t('PLACEENTER')"
                    @change="form.code = form.code.slice(0, 50).trim()"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('TITLE')" prop="name" allow-clear>
                  <a-input
                    v-model="form.name"
                    :placeholder="$t('PLACEENTER')"
                    @change="form.name = form.name.slice(0, 50).trim()"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('TRANSFER_TYPE')"
                  prop="type"
                  allow-clear
                >
                  <a-select
                    v-model="form.type"
                    :placeholder="$t('PLACEENTER')"
                    @change="changeCurrentOptions"
                  >
                    <a-select-option
                      v-for="(item, index) in transferTypeList"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="
                  form.type === 'LINE_TO_WAREHOUSE' ||
                  form.type === 'WAREHOUSE_TO_LINE'
                "
                :span="8"
              >
                <a-form-model-item
                  :label="
                    form.type === 'LINE_TO_WAREHOUSE'
                      ? $t('SET_AS_IDLE')
                      : $t('SET_AS_IN_USE')
                  "
                  prop="assetsStatusSetFlag"
                >
                  <a-radio-group v-model="form.assetsStatusSetFlag">
                    <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 :span="8">
                <a-form-model-item
                  :label="$t('TARGET_PLANT')"
                  prop="toSiteCode"
                  allow-clear
                >
                  <a-select
                    v-model="form.toSiteCode"
                    :placeholder="$t('PLACEENTER')"
                    @change="siteChange"
                  >
                    <a-select-option
                      v-for="(item, index) in sitePermission"
                      :key="index"
                      :value="item.siteCode"
                      >{{ item.siteName }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('TRANSFER_TARGET_POSITION')"
                  prop="locationFirstIdArr"
                >
                  <a-cascader
                    v-model="form.locationFirstIdArr"
                    :placeholder="$t('PLACESELECT')"
                    :options="currentOptions"
                    :field-names="fieldNames"
                  >
                    <template
                      slot="displayRender"
                      slot-scope="{ labels, selectedOptions }"
                    >
                      <span
                        v-for="(label, index) in labels"
                        :key="selectedOptions[index].value"
                      >
                        <span v-if="index !== 0">{{ label }} /</span>
                      </span>
                    </template>
                  </a-cascader>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('RECEIVER_DEPT')" prop="toDeptId">
                  <a-tree-select
                    v-model="form.toDeptId"
                    :replace-fields="treeProps"
                    tree-check-strictly
                    :tree-data="treeData"
                    allow-clear
                    @change="handChangeToDep"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('RECIPIENT')" prop="toUserId">
                  <template>
                    <div style="position: relative">
                      <select-user
                        ref="selectUser"
                        v-model="form.toUserId"
                        :multiple="false"
                        show-key="name"
                        :default-selected-rows="selectedToUser"
                        :search-params="searchToParams"
                        @confirm="getToReturnData"
                      />
                    </div>
                  </template>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('AUDIT_PROCESS')"
                  prop="checkProcessId"
                >
                  <SelectSearch
                    :show-multiple="false"
                    :need-disabled="true"
                    query-list-key="searchKey"
                    request-api="/api/epm/ebs/epm-check-process/search?checkProcessTypeList=TRANSFER_CHECK"
                    option-label="checkProcessName"
                    option-value="id"
                    :default-selected-keys="form.checkProcessId"
                    @change="onSelectSearchChange"
                  />
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('remark')" :span="8">
                <a-form-model-item :label="$t('REMARK')" prop="remark">
                  <a-input
                    v-model="form.remark"
                    :placeholder="$t('PLACEENTER')"
                    onkeyup="value=value.slice(0, 50)"
                  />
                </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('EQUIPMENT_LIST')">
            <MomTable
              ref="MomTable"
              row-key="itemName"
              :action-buttons="actionButtons"
              :columns="columns"
              :data-source="eqpList"
              :pagination="false"
              @delete="handleDelete"
            >
              <div slot="toolbar" class="button-top-table">
                <a-button @click="handleselectEqp()">{{
                  `${$t("ADD")}`
                }}</a-button>
              </div>
              <template slot="assetsStatus" slot-scope="text, record">
                <span class="status-box" :class="text">{{
                  formatData(assetsStatusList, record.assetsStatus)
                }}</span>
              </template>
            </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">
      <a-button
        type="primary"
        :loading="confirmLoading"
        @click="handleSave('save')"
      >
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button
        :loading="confirmLoading"
        type="primary"
        @click="handleSave('saveAndApproval')"
      >
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE_AND_SUBMIT_FOR_APPROVAL") }}
      </a-button>
      <a-button @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("CANCEL") }}
      </a-button>
    </div>
    <!-- 选择设备清单组件 -->
    <select-eqp
      ref="selectEqp"
      show-key="id"
      :show-slot="false"
      :default-selected-rows="eqpList"
      @confirm="getEqpReturnData"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";
import { deleteLeafArray } from "@mega-apps/utils";
import { uniqBy } from "lodash";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";
import SelectEqp from "@/components/SelectEqp";

export default {
  components: {
    breadcrumb,
    SelectEqp,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("EQUIPMENT_TRANSFER"),
          url: "/eam/account_management/equipment_transfer",
        },
        { name: this.$t("ADD"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_eqp_transfer",
          tab: "设备移转",
        },
      ],
      dataAttr: {
        form: "form",
      },
      // 移转类型
      transferTypeList: [],
      // 申请部门
      treeData: [],
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      fieldNames: { label: "label", value: "code", children: "children" },
      // 申请部门级联用户
      searchParams: {
        deptId: "",
      },
      // 申请部门级联用户
      searchToParams: {
        deptId: "",
      },
      // 选中的申请用户
      selectedUser: [],
      // 选中的接收用户
      selectedToUser: [],
      // 目标位置
      currentOptions: [],
      currentOptionsLine: [
        {
          code: "LINE",
          label: "车间",
          children: [],
        },
      ],
      currentOptionsWh: [
        {
          code: "WAREHOUSE",
          label: "仓库",
          children: [],
        },
      ],
      activeKey: "a",
      activeKeyB: "b",
      confirmLoading: false,
      dataSource: [],
      form: {
        code: "", // 申请表单编码
        name: "", // 申请移转名称
        type: "", // 移转类型
        applyDeptId: "", // 申请部门
        applyUserId: "", // 申请人
        applyUserName: "", // 申请人
        toSiteCode: "", // 目标厂区
        locationFirstIdArr: [], // 当前位置
        locationFirstId: "",
        toDeptId: "", // 目标部门
        toUserId: "", // 接收人
        checkProcessId: "", // 审批流程
        remark: "",
      },
      formOld: {
        code: "", // 申请表单编码
        name: "", // 申请移转名称
        type: "", // 移转类型
        applyDeptId: "", // 申请部门
        applyUserId: "", // 申请人
        applyUserName: "", // 申请人
        toSiteCode: "", // 目标厂区
        locationFirstIdArr: [], // 当前位置
        locationFirstId: "",
        toDeptId: "", // 目标部门
        toUserId: "", // 接收人
        checkProcessId: "", // 审批流程
        remark: "",
      },
      eqpList: [],
      fieldExtendList: [], // 字段扩展列表
      drawerVisible: false,
      isEdit: false,
      editIndex: 0,
      actionButtons: ["delete"],
      assetsStatusList: [],
      defaultList: [
        {
          dataIndex: "eqpCode", // 设备编码
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EPMS_EQP_CODE"),
        },
        {
          dataIndex: "eqpName", // 设备名称
          title: () => this.$t("EQP_NAME"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "eqpTypeName", // 设备类型
          align: "left",
          sorter: false,
          ellipsis: true,
          width: 180,
          title: () => this.$t("EQP_TYPE"),
        },
        {
          dataIndex: "assetsCode", // 资产编码
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EPMS_ASSETS_CODE"),
        },
        {
          dataIndex: "assetsStatus", // 资产状态
          sorter: false,
          ellipsis: true,
          width: 180,
          title: () => this.$t("ASSETS_STATUS"),
          scopedSlots: { customRender: "assetsStatus" },
        },
        {
          dataIndex: "eqpModel", // 规格型号
          sorter: false,
          ellipsis: true,
          width: 180,
          title: () => this.$t("EQP_MODEL"),
        },
        {
          dataIndex: "ownerName", // 设备负责人
          sorter: false,
          ellipsis: true,
          title: () => this.$t("LEADER_NAME"),
        },
        {
          dataIndex: "location", // 位置
          sorter: false,
          ellipsis: true,
          width: 360,
          title: () => this.$t("CURRENT_LOCATION"),
        },
      ],
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      columnsList: [],
      sitePermission: [],
      yesNoList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapState({}),
    rules() {
      return {
        type: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        assetsStatusSetFlag: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        applyUserId: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        toSiteCode: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        toUserId: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkProcessId: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        locationFirstIdArr: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            validator: this.validLocation,
            trigger: "change",
          },
        ],
      };
    },
    columns() {
      return [...this.defaultList, ...this.columnsList];
    },
  },
  watch: {},
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-transfer/get-by-id/${id}`
        )
        .then((detailRes) => {
          /* eslint-enable */
          const { applyDeptId, toDeptId, eqpTransferItemBPOList } = {
            ...detailRes.data?.data,
          };
          this.searchParams.deptId = applyDeptId || "";
          this.searchToParams.deptId = toDeptId || "";
          this.form = { ...detailRes.data?.data };
          this.selectedUser = [
            { id: this.form.applyUserId, name: this.form.applyUserName },
          ];
          this.selectedToUser = [
            { id: this.form.toUserId, name: this.form.toUserName },
          ];
          const eqpListTrans = eqpTransferItemBPOList.map((list) => {
            // eslint-disable-next-line no-param-reassign
            delete list.id;
            return {
              ...list,
              id: list.eqpId,
            };
          });
          this.eqpList = [...eqpListTrans];
          this.form.locationFirstIdArr = [
            this.form.locationType,
            this.form.locationFirstId,
            this.form.locationSecondId,
            this.form.locationThirdId,
          ];
          this.$axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp/sitecode/location-tree?siteCode=${this.form.toSiteCode}`
            )
            .then((res) => {
              deleteLeafArray(res.data.data.lineTree, "children");
              deleteLeafArray(res.data.data.warehouseTree, "children");
              this.currentOptionsLine[0].children = res.data.data.lineTree;
              this.currentOptionsWh[0].children = res.data.data.warehouseTree;
              this.changeCurrentOptions(this.form.type, false);
            });
          delete this.form.eqpTransferItemBPOList;
          this.queryFieldExtend().then(() => {
            // this.$refs.fieldAuthRef.init();
          });
        });
    } else {
      this.queryFieldExtend().then(() => {
        // this.$refs.fieldAuthRef.init();
      });
    }
    // 初始化数据
    this.init();
  },
  methods: {
    // 校验location是否填写
    validLocation(rule, value, callback) {
      setTimeout(() => {
        if (value.length < 2) {
          callback(new Error(this.$t("PLACESELECT")));
        } else {
          callback();
        }
      }, 100);
    },
    // 获取选择申请用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      this.form.applyUserId = selectedRows[0]?.id;
      this.form.applyUserName = selectedRows[0]?.name;
      this.selectedUser = selectedRows;
      this.$refs.ruleForm.validateField("applyUserId");
    },
    // 获取选择接收用户组件返回数据
    getToReturnData(selectedKeys, selectedRows) {
      this.form.toUserId = selectedRows[0]?.id;
      this.selectedToUser = selectedRows;
      this.$refs.ruleForm.validateField("toUserId");
    },
    // 目标厂区更改
    siteChange() {
      this.form.locationFirstIdArr = [];
      // 获取目标厂区位置的三级树
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp/sitecode/location-tree?siteCode=${this.form.toSiteCode}`
        )
        .then((res) => {
          deleteLeafArray(res.data.data.lineTree, "children");
          deleteLeafArray(res.data.data.warehouseTree, "children");
          this.currentOptionsLine[0].children = res.data.data.lineTree;
          this.currentOptionsWh[0].children = res.data.data.warehouseTree;
          this.changeCurrentOptions(this.form.type, false);
        });
    },
    onSelectSearchChange(e, info) {
      this.form.checkProcessId = info.id;
    },
    formatData(data, status = "") {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 获取返回数据，设备清单
    getEqpReturnData(selectedKeys, selectedRows) {
      if (selectedRows && selectedRows.length > 0) {
        this.eqpList = this.eqpList.concat(selectedRows);
        this.checkItemList();
      }
    },
    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();
      });
    },
    // 移转类型更改currentOptions
    changeCurrentOptions(val, needClear = true) {
      if (needClear) {
        this.form.locationFirstIdArr = [];
      }
      if (["LINE_TO_LINE", "WARREHOUSE_TO_LINE"].includes(val)) {
        this.currentOptions = [...this.currentOptionsLine];
      } else if (
        ["LINE_TO_WAREHOUSE", "WARREHOUSE_TO_WARREHOUSE"].includes(val)
      ) {
        this.currentOptions = [...this.currentOptionsWh];
      } else {
        this.currentOptions = [
          ...this.currentOptionsLine,
          ...this.currentOptionsWh,
        ];
      }
    },
    // 监听选择申请部门组件返回数据
    handChangeDep(val) {
      this.searchParams.deptId = val;
      this.form.applyUserId = "";
      this.form.applyUserName = "";
      this.selectedUser = [];
    },
    // 监听选择接收部门组件返回数据
    handChangeToDep(val) {
      this.searchToParams.deptId = val;
      this.form.toUserId = [];
      this.selectedToUser = [];
    },
    handleDelete(row) {
      const index = this.eqpList.findIndex((item) => item.id === row.id);
      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.eqpList.splice(index, 1);
        },
      });
    },
    // 初始化数据
    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:EQP_TRANSFER_TYPE`
        ), // 移转类型
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`, {
          params,
        }), // 部门树结构
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ASSETS_STATUS`
        ), // 资产状态
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-site/list`),
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
      ]).then(([typeRes, treeRes, assetsStatusRes, siteRes, yesNoRes]) => {
        this.transferTypeList = typeRes.data?.data;
        this.treeData = treeRes.data.data;
        this.assetsStatusList = assetsStatusRes.data.data;
        this.sitePermission = siteRes.data.data;
        this.yesNoList = yesNoRes.data.data;
      });
    },
    // 监听选择设备清单
    handleselectEqp() {
      this.$refs.selectEqp.openDialog();
    },
    // 设备清单去重
    checkItemList() {
      this.eqpList = uniqBy(this.eqpList, "id"); // 去重
    },
    // 监听保存按钮点击事件
    handleSave(type) {
      if (!this.eqpList.length) {
        this.$message.error(this.$t("AT_LEAST_ONE_EQP"));
        return;
      }
      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 { code, name } = this.form;
          let eqpTransferItemFormParamList = [];
          if (this.eqpList.length > 0) {
            // eslint-disable-next-line array-callback-return
            eqpTransferItemFormParamList = this.eqpList.map((item) => {
              const { eqpCode, id } = item;
              const req = {
                eqpCode,
                eqpId: id,
              };
              return req;
            });
          }
          this.confirmLoading = true;
          const params = {
            ...this.form,
            eqpTransferItemFormParamList,
          };
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-transfer`, params)
            .then(() => {
              this.$message.success(this.$t("SAVE_SUCCESS"));
              this.confirmLoading = false;
              if (type === "saveAndApproval") {
                this.handleAudit(this.$route.query.id);
              } else {
                this.handleCancel();
              }
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听提交事件
    handleAudit(id) {
      const params = {
        ids: [id],
      };
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-transfer/commit-to-check`,
          params
        )
        .then(() => {
          setTimeout(() => {
            this.handleCancel();
          }, 500);
        });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/account_management/equipment_transfer",
        },
        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>
