<template>
  <div>
    <a-form v-bind='formItemLayout'>
      <a-form-item required :label="$t('functional-analysis.top-modal.import-file')">
        <a-upload
            name='file'
            action=''
            accept='.rfmea'
            :fileList='fileList'
            :customRequest="uploadFile"
            :max-count="1"
            :remove='removeFile'>
          <a-button>
            <a-icon type="upload"/>
            {{ $t('global-btn.select-file') }}
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>

    <div class="dialog-footer text-right mt10">
      <a-button v-if="this.$api.isLook !== '1'" @click="importFile" type="primary" :loading="importLoading">
        {{ $t('global-btn.import') }}
      </a-button>
    </div>
  </div>
</template>
<script>

export default {
  data() {
    return {
      /** 表单布局 */
      formItemLayout: {
        // xxl: '1600px',
        // xl: '1200px',
        // lg: '992px',
        // md: '768px',
        // sm: '576px',
        // xs: '480px',
        labelCol: {
          xxl: {span: 3},
          xl: {span: 3},
          lg: {span: 3},
          md: {span: 24},
          xs: {span: 24},
          sm: {span: 24}
        },
        wrapperCol: {
          xxl: {span: 21},
          xl: {span: 21},
          lg: {span: 21},
          md: {span: 24},
          xs: {span: 24},
          sm: {span: 24}
        }
      },
      /** 文件上传集合 */
      fileList: [],
      /** 导入Loading */
      importLoading: false
    };
  },
  methods: {
    /**
     * 刷新左侧树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 刷新右侧树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 刷新变体下拉
     */
    initVariantSelect() {
      this.$emit("initVariantSelect");
    },
    /**
     * 清空变体下拉值
     */
    cleanVariantSelect() {
      this.$emit("cleanVariantSelect");
    },
    /**
     * 刷新默认顶部按钮状态
     */
    refreshDefaultBtnStatus() {
      this.$emit("refreshDefaultBtnStatus");
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 校验文件
     * @param file 文件
     */
    validateFile(file) {
      if (file.size > 52428800) {
        this.$message.warning(this.$t('global-message.warn.uploaded-files-cannot-exceed'));
        this.fileList = [];
        return false;
      }
      return true;
    },
    /**
     * 上传文件
     * @param obj 回调对象
     */
    uploadFile(obj) {
      // 校验
      if (!this.validateFile(obj.file)) return;
      this.fileList = [];
      this.fileList.push(obj.file);
    },
    /**
     * 文件删除
     * @param file 文件
     */
    removeFile(file) {
      let files = this.fileList;
      for (let i = files.length - 1; i >= 0; i--) {
        if (file.uid === files[i].uid) files.splice(i, 1);
      }
    },
    /**
     * 导入文件
     */
    importFile() {
      let _that = this;
      if (_that.fileList.length === 0) {
        _that.$message.warn(this.$t('global-message.warn.select-file'), 1);
        return;
      }
      /************** 数据组装 Start **********/
      let formData = new FormData();
      // 添加额外的参数
      formData.append("file", _that.fileList[0]);
      formData.append("fmeaId", _that.$store.getters.fmeaId);
      formData.append("rfmeaId", _that.$store.getters.rfmeaId);
      /************** 数据组装 End **********/

      _that.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.warn.import-overwrite-all-data'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          _that.importLoading = true;
          _that.$api.RFMEAImport(
              formData
          ).then((res) => {
            if (res.flag) {
              // 添加成功
              _that.$message.success(res.message, 1);
              let rfmeaId = res.data.fmeaId;
              // 设置url：rfmeaId参数值
              _that.setUrlRfmeaIdParam(rfmeaId);
              // 储存rfmeaId
              _that.$store.dispatch('fmeaTree/set', {
                key: "rfmeaId",
                value: rfmeaId
              });
              sessionStorage.setItem("rfmeaId", rfmeaId);
              // 清空缓存节点
              _that.$store.dispatch("fmeaTree/clear");
              _that.initDraw();
            } else {
              _that.$message.error(res.message, 1);
            }
          }).catch((error) => {
            _that.$message.error(error.response.data.message, 1);
          }).finally(() => {
            _that.importLoading = false;
            // 刷新默认顶部按钮状态
            _that.refreshDefaultBtnStatus();
          });
        },
      });
    },
    /**
     * 设置url：rfmeaId参数值
     * @param value 参数值
     */
    setUrlRfmeaIdParam(value) {
      let query = this.$router.history.current.query;
      let path = this.$router.history.current.path;
      // 对象的拷贝
      let newQuery = JSON.parse(JSON.stringify(query));
      // 地址栏的参数值赋值
      newQuery.rfmeaId = value;
      this.$router.push({path, query: newQuery});
    },
    /**
     * 编制页面进入时初始化
     */
    initDraw() {
      let _that = this;
      _that.$api.initDraw({
        fmeaId: _that.$store.getters.rfmeaId
      }).then((res) => {
        if (res.flag) {
          // 关闭弹窗，刷新左、右侧树
          _that.closeModal();
          _that.initLeftTree();
          _that.initRightTree();
          _that.initVariantSelect();
          _that.cleanVariantSelect();
        } else {
          _that.$message.error(res.message, 1);
        }
      });
    }
  },
};
</script>
<style lang="less" scoped>

</style>
