<template>
  <div>
    <a-form>
      <a-tabs v-model="tabName" type="card">
        <a-tab-pane
            :tab="$t('functional-analysis.add-modal.product-features-add')"
            key="addProductFeature">
          <HotTable
              ref="addProductFeature"
              key="addProductFeature"
              v-if="tabName === 'addProductFeature'"
              :formData="productFeatureData"
              :headers="headers"
              :columns="columns"
              :focusCol="focusCol"
              @formDataChange="productFeatureDataChange"
          />
          <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('functional-analysis.add-modal.library-add')"
            key="addProductFeatureFromLibrary">
          <AddProductFeatureFromLibrary
              ref="addProductFeatureFromLibrary"
              v-if="tabName === 'addProductFeatureFromLibrary'"
              :struTypeCode="struTypeCode"
              :struId="checkedNode.id"
              :selectType.sync="selectType"
              @dataChange="productFeatureLibraryDataChange"
          />
        </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 AddDFMEALibrary from "./components/AddDFMEALibrary";
import {checkHotTableLength} from "@/utils/validate";
import AddProductFeatureFromLibrary from "./components/AddProductFeatureFromLibrary";
import { getLibraryNo } from '@/utils/util';

export default {
  name: "AddProductFeature",
  components: {
    HotTable,
    AddDFMEALibrary,
    AddProductFeatureFromLibrary
  },
  props: {
    struTypeCode: {
      default: '',
      type: String
    },
    checkedNode: {
      type: Object
    }
  },
  data() {
    return {
      productFeatureData: [], // 添加产品特性
      DFMEALibraryData: [], // 添加DFMEA库
      tabName: "addProductFeature",
      columns: [
        {data: "name", type: "text"},
      ],
      headers: [this.$t('functional-analysis.add-modal.product-features')],
      focusCol: 0,
      saveLoading: false,
      selectType: 1,
      productFeatureLibraryData: [],
      checked: true,//是否同步到知识库
    };
  },
  methods: {
    /**
     * 接受子组件知识库的数据
     */
    productFeatureLibraryDataChange(val) {
      this.productFeatureLibraryData = val;
    },
    /**
     * 接受子组件handsontable数据
     */
    productFeatureDataChange(val) {
      this.productFeatureData = val;
    },
    /**
     * 接受子组件DFMEA库数据
     */
    DFMEALibraryDataChange(val) {
      this.DFMEALibraryData = val;
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新结构树
     */
    initTree() {
      this.$emit("initTree");
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      if (_that.tabName === 'addProductFeature') { // 产品特性添加：保存
        _that.saveProductFeature();
      } else if (_that.tabName === 'addDFMEALibrary') { // DFMEA库选择：保存
        _that.saveMFMEALibrary();
      } else if (_that.tabName === 'addProductFeatureFromLibrary') { // 知识库添加
        _that.saveProductFeatureLibraryToDfmea();
      }
    },
    /**
     * 构建：产品特性数据
     */
    buildProductFeatureData() {
      return this.productFeatureData.map((item) => {
        return {name: item.name, code: item.code}
      }).filter((item) => {
        return item.name;
      });
    },
    /**
     * 校验：产品特性数据
     */
    validateProductFeatureData(productFeatureData) {
      if (productFeatureData && productFeatureData.length > 0) {
        let flag = true;
        productFeatureData.some((item, idx) => {
          if (checkHotTableLength(item.name, 1000)) {
            this.$message.warning(this.$t('global-message.warn.product-features-name-length'));
            flag = false
            return true;
          }
        });
        return flag;
      } else {
        this.$message.warning(this.$t('global-message.warn.please-enter-not-name-line'))
        return false;
      }
    },
    /**
     * 保存：产品特性
     */
    saveProductFeature() {
      let _that = this;
      // 构建数据
      let productFeatureData = _that.buildProductFeatureData();
      // 校验
      if (!_that.validateProductFeatureData(productFeatureData)) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveProductFeature({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        struTypeCode: _that.struTypeCode,
        mfmeaStruInputModels: productFeatureData,
        libraryPushFlag: _that.checked,
        libraryStruNo: getLibraryNo('C')
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新右侧树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initTree();
        } 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.initTree();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false; // 关闭：加载中...
      })
    },
    /**
     * 校验：知识库-产品特性库选择
     */
    validateProductFeatureLibraryData() {
      let _that = this;
      if (_that.productFeatureLibraryData.length === 0) {
        _that.$message.warning(this.$t('global-message.warn.please-select-node'));
        return false;
      }
      return true;
    },
    /**
     * 保存：知识库添加
     */
    saveProductFeatureLibraryToDfmea() {
      let _that = this;
      // 校验
      if (!_that.validateProductFeatureLibraryData()) return;
      _that.saveLoading = true; // 开启：加载中...
      _that.$api.saveNodeFromLibrarySelect({
        fmeaId: _that.$store.getters.rfmeaId,
        parentStruId: _that.checkedNode.id,
        selectType: _that.selectType,
        libraryTypeCode: _that.selectType, // 产品特性
        libraryIds: _that.productFeatureLibraryData,
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新右侧树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initTree();
        } 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>
