<template>
  <div>
    <a-form>
      <a-tabs v-model="tabName" type="card">
        <a-tab-pane
            :tab="$t('structural-analysis.add-modal.interface-add')"
            key="addInterface">
          <HotTable
              ref="addInterface"
              key="addInterface"
              v-if="tabName === 'addInterface'"
              :formData="interfaceData"
              :headers="headers"
              :columns="columns"
              :focusCol="focusCol"
              @formDataChange="interfaceDataChange"
          />
        </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 {checkHotTableLength} from "@/utils/validate";
import {getNextX6NodePositions, getX6Node} from "@/views/structure/assets/topology";

export default {
  name: "AddInterface",
  components: {
    HotTable,
  },
  props: {
    checkedNode: {
      default: {},
      type: Object
    },
  },
  data() {
    return {
      interfaceData: [], // 添加接口
      DFMEALibraryData: [], // 添加DFMEA库
      tabName: "addInterface",
      columns: [
        {data: "name", type: "text"},
        {data: "code", type: "text"}
      ],
      headers: [
        this.$t('structural-analysis.add-modal.interface'),
        this.$t('structural-analysis.add-modal.equipment-number')
      ],
      focusCol: 0,
      saveLoading: false,
      selectType: 1
    };
  },
  methods: {
    /**
     * 接受子组件handsontable数据
     */
    interfaceDataChange(val) {
      this.interfaceData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新左侧接口树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 刷新右侧X6
     */
    initRightX6() {
      this.$emit("initRightX6");
    },
    /**
     * 添加X6节点
     */
    addRightX6Node(node) {
      this.$emit("addRightX6Node", node);
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addInterface') { // 接口添加：保存
        let interfaceData = _that.buildInterfaceData();
        _that.saveInterface(interfaceData);
      }
    },
    /**
     * 构建：接口数据
     */
    buildInterfaceData() {
      let interfaceData =  this.interfaceData.map((item) => {
        return {
          name: item.name,
          code: item.code,
        }
      }).filter((item) => {
        return item.name;
      });
      // 处理x6信息
      if (this.checkedNode?.x6Node) {
        let pid = this.checkedNode.id;
        let zIndex = this.checkedNode?.x6Node?.zIndex;
        let clickPositions = {
          x: this.checkedNode?.x6Node?.x,
          y: this.checkedNode?.x6Node?.y,
        };
        let positions = getNextX6NodePositions(interfaceData.length, clickPositions);
        for (let i = 0; i < interfaceData.length; i++) {
          let item = interfaceData[i];
          let x = positions[i].x;
          let y = positions[i].y;
          item['options'] = JSON.stringify(getX6Node('', pid, x, y, item.name, '99', zIndex));
        }
      }
      return interfaceData;
    },
    buildPartsData() {
      return this.selectedData.map((item) => {
        return {name: item.ffcDescriptionCn, code: item.ffcCode}
      }).filter((item) => {
        return item.name;
      });
    },
    /**
     * 校验：接口数据
     */
    validateInterfaceData(interfaceData) {
      if (interfaceData && interfaceData.length > 0) {
        let flag = true;
        interfaceData.some((item, idx) => {
          if (checkHotTableLength(item.name, 500)) {
            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;
      }
    },
    /**
     * 保存：接口
     * 计算位置
     */
    async saveInterface(interfaceData) {
      let _that = this;
      // 校验
      if (!_that.validateInterfaceData(interfaceData)) return;
      _that.saveLoading = true; // 开启：加载中...
      await _that.$api.saveOutStruChart({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.$store.getters.lastCheckedNode.id,
        struTypeCode: '99',
        chartFlag: _that.checkedNode.chartFlag, // 0：隐藏 1：显示
        mfmeaStruInputModels: interfaceData,
      }).then((res) => {
        if (res.flag) {
          // 刷新左侧树，关闭model
          _that.closeModal();
          _that.initLeftTree();
          if (res.data?.options && res.data?.options.length > 0) {
            res.data.options.forEach(options => {
              let node = JSON.parse(options);
              _that.addRightX6Node(node);
            });
            // 全屏
            // window.rightX6Graph.zoomToFit();
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
  }
};
</script>
<style lang="less">

</style>
