<template>
  <div>
    <a-form>
      <a-tabs v-model="tabName" type="card">
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.failure-add')"
            key="addFault">
          <HotTable
              ref="addFault"
              key="addFault"
              v-if="tabName === 'addFault'"
              :formData="faultData"
              :headers="headers"
              :columns="columns"
              :focusCol="focusCol"
              @formDataChange="functionDataChange"
          />
          <span style="display: block">
            <a-checkbox v-model="checked">{{ $t('functional-analysis.add-modal.Whether-to-synchronize-to-the-knowledge-base') }}</a-checkbox>
          </span>
        </a-tab-pane>
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.p-chart-add')"
            key="addParameter">
          <AddParameter
              ref="addParameter"
              v-if="tabName === 'addParameter'"
              :struTypeCode="struTypeCode"
              :struId="checkedNode.id"
              :selectType.sync="selectType"
              @dataChange="parameterDataChange"
          />
        </a-tab-pane>
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.library-add')"
            key="addFromLibrary">
          <AddFromLibrary
              ref="addFromLibrary"
              v-if="tabName === 'addFromLibrary'"
              :struTypeCode="struTypeCode"
              :struId="checkedNode.id"
              :selectType.sync="selectType"
              @dataChange="faultLibraryDataChange"
          />
        </a-tab-pane>
        <a-tab-pane
            v-if="isAiSwtich"
            :tab="$t('functional-analysis.add-modal.ai-add')"
            key="addAi">
          <AddAi
              ref="addAi"
              v-if="tabName === 'addAi'"
              :struTypeCode="struTypeCode"
              :struName="checkedNode.description"
              @aiDataChange="aiDataChange"
          />
        </a-tab-pane>
      </a-tabs>
    </a-form>
    <!-- 失效参考示例图 -->
    <span v-if="tabName === 'addFault'">
      {{ $t('functional-analysis.add-modal.reference.example') }}
      <div class="header clear">
        <a>
          <img src="@/assets/fault.png" alt="logo" class="faultLogo"/>
        </a>
      </div>
    </span>
    <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 AddParameter from "./components/AddParameter";
import AddFromLibrary from "./components/AddFromLibrary";
import {checkHotTableLength} from "@/utils/validate";
import { getLibraryNo } from '@/utils/util';
import AddAi from "./components/AddAi.vue";

export default {
  name: "AddFault",
  components: {
    AddAi,
    HotTable,
    AddDFMEALibrary,
    AddParameter,
    AddFromLibrary
  },
  props: {
    struTypeCode: {
      default: '',
      type: String
    },
    checkedNode: {
      type: Object
    }
  },
  data() {
    return {
      faultData: [], // 添加失效
      DFMEALibraryData: [], // 添加DFMEA库
      aiData: [], // 添加AI
      tabName: "addFault",
      columns: [
        {data: "name", type: "text"},
      ],
      headers: [this.$t('functional-analysis.add-modal.failure')],
      focusCol: 0,
      saveLoading: false,
      selectType: 1,
      checked: true, //是否同步到知识库
      isAiSwtich: true
    };
  },
  methods: {
    /**
     * 接受子组件handsontable数据
     */
    functionDataChange(val) {
      this.faultData = val;
    },
    /**
     * 接受子组件DFMEA库数据
     */
    DFMEALibraryDataChange(val) {
      this.DFMEALibraryData = val;
    },
    /**
     * 接受子组件DFMEA库数据
     */
    faultLibraryDataChange(val) {
      this.DFMEALibraryData = val;
    },
    /**
     * P图
     * @param val
     */
    parameterDataChange(val) {
      this.parameterData = val;
    },
    /**
     * Ai
     * @param val
     */
    aiDataChange(val) {
      this.aiData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新右侧结构树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addFault') { // 失效添加：保存
        _that.saveFault();
      } else if (_that.tabName === 'addDFMEALibrary') { // DFMEA库选择：保存
        _that.saveMFMEALibrary();
      } else if (_that.tabName === 'addParameter') { // P图选择：保存
        _that.saveParameter();
      } else if (_that.tabName === 'addFromLibrary') { // 知识库添加
        _that.saveFaultLibraryToDfmea();
      } else if (_that.tabName === 'addAi') { // AI选择：保存
        _that.saveAi();
      }
    },
    /**
     * 构建：失效数据
     */
    buildFaultData() {
      return this.faultData.map((item) => {
        return {name: item.name, code: item.code}
      }).filter((item) => {
        return item.name;
      });
    },
    /**
     * 校验：失效数据
     */
    validateFaultData(faultData) {
      if (faultData && faultData.length > 0) {
        let flag = true;
        faultData.some((item, idx) => {
          if (checkHotTableLength(item.name, 1000)) {
            this.$message.warning(this.$t('global-message.warn.failure-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;
      }
    },
    /**
     * 保存：失效
     */
    saveFault() {
      let _that = this;
      // 构建数据
      let faultData = _that.buildFaultData();
      // 校验
      if (!_that.validateFaultData(faultData)) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveFault({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        struTypeCode: _that.struTypeCode,
        mfmeaStruInputModels: faultData,
        libraryPushFlag: _that.checked,
        libraryStruNo: getLibraryNo('FM')
      }).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; // 关闭：加载中...
      })
    },
    /**
     * 校验：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.initRightTree();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false; // 关闭：加载中...
      })
    },

    /**
     * 保存：知识库添加
     */
    saveFaultLibraryToDfmea() {
      let _that = this;
      // 校验
      if (!_that.validateDFMEALibraryData()) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveNodeFromLibrarySelect({
        fmeaId: _that.$store.getters.rfmeaId,
        parentStruId: _that.checkedNode.id,
        selectType: _that.selectType,
        libraryTypeCode: '06',
        libraryIds: _that.DFMEALibraryData,
      }).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; // 关闭：加载中...
      })
    },

    validateParameterData() {
      let _that = this;
      if (!_that.parameterData || _that.parameterData.length === 0) {
        _that.$message.warning(this.$t('global-message.warn.please-select-node'));
        return false;
      }
      return true;
    },

    saveParameter() {
      let _that = this;
      // 校验
      if (!_that.validateParameterData()) return;
      // 构建数据
      let ids = _that.parameterData.map((item) => {
        return ' ' + item.pdId;
      });
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.funAnalysisPdSave({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        // selectType: _that.selectType,
        struTypeCode: _that.struTypeCode,
        selectPdIds: ids.toString().trim()
      }).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; // 关闭：加载中...
      })
    },

    /**
     * 校验AI添加
     * @returns {boolean}
     */
    validateAiData(faultData) {
      if (faultData && faultData.length > 0) {
        let flag = true;
        faultData.some((item, idx) => {
          if (checkHotTableLength(item.name, 500)) {
            this.$message.warning(this.$t('global-message.warn.failure-name-length', [idx + 1]));
            flag = false
            return true;
          }
        });
        return flag;
      } else {
        this.$message.warning(this.$t('global-message.warn.please-select-a-piece-of-data'))
        return false;
      }
    },

    /**
     * AI选择：保存
     */
    saveAi() {
      let _that = this;
      // 构建数据
      let faultData = _that.aiData.map((item) => {
        return { name: item.name }
      });
      // 校验
      if (!_that.validateAiData(faultData)) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveFault({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        struTypeCode: _that.struTypeCode,
        mfmeaStruInputModels: faultData,
      }).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; // 关闭：加载中...
      })
    },
  },
  mounted() {
    this.isAiSwtich = window.apiObj.isAiSwtich;
  },
};
</script>
<style lang="less">
.faultLogo{
  height: 280px;
  width: 900px;
}
</style>
