<template>
  <div>
    <a-form>
      <a-tabs v-model="tabName" type="card">
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.equipment-add')"
            key="addStructure">
          <HotTable
              ref="addStructure"
              key="addStructure"
              v-if="tabName === 'addStructure'"
              :formData="structureData"
              :headers="headers"
              :columns="columns"
              :focusCol="focusCol"
              @formDataChange="structureDataChange"
          />
        </a-tab-pane>
      </a-tabs>
    </a-form>
    <div slot="footer" class="mt10 text-right">
      <a-button @click="closeModal">
        {{ $t('global-btn.cancel') }}
      </a-button>
      <a-button
          type="primary"
          class="ml10"
          @click="save()"
          :loading="saveLoading"
          v-preventReClick>
        {{ $t('global-btn.confirm') }}
      </a-button>
    </div>
  </div>
</template>
<script>

import HotTable from "@/components/HotTable";
import AddDFMEALibrary from "./components/AddDFMEALibrary";
import {checkHotTableLength} from "@/utils/validate";
import {config} from "@/views/structure/assets/topology"

export default {
  name: "AddStructure",
  components: {
    HotTable,
    AddDFMEALibrary
  },
  props: {
    struTypeCode: {
      default: '',
      type: String
    },
    checkedNode: {
      type: Object
    },
  },
  data() {
    return {
      structureData: [], // 添加结构
      DFMEALibraryData: [], // 添加DFMEA库
      tabName: "addStructure",
      columns: [
        {data: "name", type: "text"},
        {data: "code", type: "text"}
      ],
      headers: [this.$t('functional-analysis.add-modal.equipment'),
        this.$t('functional-analysis.add-modal.equipment-number')], focusCol: 0,
      saveLoading: false,
      selectType: 1
    };
  },
  methods: {
    /**
     * 接受子组件handsontable数据
     */
    structureDataChange(val) {
      this.structureData = val;
    },
    /**
     * 接受子组件DFMEA库数据
     */
    DFMEALibraryDataChange(val) {
      this.DFMEALibraryData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新左侧结构树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addStructure') { // 结构添加：保存
        _that.saveStructure();
      } else if (_that.tabName === 'addDFMEALibrary') { // DFMEA库选择：保存
        _that.saveMFMEALibrary();
      }
    },
    /**
     * 构建：结构数据
     */
    buildStructureData() {
      return this.structureData.map((item) => {
        return {name: item.name, code: item.code}
      }).filter((item) => {
        return item.name;
      });
    },
    /**
     * 校验：结构数据
     */
    validateStructureData(structureData) {
      if (structureData && structureData.length > 0) {
        let flag = true;
        structureData.some((item, idx) => {
          if (checkHotTableLength(item.name, 1000)) {
            this.$message.warning(this.$t('global-message.warn.structure-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.code, 100)) {
            this.$message.warning(this.$t('global-message.warn.part-number-length', [idx + 1]));
            flag = false
            return true;
          }
        });
        return flag;
      } else {
        this.$message.warning(this.$t('global-message.warn.please-enter-not-name-line'))
        return false;
      }
    },
    /**
     * 保存：结构
     */
    saveStructure() {
      let _that = this;
      // 构建数据
      let structureData = _that.buildStructureData();
      // 校验
      if (!_that.validateStructureData(structureData)) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveStructure({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        struTypeCode: '01',
        chartFlag: 0, // 0：隐藏 1：显示
        mfmeaStruInputModels: structureData,
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新左侧树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initLeftTree();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false; // 关闭：加载中...
      })
    },
    /**
     * 校验：DFAME库选择
     */
    validateDFMEALibraryData() {
      let _that = this;
      if (_that.DFMEALibraryData.length === 0) {
        _that.$message.warning(this.$t('global-message.warn.please-select-node'));
        return false;
      }
      return true;
    },
    /**
     * 保存：DFAME库选择
     */
    saveMFMEALibrary() {
      let _that = this;
      // 校验
      if (!_that.validateDFMEALibraryData()) return;
      // 构建数据
      let ids = _that.DFMEALibraryData.map((item) => {
        return item.id;
      });
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveMFMEALibrarySelect({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        selectType: _that.selectType,
        struIds: ids.toString(),
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新左侧树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initLeftTree();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false; // 关闭：加载中...
      })
    }
  }
};
</script>
<style lang="less">

</style>
