<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"
                    option-label="checkProcessName"
                    :default-selected-keys="form.checkProcessId"
                    :default-selected-names="form.checkProcessName"
                    :search-params="searchParams"
                    @change="onSelectSearchChange"
                  >
                  </SelectSearch>
                </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('MOLD_LIST')}`">
            <MomTable
              ref="MomTable"
              row-key="itemName"
              :action-buttons="actionButtons"
              :columns="columns"
              :data-source="moldList"
              @delete="handleDelete"
            >
              <div slot="toolbar" class="button-top-table">
                <a-button @click="handleSelectMold()">{{
                  `${$t("SELECT")}${$t("MOLD_LIST")}`
                }}</a-button>
              </div>
            </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
        :loading="confirmLoading"
        type="primary"
        @click="handleSave('save')"
      >
        <i class="iconfont icon-baocun" />
        {{ $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
        :loading="confirmLoading"
        type="primary"
        @click="handleSave('saveAndAdd')"
      >
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE_AND_ADD_NEXT") }}
      </a-button>
      <a-button @click="handleCancel()">
        <i class="iconfont icon-quxiao" />
        {{ $t("CANCEL") }}
      </a-button>
    </div>
    <!-- 选择模具组件 -->
    <select-mold
      ref="selectMold"
      show-key="id"
      :show-slot="false"
      :default-selected-rows="moldList"
      @confirm="getReturnDataMold"
    />
  </div>
</template>

<script lang="ts">
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { uniqBy } from "lodash";
import { mapGetters, mapState } from "vuex";
import { deleteLeafArray } from "@mega-apps/utils";
import ApiConstant from "@/api/ApiConstant";
import breadcrumb from "@/components/breadcrumb/index.vue";
import FieldExtendMixin from "@/mixins/fieldExtend";
import SelectMold from "@/components/epms/SelectMold/index.vue";

export default {
  components: { breadcrumb, SelectMold },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("MOLD_TYPE"),
          url: "/eam/mold_management/mold_type",
        },
        { name: this.$t("EQUIPMENT_TYPE"), url: "" },
      ],
      activeKeyA: "a",
      activeKeyB: "b",
      confirmLoading: false,
      actionButtons: ["delete"],
      form: {
        id: null,
        code: "",
        name: "",
        locationFirstIdArr: [], // 报废仓
        checkProcessId: "", // 工作流
        remark: "",
      },
      // 申请部门
      treeData: [],
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      selectedUser: [{ name: "" }],
      typeList: [],
      columns: [
        {
          dataIndex: "moldCode", // 编码
          title: () => this.$t("MOLD_CODE"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "moldName", // 名称
          title: () => `${this.$t("MOLD")}${this.$t("NAME")}` as string,
          ellipsis: true,
          scopedSlots: { customRender: "moldName" },
        },
        {
          dataIndex: "moldTypeName", // 模具类型名称
          title: () => `${this.$t("MOLD_TYPE")}${this.$t("NAME")}`,
          ellipsis: true,
        },
        {
          dataIndex: "moldHoleNum", // 模具穴数
          title: () => this.$t("NUMBER_OF_ACUPOINTS"),
          ellipsis: true,
        },
        {
          dataIndex: "manageType",
          align: "left",
          width: 150,
          ellipsis: true,
          title: () => this.$t("MOLD_CONTROL_MODE"), // 管控方式
          scopedSlots: { customRender: "manageType" },
        },
        {
          dataIndex: "initValue", // 当次初始时间/次数
          title: () => this.$t("INITIAL_VALUE_OF_CURRENT_USE"),
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "initValue" },
        },
        {
          dataIndex: "totalInitValue", // 历次累积时间/次数
          title: () => this.$t("INITIAL_VALUE_OF_PREVIOUS_USE"),
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "totalInitValue" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ],
      moldList: [], // 模具列表
      selectedList: [],
      searchParams: {
        deptId: "",
        checkProcessTypeList: "MOLD_SCRAP_CHECK",
      },
      fieldNames: { label: "label", value: "code", children: "children" },
      currentOptions: [
        // {
        //   code: "LINE",
        //   label: "车间",
        //   children: [],
        // },
        // {
        //   code: "WAREHOUSE",
        //   label: "仓库",
        //   children: [],
        // },
      ],
      tableNameList: [
        {
          key: "epm_mold_scrap",
          tab: "模具报废",
        },
      ],
      dataAttr: {
        form: "form",
      },
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapGetters(["modules"]),
    rules(): object {
      return {
        locationFirstIdArr: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkProcessId: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
  },
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/mam/mold-scrap/get-by-id/${id}`
        )
        .then((res) => {
          this.form = { ...res?.data?.data };
          const {
            detailList = [],
            whId = "",
            whCateId = "",
            locationId = "",
          } = { ...res?.data?.data };
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          this.form.locationFirstIdArr = [whId, whCateId, locationId];
          this.moldList = [...detailList] as any;
          this.selectedList = detailList.map(
            (item: { id: any; moldId: any }) => {
              return {
                ...item,
                id: item.moldId,
              };
            }
          );
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          this.queryFieldExtend().then(() => {});
        });
    } else {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      this.queryFieldExtend().then(() => {});
    }
    // 初始化数据
    this.init();
  },
  methods: {
    // 获取返回数据，选择模具
    getReturnDataMold(selectedKeys: any, selectedRows: any) {
      this.moldList = selectedRows;
    },
    // 监听选择报废模具
    handleSelectMold() {
      const refs: any = this.$refs;
      refs.selectMold.openDialog();
    },
    // 监听签核流程返回事件
    onSelectSearchChange(e: string) {
      this.form.checkProcessId = e;
    },
    // 初始化数据，获取数据字典数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:MOLD_MANAGE_TYPE`
        ), // 模具管控方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp/location-tree`
        ), // 获取当前位置的三级树
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`), // 部门树结构
      ]).then(([typeRes, treeRes, orgTreeRes]) => {
        this.typeList = typeRes.data.data;
        deleteLeafArray(treeRes.data.data.lineTree, "children");
        deleteLeafArray(treeRes.data.data.warehouseTree, "children");
        // this.currentOptions[0].children = treeRes.data.data.lineTree;
        this.currentOptions = treeRes.data.data.warehouseTree;
        this.treeData = orgTreeRes.data.data;
      });
    },
    // 监听保存点击事件
    handleSave(type: string) {
      const refs: any = this.$refs;
      refs.ruleForm.validate((valid: boolean) => {
        if (valid) {
          this.confirmLoading = true;
          const moldIdList = this.moldList.map((item: any) => {
            return item.id;
          });
          const [whId, whCateId, locationId] = this.form.locationFirstIdArr;
          const params = {
            ...this.form,
            moldIdList,
            whId,
            whCateId,
            locationId,
          };
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          const req = this.fieldExReqDataFn(params);
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold-scrap`, req)
            .then(() => {
              this.$message.success(this.$t("EDIT_SUCCESS") as string);
              this.confirmLoading = false;
              if (type === "saveAndApproval") {
                this.handleAudit(this.$route.query.id as string);
              } else if (type === "saveAndAdd") {
                // this.handleCancel();
              } else {
                this.handleCancel();
              }
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听提交事件
    handleAudit(id: string) {
      const params = {
        ids: [id],
      };
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/epm/mam/mold-scrap/commit-to-check`,
          params
        )
        .then(() => {
          setTimeout(() => {
            this.handleCancel();
          }, 500);
        });
    },
    // 监听删除点击事件
    handleDelete(row: any) {
      const index = this.moldList.findIndex((item: any) => item.id === row.id);
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE") as string,
        cancelText: this.$t("CANCEL") as string,
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.moldList.splice(index, 1);
        },
      });
    },
    // 监听取消点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/mold_management/mold_scrap",
        },
        vm: this,
      });
    },
  },
};
</script>
