<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"
                    disabled
                    :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('APPLY_DEPT')" prop="applyDeptId">
                  <a-tree-select
                    v-model="form.applyDeptId"
                    disabled
                    :replace-fields="treeProps"
                    tree-check-strictly
                    :tree-data="treeData"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <!-- 部门 结束 -->
              <!-- 申请人 开始 -->
              <a-col :span="8">
                <a-form-model-item :label="$t('APPLY_USER')" prop="applyUserId">
                  <a-input
                    v-model="form.applyUserName"
                    disabled
                    :placeholder="$t('PLACEENTER')"
                  />
                </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"
                    disabled
                    :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"
                    disabled
                    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"
                  >
                  </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"
                    disabled
                    :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('SPARE_PARTS_LIST')}`">
            <MomTable
              ref="MomTable"
              row-key="itemName"
              :action-buttons="actionButtons"
              :columns="columns"
              :data-source="sparePartsList"
            >
              <template slot="imgUrl" slot-scope="text, record">
                <img
                  class="eqp_picture"
                  :src="record.imgUrl || defaultImg"
                  alt=""
                />
              </template>
              <div slot="sn" slot-scope="text, record">
                <div class="flex flex-col justify-center">
                  <vue-barcode
                    v-if="record.sn"
                    :value="record.sn"
                    :display-value="false"
                    :width="1.5"
                    :height="24"
                    tag="svg"
                  >
                  </vue-barcode>
                  <div class="flex justify-center" style="letter-spacing: 3px">
                    {{ record.sn }}
                  </div>
                </div>
              </div>
              <div slot="matUnit" slot-scope="text, record">
                {{ getAttrValue(unitList, record.matUnit) }}
              </div>
            </MomTable>
          </a-collapse-panel>
          <!-- 扩展字段 -->
          {{
            fieldExRenderFn($createElement, {
              layout: "grid",
              itemSpan: 8,
              disabled: true,
            })
          }}
          <slot name="RenderFieldExtendDom"></slot>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button @click="handleCancel()">
        <i class="iconfont icon-quxiao" />
        {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

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

export default {
  components: {
    breadcrumb,
    VueBarcode,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      // eslint-disable-next-line
      defaultImg: require("@/assets/img/attachmentImg.png"),
      breadcrumbData: [
        {
          name: this.$t("SPARE_PARTS_SCRAP"),
          url: "/eam/spare_parts_mgmt/scrap",
        },
        { name: this.$t("SPARE_PARTS_SCRAP"), url: "" },
      ],
      activeKeyA: "a",
      activeKeyB: "b",
      confirmLoading: false,
      actionButtons: [],
      form: {
        id: null,
        code: "",
        name: "",
        applyUserId: "",
        applyUserName: "",
        locationFirstIdArr: [], // 报废仓
        checkProcessId: "", // 工作流
        remark: "",
      },
      // 申请部门
      treeData: [],
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      selectedUser: [{ name: "" }],
      typeList: [],
      columns: [
        {
          dataIndex: "imgUrl",
          width: 100,
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "imgUrl" },
          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: "batchCode", // 批次
          title: () => this.$t("BATCH_NO"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "num", // 全部数量
          sorter: false,
          ellipsis: true,
          width: 150,
          title: () => `${this.$t("ALL")}${this.$t("QUANTITY")}`,
        },
        {
          dataIndex: "usableNum", // 可退数量
          sorter: false,
          ellipsis: true,
          width: 150,
          title: () => this.$t("CAN_SCRAP_QUANTITY"),
        },
        {
          dataIndex: "scrapNum", // 申请数量
          width: 120,
          sorter: false,
          title: () => this.$t("SCRAP_QUANTITY"),
        },
        {
          dataIndex: "sn", // 条形码
          title: () => this.$t("BAR_CODE"),
          ellipsis: true,
          sorter: false,
          width: 320,
          minWidth: 320,
          scopedSlots: { customRender: "sn" },
        },
        {
          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: "matUnit", // 单位
          title: () => this.$t("TIME_UNIT"),
          width: 80,
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "matUnit" },
        },
        {
          dataIndex: "recentUnbindTime", // 最近下机时间
          width: 180,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("LATEST_DISEMBARKATION_TIME"),
        },
      ],
      sparePartsList: [], // 模具列表
      searchParams: {
        deptId: "",
        checkProcessTypeList: "PART_SCRAP_CHECK",
      },
      searchParamsParts: {
        partScrapCode: "",
        ngFlag: "Y",
      },
      fieldNames: { label: "label", value: "code", children: "children" },
      currentOptions: [
        // {
        //   code: "LINE",
        //   label: "车间",
        //   children: [],
        // },
        // {
        //   code: "WAREHOUSE",
        //   label: "仓库",
        //   children: [],
        // },
      ],
      tableNameList: [
        {
          key: "epm_part_scrap",
          tab: "备件报废",
        },
      ],
      dataAttr: {
        form: "form",
      },
      unitList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapGetters(["modules"]),
    rules(): object {
      return {
        applyUserId: [
          {
            required: true,
            message: () => this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        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/part/part-scrap/get-by-id/${id}`
        )
        .then((res) => {
          this.form = { ...res?.data?.data };
          this.selectedUser = [
            { name: res?.data?.data?.applyUserName as string },
          ];
          const {
            detailList = [],
            whId = "",
            whCateId = "",
            locationId = "",
            code = "",
          } = { ...res?.data?.data };
          this.searchParamsParts.partScrapCode = code;
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          this.form.locationFirstIdArr = [whId, whCateId, locationId];
          this.sparePartsList = [...detailList] as any;
          // 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: {
    // 初始化数据，获取数据字典数据
    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`), // 部门树结构
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:CORE:MATERIAL_UNIT`
        ), // 单位数据字典
      ]).then(([typeRes, treeRes, orgTreeRes, unitRes]) => {
        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;
        this.unitList = unitRes.data?.data;
      });
    },
    // 监听取消点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/spare_parts_mgmt/scrap",
        },
        vm: this,
      });
    },
  },
};
</script>
<style scoped lang="less">
.eqp_picture {
  width: 50px;
  height: 50px;
}
</style>
