/**version-1.0*/
import {read, utils} from 'xlsx'

let tmixins = {};
var XLSX = window.XLSX || {read, utils};
import {
  getToken
} from '../../utils/auth';
import { getErrorMsg } from '@base/utils/index.js'

let configUtil = {
  baseUrl: process.env.VUE_APP_BASE_API,
  XLSX,
  getToken
};
let importTimer = null;
let loadingObj = null
tmixins = {
  name: 'excelImport',
  props: ['param'],
  data() {
    return {
      excTime: 0,
      showImportDialog: false,
      showImportDialog2: false,
      falseValue: false,
      fileRaw: false,
      isEnd: false,
      currentIndex: 0,
      excelTemplate: "",
      prefix: '/user',
      dataSize: 0,
      totalSuccessNum: 0,
      totalErrorNum: 0,
      percentageNum: 0,
      successRows: [],
      failRows: [],
      oriCols: [],
      showImportResult: false,
      resultType: '',
      option: {},
      showContent: false,
      resOption: {},
      abc: "A"
    }
  },
  created() {

  },
  beforeDestroy() {
    // this.clearImportTimer()
  },
  methods: {
    initResGird() {
      var that = this;
      let tableRef = 'resGrid';
      let resultColumns = this.param.resultColumns || [];
      let columns = [
        {
          type: 'checkbox',
          fixed: 'left',
          width: 48,
          resizable: false,
          headerClassName: 'vxe-hcs',
          className: 'vxe-hcs'
        },
        {
          field: '_resultContent',
          title: this.$t1('结果'),
          width: 250,
          fixed: 'left',
          slots: {
            default: ({
                        row,
                        $rowIndex,
                        $table
                      }) => {
              return that.handleRes(row._impReturnMsg);
            }
          }
        },
        ...resultColumns
      ];
      let cCols = this.oriCols.map((oriCol, index) => {
        let col = {
          field: oriCol.field,
          title: oriCol.title,
          width: 150
        };
        if (index == 0) {
          col.fixed = 'left';
        }
        return col;
      });
      columns = columns.concat(cCols);

      let tableOption = {
        vue: this,
        tableRef: tableRef,
        tableNameRequired: false,
        columns: columns,
        config: {
          toolbarConfig: {
            custom: false
          }
        }
      };

      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.resOption = opts;
        this.$nextTick(() => {
          let rows = this.resultType == 1 ? this.successRows : this.failRows;
          let tDatas = rows.map((item, index) => {
            return item;
          });
          this.$refs.resGrid.loadData(tDatas);
        });
      });
    },
    exc() {
      this.option = this.param;
      this.showContent = true;
      this.showImportDialog = true;
      this.showImportDialog2 = false;
    },
    showSuccessResult() {
      this.showImportResult = true;
      this.resultType = 1;
      setTimeout(() => {
        this.$nextTick(() => {
          this.initResGird();
        });
      }, 0)
    },
    showErrorResult() {
      this.showImportResult = true;
      this.resultType = 0;
      setTimeout(() => {
        this.$nextTick(() => {
          this.initResGird();
        });
      }, 0)
    },
    fileChange(file) {
      if (file) {
        this.fileRaw = file.raw;
      } else {
        this.fileRaw = false;
      }
    },
    dialogClose1() {
      this.$emit("update:visiable", false);
      this.showContent = false;
    },
    openImportDialog() {
      this.showImportDialog = true;
    },
    confirmExport() {

    },
    async dialogPrimary1() {
      let that = this;
      let option = this.option;
      let saveUrl = option.saveUrl;
      if (!saveUrl) {
        return false;
      }

      if (!(this.fileRaw)) {
        this.$baseAlert(this.$t2('请上传附件', 'components.excelImport.warmMsg1'));
        return false;
      }
      this.showImportDialog = false;
      if (!option.onConfirm) {
        this.showImportDialog2 = true;
      }
      this.$nextTick(() => {
        this.readExcel(this.fileRaw, function (resultData) {
          if (option.onConfirm) {
            option.onConfirm(resultData, that.fileRaw);
          } else {
            that.syncDataForImport({
              multi: false,
              data: resultData,
              saveUrl: saveUrl
            });
          }
        });

      });
    },
    dialogClose2() {
      this.clearImportTimer();
      this.showImportDialog2 = false;
      this.showContent = false;
      this.option.callback && this.option.callback();
    },
    dialogPrimary2() {
      this.clearImportTimer();
      this.showImportDialog2 = false;
      this.showContent = false;
      this.option.callback && this.option.callback(this.resultData);
    },
    async readExcel(file, callback) {
      let that = this;
      let option = this.option;

      const fileReader = new FileReader();
      fileReader.onload = async (ev) => {
        var resultData;
        try {
          let fileContent = ev.target.result
          callback(fileContent);
        } catch (et) {
          that.showContent = false;
          console.error(et)
        }
      };
      fileReader.readAsText(file, 'UTF-8');
    },
    syncDataForImport(opts) {
      let showResult = this.param.showResult;
      if (!showResult) {
        this.dialogClose1();
      }

      let option = this.option
      this.$http({
        url: opts.saveUrl,
        method: `post`,
        data: {
          data: opts.data
        },
        isLoading: true,
        success: res => {
          var successNum = 0;
          var failNum = 0;
          var multiRows = res.objx;
          this.dataSize = multiRows.length;
          for (let i = 0; i < multiRows.length; i++) {
            let row = multiRows[i];
            if (row.impReturnType == "success") {
              row._impReturnMsg = this.$t1('导入成功')
              successNum++;
              this.successRows.push(row);
            } else {
              row._impReturnMsg = row.impReturnMsg
              failNum++;
              this.failRows.push(row);
            }
          }
          this.totalSuccessNum = successNum;
          this.totalErrorNum = failNum;

          if (!showResult) {
            this.$message({
              message: res.content,
              type: 'success',
              duration: 500,
              onClose: t => {
                option.callback && option.callback(res)
              }
            });
          } else {
            this.showImportDialog = false;
            this.showImportDialog2 = true;
          }

        }
      });
    },
    handleRes(val) {
      /* var content = val;
      var text = content;
      if (content && content.indexOf("Exception") >= 0) {
        var index0 = content.lastIndexOf("*]");
        if (index0 >= 0) {
          text = content.substr(index0);
          if (text) {
            var index1 = text.indexOf("Exception:");
            if (index1 >= 0) {
              text = text.substr(index1 + 10);
            }
          }
        }
      } */
      let text = getErrorMsg(val)
      return text;
    },
    exportToExcel() {
      let str = this.resultType === 1 ? this.$t2('成功', 'components.excelImport.success') : this.$t2('失败', 'components.excelImport.fail');
      let fileName = this.$t2('导入结果导出', 'components.excelImport.exportFileName') + '（' + str + '）';
      let $grid = this.$refs.resGrid;
      let columns = $grid.getColumns();
      if (columns && columns.length) {
        let fields = columns.filter((item, index) => {
          return index > 0 && item.property;
        }).map((item, index) => {
          return item.property;
        });
        this.$refs.resGrid.exportData({
          filename: fileName,
          mode: 'all',
          type: 'csv',
          columns: fields
        });
      }
    },
    createImportTimer() {
      this.excTime = 0;
      let beginTime = new Date().getTime();
      importTimer = setInterval(() => {
        let nowTime = new Date().getTime();
        let diffTime = (nowTime - beginTime) / 1000;
        this.$set(this, 'excTime', this.$baseLodash.round(diffTime, 2));
      }, 100);
    },
    clearImportTimer() {
      clearInterval(importTimer);
      loadingObj && loadingObj.close();
    },
    async dialogPrimary3() {
      if (!(this.fileRaw)) {
        this.$baseAlert(this.$t2('请上传附件', 'components.excelImport.warmMsg1'));
        return false;
      }
      let that = this;
      let option = this.option;
      loadingObj = this.$baseLoading({
        target: document.body,
        background: 'unset'
      });
      this.readExcel(this.fileRaw, function (resultData) {
        try {
          if (option.callback && option.callback(resultData) !== false) {
            that.showImportDialog = false;
          }
        } catch (et) {
          console.error(et);
        }
        setTimeout(function () {
          loadingObj && loadingObj.close();
        }, 200);
      });
    }
  }
};
export const mixins = tmixins;
