<!-- 边界图右侧添加结构弹窗, 后面看情况和左侧树用同一个弹窗 -->
<template>
  <div>
    <DragModal
        v-a-modal
        :footer='null'
        :title="addTitle"
        :visible='addParameterVisible'
        :width='1000'
        destroy-on-close
        @cancel='closeModal'
    >
      <!-- 添加 -->
      <div>
        <a-form>
          <HotTable
              key='addParameter'
              ref='addTable'
              :focusCol='undefined'
              :columns='columns'
              :formData='parameterData'
              :headers='headers'
              @formDataChange='parameterDataChange'
          />
        </a-form>
        <div slot='footer' v-if="$api.isLook !== '1'" class='mt10 text-right'>
          <a-button @click='closeModal'>
            {{ $t('global-btn.cancel') }}
          </a-button>
          <a-button
              v-preventReClick
              :loading='saveLoading'
              class='ml10'
              type='primary'
              @click='save()'>
            {{ $t('global-btn.confirm') }}
          </a-button>
        </div>
      </div>
    </DragModal>
  </div>
</template>
<script>

import HotTable from '@/components/HotTable/index.vue';
import {getDiff} from "@/utils/tree";
import {checkHotTableLength} from "@/utils/validate";

const selectOptions = ['=', '>', '<', '>=', '<=', '<>'];

export default {
  name: 'AddParameter',
  components: {
    HotTable
  },
  props: {
    struTypeCode: {
      default: '',
      type: String
    },
    checkedNode: {
      type: Object
    },
    addType: {
      type: String,
      default: ''
    }
  },
  watch: {
    addParameterVisible(value) {
      if (value) {
        let that = this;
        setTimeout(function () {
          that.initHotData();
        }, 100);
      }
    },
  },
  data() {
    return {
      parameterData: [], // 添加结构
      tabName: 'addParameter',
      /** 表格数据 */
      tableData: [],
      columns: [
        {data: 'name', type: 'text'},
        {
          data: 'featureLogic', type: 'text',
          editor: 'select',
          selectOptions: selectOptions
        },
        {data: 'featureValue', type: 'text'},
        {data: 'unit', type: 'text'},
        {data: 'tolerance', type: 'text'}
      ],
      headers: [
        this.$t('structural-analysis.p-chart.edit-modal.name'),
        this.$t('structural-analysis.p-chart.edit-modal.symbol'),
        this.$t('structural-analysis.p-chart.edit-modal.value'),
        this.$t('structural-analysis.p-chart.edit-modal.unit'),
        this.$t('structural-analysis.p-chart.edit-modal.tolerance'),
      ],
      focusCol: 0,
      saveLoading: false,
      selectType: 1,
      addParameterVisible: false,
      addTitle: '',
      pdCode: '',
    };
  },
  methods: {
    /**
     * 接受子组件handsontable数据
     */
    parameterDataChange(val) {
      this.parameterData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.addParameterVisible = false;
      this.parameterData = [];
      // this.$emit('closeModal');
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addParameter') { // 结构添加：保存
        let parameterData = _that.buildParameterData();
        _that.saveParameter(parameterData);
      }
    },
    /**
     * 构建：结构数据
     */
    buildParameterData() {
      let data = this.parameterData.map((item) => {
        return {
          name: item.name,
          featureLogic: item.featureLogic,
          featureValue: item.featureValue,
          unit: item.unit,
          tolerance: item.tolerance,
          pdId: item.pdId
        };
      }).filter((item) => {
        return item.name;
      });
      let var1 = this.tableData.map(item => {
        return item.pdId;
      });
      let var2 = data.map(item => {
        return item.pdId;
      });
      // 取交集，与初始化数据对比，缺失为已删除
      let diff = getDiff(var1, var2);
      if (diff && diff.length > 0) {
        for (let i = 0; i < diff.length; i++) {
          // 补全数据（已删除）
          data.push({pdId: diff[i]});
        }
      }
      return data;
    },
    /**
     * 保存
     */
    async saveParameter(parameterData) {
      let _that = this;
      // 校验
      if (!_that.validateStructureData(parameterData)) return;
      _that.saveLoading = true; // 开启：加载中...
      await _that.$api.rdfmPdSave({
        struId: _that.$store.getters.parameterCheckedNode.id,
        fmeaId: _that.$store.getters.rfmeaId,
        pdCode: _that.pdCode,
        pdInputModels: parameterData,
      }).then((res) => {
        if (res.flag) {
          // 刷新左侧树，关闭model
          _that.$emit('getInitData', _that.$store.getters.parameterCheckedNode);
          _that.closeModal();
        } else {
          this.$message.error(res.message);
        }
      }).finally(() => {
        _that.saveLoading = false;
      });
    },
    // 表格渲染
    initHotData() {
      let that = this;
      // that.$refs.addTable.$refs[that.$refs.addTable.ref].hotInstance.loadData(null);
      // that.parameterData = [{
      //     name: '', featureLogic: '', featureValue: '', unit: '', tolerance: ''
      // }];
      // that.$refs.addTable.$refs[that.$refs.addTable.ref].hotInstance.loadData(that.parameterData);
      // 获取最小行数
      let data = {
        fmeaId: that.$store.getters.rfmeaId,
        struId: that.$store.getters.parameterCheckedNode.id,
        pdCode: that.pdCode
      };
      that.$api.rdfmPdSaveInit(data).then(res => {
        if (res.flag) {
          setTimeout(function () {
            that.parameterData = JSON.parse(res.data.jsonStr);
            that.tableData = JSON.parse(res.data.jsonStr);
            that.$refs.addTable.$refs[that.$refs.addTable.ref].hotInstance.loadData(JSON.parse(res.data.jsonStr));
          }, 100);
        } else {
          that.$notification.error({message: res.message});
        }
      });
    },

    /**
     * 校验：结构数据
     */
    validateStructureData(structureData) {
        if (structureData && structureData.length > 0) {
            let flag = true;
            structureData.some((item, idx) => {
                if (checkHotTableLength(item.name, 500)) {
                    this.$message.warning(this.$t('global-message.warn.name-length', [idx + 1]));
                    flag = false
                    return true;
                }
                if (checkHotTableLength(item.featureValue, 500)) {
                    this.$message.warning(this.$t('global-message.warn.row.feature-value-length', [idx + 1]));
                    flag = false
                    return true;
                }
                if (checkHotTableLength(item.unit, 30)) {
                    this.$message.warning(this.$t('global-message.warn.row.unit-length', [idx + 1]));
                    flag = false
                    return true;
                }
                if (checkHotTableLength(item.tolerance, 30)) {
                    this.$message.warning(this.$t('global-message.warn.row.tolerance-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;
        }
    },
  }
};
</script>
<style lang='less' scoped>

</style>
