<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: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <!-- 基础信息 -->
        <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">
              <a-col v-if="form.hasOwnProperty('moldCode')" :span="8">
                <a-form-model-item
                  :label="`${$t('MOLD')}${$t('CODE')}`"
                  prop="moldCode"
                >
                  <a-input
                    v-model="form.moldCode"
                    :placeholder="`${$t('SYSTEM_DEFAULT_CODE')}MOLD+${$t(
                      'NUMBER'
                    )}`"
                    @change="form.moldCode = form.moldCode.slice(0, 50).trim()"
                  /> </a-form-model-item
              ></a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="`${$t('MOLD')}${$t('NAME')}`"
                  prop="moldName"
                >
                  <a-input
                    v-model="form.moldName"
                    :placeholder="$t('PLACEENTER')"
                    @change="form.moldName = form.moldName.slice(0, 50).trim()"
                  /> </a-form-model-item
              ></a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('MOLD_TYPE')" prop="moldTypeId">
                  <SelectSearch
                    :show-multiple="false"
                    request-api="/api/epm/mam/mold-type/search"
                    option-label="moldTypeName"
                    query-list-key="moldTypeName"
                    :default-selected-keys="form.moldTypeId"
                    :default-selected-names="form.moldTypeName"
                    @change="onSelectSearchChange"
                  >
                  </SelectSearch>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('NUMBER_OF_ACUPOINTS')"
                  prop="moldHoleNum"
                >
                  <a-input-number
                    v-model="form.moldHoleNum"
                    style="width: 100%"
                    :precision="0"
                    :max="999999"
                    :min="1"
                    :placeholder="$t('PLACEENTER')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('owner')" :span="8">
                <a-form-model-item :label="$t('LEADER_NAME')" prop="owner">
                  <template>
                    <div style="position: relative">
                      <select-user
                        ref="selectUser"
                        v-model="form.owner"
                        show-key="name"
                        :multiple="false"
                        :default-selected-rows="selectedUser"
                        @confirm="getReturnData"
                      />
                    </div>
                  </template>
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('imgUrl')" :span="8">
                <a-form-model-item
                  :label="`${$t('MOLD')}${$t('CORE_PICTURE')}`"
                  prop="imgUrl"
                >
                  <SingleUpload v-model="form.imgUrl" /> </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('ATTRIBUTE')}`">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MOLD_CONTROL_MODE')"
                  prop="manageType"
                >
                  <a-radio-group v-model="form.manageType">
                    <a-radio
                      v-for="item in typeList"
                      :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('INITIAL_VALUE_OF_CURRENT_USE')"
                  prop="initValue"
                >
                  <div class="flex" style="width: 100%">
                    <a-input-number
                      v-model="form.initValue"
                      class="relative"
                      style="width: 100%"
                      :precision="0"
                      :max="999999"
                      :min="0"
                      :placeholder="$t('PLACEENTER')"
                    />
                    <span
                      v-if="form.manageType === 'TIME'"
                      style="min-width: 20px; margin-left: 10px"
                      >min</span
                    >
                    <span v-else style="min-width: 20px; margin-left: 10px">{{
                      $t("FREQUENCY")
                    }}</span>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('INITIAL_VALUE_OF_PREVIOUS_USE')"
                  prop="totalInitValue"
                >
                  <div class="flex" style="width: 100%">
                    <a-input-number
                      v-model="form.totalInitValue"
                      class="relative"
                      style="width: 100%"
                      :precision="0"
                      :max="999999"
                      :min="0"
                      :placeholder="$t('PLACEENTER')"
                    />
                    <span
                      v-if="form.manageType === 'TIME'"
                      style="min-width: 20px; margin-left: 10px"
                      >min</span
                    >
                    <span v-else style="min-width: 20px; margin-left: 10px">{{
                      $t("FREQUENCY")
                    }}</span>
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
          </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('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>
  </div>
</template>

<script lang="ts">
import { mapGetters, mapState } from "vuex";
import ApiConstant from "@/api/ApiConstant";
import breadcrumb from "@/components/breadcrumb/index.vue";
import FieldExtendMixin from "@/mixins/fieldExtend";
import SingleUpload from "@/components/uploadPicture/singleUpload.vue";
import SelectUser from "@/components/epms/SelectUser/index.vue";

export default {
  components: { breadcrumb, SingleUpload, SelectUser },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("MOLD_ACCOUNT"),
          url: "/eam/mold_management/mold_account",
        },
        { name: this.$t("EQUIPMENT_TYPE"), url: "" },
      ],
      activeKeyA: "a",
      activeKeyB: "b",
      confirmLoading: false,
      form: {
        id: null,
        moldCode: "",
        moldName: "",
        imgUrl: "",
        owner: "",
        manageType: "TIME",
        moldTypeId: "",
        moldHoleNum: 1,
        initValue: null,
        totalInitValue: null,
      },
      selectedUser: [{ name: "" }],
      typeList: [], // 类型列表
      tableNameList: [
        {
          key: "epm_mold",
          tab: "模具台账",
        },
      ],
      dataAttr: {
        form: "form",
      },
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapGetters(["modules"]),
    rules(): object {
      return {
        moldName: [
          {
            required: true,
            message: `${this.$t("PLACEENTER")}`,
            trigger: "blur",
          },
        ],
        moldTypeId: [
          {
            required: true,
            message: `${this.$t("PLACESELECT")}`,
            trigger: "change",
          },
        ],
        moldHoleNum: [
          {
            required: true,
            message: `${this.$t("PLACEENTER")}`,
            trigger: "change",
          },
        ],
        manageType: [
          {
            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/get-by-id/${id}`)
        .then((res) => {
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          this.form = { ...res.data?.data };
          this.selectedUser = [{ name: res?.data?.data?.ownerName as string }];
          this.form.id = null;
          this.form.moldCode = "";
          // 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: {
    // 获取模具类型选择组件返回数据
    onSelectSearchChange(moldTypeId: string, info: any) {
      const {
        manageType,
        imgUrl,
        owner,
        ownerName,
        initValue,
        totalInitValue,
      } = info;
      this.form.moldTypeId = moldTypeId;
      this.form.manageType = manageType;
      this.form.imgUrl = imgUrl;
      this.form.owner = owner;
      this.form.initValue = initValue;
      this.form.totalInitValue = totalInitValue;
      this.selectedUser = [{ name: ownerName as string }];
    },
    // 初始化数据，获取数据字典数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:MOLD_MANAGE_TYPE`
        ), // 模具管控方式
      ]).then(([typeRes, detailBatchRes]) => {
        this.typeList = typeRes.data.data;
      });
    },
    // 获取选择用户组件返回数据
    getReturnData(
      selectedKeys: [],
      selectedRows: [{ name: string; userName: string }]
    ) {
      this.form.owner = selectedRows[0]?.userName;
      this.selectedUser = selectedRows;
    },
    // 监听保存点击事件
    handleSave(type: string) {
      const refs: any = this.$refs;
      refs.ruleForm.validate((valid: boolean) => {
        if (valid) {
          this.confirmLoading = true;
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold`, this.form)
            .then(() => {
              this.$message.success(this.$t("ADD_SUCCESS") as string);
              this.confirmLoading = false;
              if (type === "saveAndAdd") {
                // this.resetForm();
              } else {
                this.handleCancel();
              }
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        moldCode: "",
        moldName: "",
        imgUrl: "",
        owner: "",
        manageType: "TIME",
        moldTypeId: "",
        moldHoleNum: 1,
        initValue: null,
        totalInitValue: null,
      };
      this.selectedUser = [{ name: "" }];
    },
    // 监听取消点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/mold_management/mold_account",
        },
        vm: this,
      });
    },
  },
};
</script>
