<template>
  <div class="page-wrapper app">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <a-form-model
        slot="main"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <!-- 基础信息 -->
        <a-collapse
          v-model="activeKeyA"
          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('CODE')}`" prop="code">
                  <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">
                  <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('SCRAP_WAREHOUSE')"
                  prop="locationFirstIdArr"
                >
                  <a-cascader
                    v-model="form.locationFirstIdArr"
                    :placeholder="$t('PLACESELECT')"
                    :options="currentOptions"
                    :field-names="fieldNames"
                    change-on-select
                  />
                </a-form-model-item>
              </a-col>
              <!-- 报废仓 结束 -->
              <!-- 审核流程 开始 -->
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('CHECK_PROCESS')"
                  prop="checkProcessId"
                >
                  <SelectSearch
                    :show-multiple="false"
                    query-list-key="checkProcessName"
                    request-api="/api/epm/ebs/epm-check-process/search?checkProcessTypeList=EQP_SCRAP_CHECK"
                    option-label="checkProcessName"
                    :default-selected-keys="form.checkProcessId"
                    :default-selected-names="form.checkProcessName"
                    :search-params="searchParams"
                    @change="onSelectSearchChange"
                  />
                </a-form-model-item>
              </a-col>
              <!-- 审核流程 结束 -->
            </a-row>
            <a-row v-if="form.hasOwnProperty('remark')" :gutter="21">
              <a-col :span="18">
                <a-form-model-item
                  :label="$t('REMARK')"
                  :label-col="{ span: 3 }"
                  :wrapper-col="{ span: 19 }"
                  prop="remark"
                >
                  <a-textarea
                    v-model="form.remark"
                    :rows="2"
                    :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"
              @delete="handleDelete"
            >
              <div slot="toolbar" class="button-top-table">
                <a-button @click="handleselectEqp()">{{
                  `${$t("SELECT")}${$t("EQUIPMENT_LIST")}`
                }}</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>
          <!-- 扩展字段 -->
          {{ fieldExRenderFn($createElement, { layout: "grid", itemSpan: 8 }) }}
          <slot name="RenderFieldExtendDom"></slot>
        </a-collapse>
      </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 { fieldExReqDataFn } from "@/utils/fieldExtend";
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_scrap"),
          url: "/eam/account_management/equipment_scrap",
        },
        { name: this.$t("ADD"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_eqp_scrap",
          tab: "设备报废",
        },
      ],
      dataAttr: {
        form: "form",
      },
      // 申请部门
      treeData: [],
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      fieldNames: { label: "label", value: "code", children: "children" },
      // 申请部门级联用户
      searchParams: {
        deptId: "",
      },
      // 申请部门级联用户
      searchToParams: {
        deptId: "",
      },
      // 选中的接收用户
      selectedToUser: [],
      // 目标位置
      currentOptions: [],
      activeKeyA: "a",
      activeKeyB: "b",
      confirmLoading: false,
      dataSource: [],
      form: {
        id: null,
        code: "",
        name: "",
        locationFirstIdArr: [], // 报废仓
        checkProcessId: "", // 工作流
        remark: "",
      },
      formOld: {
        id: null,
        code: "",
        name: "",
        locationFirstIdArr: [], // 报废仓
        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: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapState({
      user: (state) => state.auth?.user?.user || {},
      activatedSite: (state) => state.activatedSite,
    }),
    rules() {
      return {
        locationFirstIdArr: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkProcessId: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            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-scrap/get-by-id/${id}`)
        .then((res) => {
          this.form = { ...res?.data?.data };
          const { eqpScrapItemBPOList, whId, whCateId, locationId } = {
            ...res?.data?.data,
          };
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          this.form.locationFirstIdArr = [whId, whCateId, locationId];
          const eqpListTrans = eqpScrapItemBPOList.map((list) => {
            // eslint-disable-next-line no-param-reassign
            delete list.id;
            return {
              ...list,
              id: list.eqpId,
            };
          });
          this.eqpList = [...eqpListTrans];
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          delete this.form.eqpScrapItemBPOList;
          this.queryFieldExtend().then(() => {});
        });
    } 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);
    },
    // 获取选择接收用户组件返回数据
    getToReturnData(selectedKeys, selectedRows) {
      this.form.toUserId = selectedRows[0]?.id;
      this.selectedToUser = selectedRows;
      this.$refs.ruleForm.validateField("toUserId");
    },
    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();
      });
    },
    // 监听选择接收部门组件返回数据
    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 = {
        moduleCode: this.$store.state.activatedModule,
      };
      return Promise.all([
        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/epm/eam/eqp/location-tree`
        ), // 获取当前位置的三级树
      ]).then(([treeRes, assetsStatusRes, locationTree]) => {
        this.treeData = treeRes.data.data;
        this.assetsStatusList = assetsStatusRes.data.data;
        deleteLeafArray(locationTree.data.data.lineTree, "children");
        deleteLeafArray(locationTree.data.data.warehouseTree, "children");
        this.currentOptions = locationTree.data.data.warehouseTree;
      });
    },
    // 监听选择设备清单
    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 [whId, whCateId, locationId] = this.form.locationFirstIdArr;
          // const { code, name } = this.form;
          let eqpScrapItemFormParamList = [];
          if (this.eqpList.length > 0) {
            // eslint-disable-next-line array-callback-return
            eqpScrapItemFormParamList = this.eqpList.map((item) => {
              const { eqpCode, id } = item;
              const req = {
                eqpCode,
                eqpId: id,
              };
              return req;
            });
          }
          this.confirmLoading = true;
          const params = {
            ...this.form,
            whId,
            whCateId,
            locationId,
            eqpScrapItemFormParamList,
          };
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-scrap`, 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-scrap/commit-to-check`,
          params
        )
        .then(() => {
          setTimeout(() => {
            this.handleCancel();
          }, 500);
        });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/account_management/equipment_scrap",
        },
        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>
