<template>
  <div>
    <a-form>
      <a-tabs v-model="tabName" type="card">
        <a-tab-pane
            :tab="tab + $t('risk-analysis.add-modal.add')"
            key="addPreventionMeasure">
          <HotTable
              ref="addPreventionMeasure"
              key="addPreventionMeasure"
              v-if="tabName === 'addPreventionMeasure'"
              :formData="preventionMeasureData"
              :headers="headers"
              :columns="columns"
              :focusCol="focusCol"
              @formDataChange="preventionMeasureDataChange"
          />
          <a-checkbox v-model="checked">{{ $t('functional-analysis.add-modal.Whether-to-synchronize-to-the-knowledge-base') }}</a-checkbox>
        </a-tab-pane>
<!--        <a-tab-pane-->
<!--            :tab="$t('risk-analysis.add-modal.dfmea-library-add')"-->
<!--            key="addDFMEALibrary">-->
<!--          <AddDFMEALibraryMeasure-->
<!--              ref="addDFMEALibrary"-->
<!--              v-if="tabName === 'addDFMEALibrary'"-->
<!--              :struTypeCode="struTypeCode.indexOf('09') !== -1 ? '09' : '10'"-->
<!--              :struId="checkedNode.id"-->
<!--              @dataChange="DFMEALibraryDataChange"-->
<!--          />-->
<!--        </a-tab-pane>-->
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.knowledge-base-add')"
            key="addKnowledgeBase">
          <AddKnowledgeBase
              ref="addKnowledgeBase"
              v-if="tabName === 'addKnowledgeBase'"
              :struId="checkedNode.id"
              @getMeasureDataFromLibrary="getMeasureDataFromLibrary"
          />
        </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 AddDFMEALibraryMeasure from "./components/AddDFMEALibraryMeasure";
import AddKnowledgeBase from "./components/AddPreventiveKnowledgeBase";
import {checkHotTableLength} from "@/utils/validate";
import { getLibraryNo } from '@/utils/util';

export default {
  name: "AddPreventionMeasure",
  components: {
    HotTable,
    AddDFMEALibraryMeasure,
    AddKnowledgeBase
  },
  props: {
    tab: {
      default: '',
      type: String
    },
    struTypeCode: {
      default: '',
      type: String
    },
    checkedNode: {
      default: {},
      type: Object
    }
  },
  data() {
    return {
      measureDataFromLibrary: [],
      preventionMeasureData: [], // 添加预防措施
      DFMEALibraryData: [], // 添加DFMEA库
      tabName: "addPreventionMeasure",
      columns: [
        {data: "name", type: "text"},
      ],
      headers: [this.tab],
      focusCol: 0,
      saveLoading: false,
      checked: true,
      libraryToFmeaFlag: false
    };
  },
  methods: {
    getMeasureDataFromLibrary(data) {
      let _that = this;
      _that.measureDataFromLibrary = data;
    },
    /**
     * 接受子组件handsontable数据
     */
    preventionMeasureDataChange(val) {
      this.preventionMeasureData = val;
    },
    /**
     * 接受子组件DFMEA库数据
     */
    DFMEALibraryDataChange(val) {
      this.DFMEALibraryData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新风险分析
     */
    initRiskNet() {
      this.$emit("initRiskNet");
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addPreventionMeasure') { // 预防措施添加：保存
        _that.savePreventionMeasure();
      } else if (_that.tabName === 'addDFMEALibrary') { // DFMEA库选择：保存
        _that.saveMFMEALibrary();
      } else if (_that.tabName === 'addKnowledgeBase') {
        _that.saveMeasureFromLibrary();
      }
    },

    /**
     * 保存：预防措施
     */
    saveMeasureFromLibrary() {
      let _that = this;
      // 校验
      if (!_that.validateDFMEALibraryData()) return;
      let preventionMeasureData = [];
      for (let i = 0; i < _that.measureDataFromLibrary.length; i++)
        preventionMeasureData.push({
          name: _that.measureDataFromLibrary[i].measureName,
          libraryStruId: _that.measureDataFromLibrary[i].measureId,
          occurrence: _that.measureDataFromLibrary[i].occurrence,
          detection: _that.measureDataFromLibrary[i].detection,
          libraryVersionNo: _that.measureDataFromLibrary[i].versionNo
        })
      _that.checked = false;
      _that.libraryToFmeaFlag = true;
      // 处理保存措施
      _that.handleSaveAction(preventionMeasureData);
    },

    /**
     * 构建：预防措施数据
     */
    buildPreventionMeasureData() {
      return this.preventionMeasureData.map((item) => {
        return {name: item.name, code: item.code}
      }).filter((item) => {
        return item.name;
      });
    },
    /**
     * 校验：预防措施数据
     */
    validatePreventionMeasureData(preventionMeasureData) {
      // if (preventionMeasureData && preventionMeasureData.length > 0) {
      //   let flag = true;
      //   preventionMeasureData.some((item, idx) => {
      //     if (checkHotTableLength(item.name, 1000)) {
      //       this.$message.warning(this.$t('global-message.warn.measure-length', [idx + 1, this.tab]));
      //       flag = false;
      //       return true;
      //     }
      //   });
      //   return flag;
      // } else {
      //   this.$message.warning(this.$t('global-message.warn.please-enter-not-name-line'))
      //   return false;
      // }
      if (_that.measureDataFromLibrary.length === 0) {
        _that.$message.warning(this.$t('global-message.warn.please-select-node'));
        return false;
      }
    },
    /**
     * 保存：预防措施
     */
    savePreventionMeasure() {
      let _that = this;
      // 构建数据
      let preventionMeasureData = _that.buildPreventionMeasureData();
      // 校验
      // if (!_that.validatePreventionMeasureData(preventionMeasureData)) return;
      // 处理保存措施
      _that.handleSaveAction(preventionMeasureData);
    },
    /**
     * 处理保存措施
     * @param inputData 输入数据
     */
    handleSaveAction(inputData) {
      let _that = this;
      // 措施类型CODE：09预防，10探测
      let struTypeCode = _that.struTypeCode.indexOf('09') !== -1 ? '09' : '10';
      // 措施状态类型CODE：14当前，07优化
      let curOrOptTypeCode = _that.struTypeCode.indexOf('14') !== -1 ? '14' : '07';
      if (_that.checkedNode.struTypeCode === '06') { // 判断失效
        if (_that.checkedNode.measureChildren && _that.checkedNode.measureChildren.length > 0) {
          let nodes = _that.checkedNode.measureChildren;
          let measureNodes = nodes.filter(item => item.struTypeCode === curOrOptTypeCode);
          if (measureNodes && measureNodes.length > 0) { // 存在当前措施、优化措施
            // 左序号升序，以确保始终用最后一个措施状态
            measureNodes = measureNodes.sort((a, b) => a.leftNo - b.leftNo);
            _that.saveAction(measureNodes[measureNodes.length - 1].id, struTypeCode, inputData);
          } else {
            _that.saveMeasure({
              measureNode: {nodeId: _that.checkedNode.id, struTypeCode: curOrOptTypeCode},
              actionNode: {struTypeCode: struTypeCode, inputData: inputData},
            });
          }
        } else { // 失效无措施状态时
          _that.saveMeasure({
            measureNode: {nodeId: _that.checkedNode.id, struTypeCode: curOrOptTypeCode},
            actionNode: {struTypeCode: struTypeCode, inputData: inputData},
          });
        }
      } else { // 判断当前措施、优化措施、措施组
        _that.saveAction(_that.checkedNode.id, struTypeCode, inputData);
      }
    },
    /**
     * 校验：DFAME库选择
     */
    validateDFMEALibraryData() {
      let _that = this;
      // if (_that.DFMEALibraryData.length === 0) {
      //   _that.$message.warning(this.$t('global-message.warn.please-select-node'));
      //   return false;
      // }
      if (_that.measureDataFromLibrary.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 preventionMeasureData = _that.DFMEALibraryData.map((item) => {
        return {struId: item.id, name: item.name}
      });
      // 处理保存措施
      _that.handleSaveAction(preventionMeasureData);
    },
    /**
     * 保存措施
     * @param nodeId 节点ID
     * @param struTypeCode 节点类型CODE
     * @param inputData 输入数据
     */
    saveAction(nodeId, struTypeCode, inputData) {
      let _that = this;
      _that.saveLoading = true; // 开启：加载中...
      // 保存标识 libraryAddFlag为true 则是DFAME库添加，false为手动添加
      let libraryAddFlag = false;
      inputData.forEach(item => {
        if (item.hasOwnProperty('struId') && item.struId !== null) {
          libraryAddFlag = true;
        }
      });
      _that.$api.saveAction({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: nodeId,
        struTypeCode: struTypeCode,
        mfmeaStruInputModels: inputData,
        libraryAddFlag: libraryAddFlag,
        dOrP: 'D',
        libraryToFmeaFlag: _that.libraryToFmeaFlag,
        libraryPushFlag: _that.checked,
        libraryStruNo: getLibraryNo('PC')
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新右侧树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initRiskNet();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false; // 关闭：加载中...
      });
    },
    /**
     * 添加措施状态
     * @param measureNode 措施状态对象
     * @param actionNode 措施对象
     */
    saveMeasure({measureNode, actionNode}) {
      let _that = this;
      _that.$api.saveMeasure({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: measureNode.nodeId,
        struTypeCode: measureNode.struTypeCode,
      }).then((res) => {
        if (res.flag) {
          // 保存措施
          _that.saveAction(res.data.measureId, actionNode.struTypeCode, actionNode.inputData);
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      });
    },
  }
};
</script>
<style lang="less">

</style>
