<template>
  <div>
    <a-form>
      <a-tabs v-model="tabName" type="card">
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.multilevel-equipment-add')"
            key="addMultistageStructure">
          <HotTable
              ref="addMultistageStructure"
              key="addMultistageStructure"
              v-if="tabName === 'addMultistageStructure'"
              :formData="multistageStructureData"
              :headers="headers"
              :columns="columns"
              :focusCol="focusCol"
              @formDataChange="formDataChange"
          />
        </a-tab-pane>
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.multilevel-element-add')"
            key="addMultilevelElement">
          <AddMultilevelElement
              ref="addMultilevelElement"
              v-if="tabName === 'addMultilevelElement'"
              @dataChange="multilevelElementDataChange"
          />
        </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 AddMultilevelElement from "./components/AddMultilevelElement";
import {checkHotTableLength, validNumberRange} from "@/utils/validate";

export default {
  name: "AddMultistageStructure",
  components: {
    HotTable,
    AddMultilevelElement
  },
  props: {
    checkedNode: {
      type: Object
    }
  },
  data() {
    return {
      multistageStructureData: [], // 添加多级结构
      multilevelElementData: [], // 添加多级元素
      tabName: "addMultistageStructure",
      columns: [
        {data: "stru1", type: "text"},
        {data: "stru2", type: "text"},
        {data: "stru3", type: "text"},
        {data: "stru4", type: "text"},
        {data: "stru5", type: "text"},
      ],
      headers: [
        this.$t('functional-analysis.add-modal.lower-1-level-equipment'),
        this.$t('functional-analysis.add-modal.lower-2-level-equipment'),
        this.$t('functional-analysis.add-modal.lower-3-level-equipment'),
        this.$t('functional-analysis.add-modal.lower-4-level-equipment'),
        this.$t('functional-analysis.add-modal.lower-5-level-equipment')
      ],
      focusCol: 0,
      saveLoading: false,
    };
  },
  methods: {
    /**
     * 接受子组件handsontable数据
     */
    formDataChange(val) {
      this.multistageStructureData = val;
    },
    /**
     * 接受子组件多级元素数据
     */
    multilevelElementDataChange(val) {
      this.multilevelElementData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新左侧结构树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 刷新右侧结构树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addMultistageStructure') { // 保存：多级结构
        _that.saveMultistageStructure();
      } else if (_that.tabName === 'addMultilevelElement') { // 保存：多级元素添加
        _that.saveMultilevelElement();
      }
    },
    /**
     * 构建：多级结构数据
     */
    buildMultistageStructureData() {
      return this.multistageStructureData.map((item) => {
        return {
          stru1: item.stru1,
          stru2: item.stru2,
          stru3: item.stru3,
          stru4: item.stru4,
          stru5: item.stru5,
        }
      }).filter((item) => {
        return item.stru1 || item.stru2 || item.stru3 || item.stru4 || item.stru5;
      });
    },
    /**
     * 校验：多级结构数据
     */
    validateMultistageStructureData(structureData) {
      if (structureData && structureData.length > 0) {
        let flag = true;
        structureData.some((item, idx) => {
          if (checkHotTableLength(item.stru1, 1000)) {
            this.$message.warning(this.$t('global-message.warn.column1-structure-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.stru2, 1000)) {
            this.$message.warning(this.$t('global-message.warn.column2-structure-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.stru3, 1000)) {
            this.$message.warning(this.$t('global-message.warn.column3-structure-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.stru4, 1000)) {
            this.$message.warning(this.$t('global-message.warn.column4-structure-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.stru5, 1000)) {
            this.$message.warning(this.$t('global-message.warn.column5-structure-name-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;
      }
    },
    /**
     * 保存：多级结构
     */
    saveMultistageStructure() {
      let _that = this;
      // 构建数据
      let structureData = _that.buildMultistageStructureData();
      // 校验
      if (!_that.validateMultistageStructureData(structureData)) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveMultistageStructure({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        mfmeaStruBatchInputModels: 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; // 关闭：加载中...
      })
    },

    /**
     * 构建：多级元素
     */
    buildMultilevelElementData() {
      return this.multilevelElementData.map((item) => {
        return {
          funType: item.funType,
          fun: item.fun,
          require: item.require,
          failure: item.failure,
          conPre: item.conPre,
          occurrence: item.occurrence,
          conDet: item.conDet,
          detection: item.detection,
        }
      }).filter((item) => {
        return item.funType || item.fun || item.require || item.failure
            || item.conPre || item.occurrence || item.conDet || item.detection;
      });
    },
    /**
     * 校验：多级元素
     */
    validateMultilevelElementData(elementData) {
      if (elementData && elementData.length > 0) {
        let flag = true;
        elementData.some((item, idx) => {
          if (item.funType && !validNumberRange(item.funType, 1, 2)) {
            this.$message.warning(this.$t('global-message.warn.function-type-name-length', [idx + 1, 1, 2]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.fun, 1000)) {
            this.$message.warning(this.$t('global-message.warn.function-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.require, 1000)) {
            this.$message.warning(this.$t('global-message.warn.require-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.failure, 1000)) {
            this.$message.warning(this.$t('global-message.warn.failure-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.conPre, 1000)) {
            this.$message.warning(this.$t('global-message.warn.control-prevention-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (item.occurrence && !validNumberRange(item.occurrence, 1, 10)) {
            this.$message.warning(this.$t('global-message.warn.o-name-length', [idx + 1, 1, 10]));
            flag = false
            return true;
          }
          if (checkHotTableLength(item.conDet, 1000)) {
            this.$message.warning(this.$t('global-message.warn.control-detection-name-length', [idx + 1]));
            flag = false
            return true;
          }
          if (item.detection && !validNumberRange(item.detection, 1, 10)) {
            this.$message.warning(this.$t('global-message.warn.d-name-length', [idx + 1, 1, 10]));
            flag = false
            return true;
          }
        });
        return flag;
      } else {
        this.$message.warning(this.$t('global-message.warn.please-enter-not-name-line'))
        return false;
      }
    },
    /**
     * 保存：多级元素
     */
    saveMultilevelElement() {
      let _that = this;
      // 构建数据
      let elementData = _that.buildMultilevelElementData();
      // 校验
      if (!_that.validateMultilevelElementData(elementData)) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveMultilevelElement({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        mfmeaEleBatchImputModel: elementData,
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新右侧树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initRightTree();
        } 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>
