/**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: {}
    }
  },
  created() {

  },
  beforeDestroy() {
    this.clearImportTimer()
  },
  methods: {
    initResGird() {
      var that = this;
      let tableRef = 'resGrid';
      let columns = [{
        type: 'checkbox',
        fixed: 'left',
        width: 48,
        resizable: false,
        headerClassName: 'vxe-hcs',
        className: 'vxe-hcs'
      },
        {
          field: 'impNumber',
          title: this.$t2('行号', 'components.excelImport.impNumber'),
          width: 100,
          fixed: 'left'
        },
        {
          field: '_resultContent',
          title: this.$t2('结果', 'components.excelImport.resultContent'),
          width: 250,
          fixed: 'left',
          slots: {
            default: ({
                        row,
                        $rowIndex,
                        $table
                      }) => {
              return that.handleRes(row._resultContent);
            }
          }
        }
      ];
      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;
      });
    },
    exc() {
      this.option = this.param;
      this.showContent = true;
      this.showImportDialog = true;
      this.showImportDialog2 = false;
    },
    showSuccessResult() {
      this.showImportResult = true;
      this.resultType = 1;
      this.$nextTick(() => {
        this.initResGird();
        this.$nextTick(() => {
          let tDatas = this.successRows.map((item, index) => {
            // item.id = index;
            return item;
          });
          this.$refs.resGrid.loadData(tDatas);
        });
      });
    },
    showErrorResult() {
      this.showImportResult = true;
      this.resultType = 0;
      this.$nextTick(() => {
        this.initResGird();
        this.$nextTick(() => {
          let tDatas = this.failRows.map((item, index) => {
            // item.id = index;
            return item;
          });
          this.$refs.resGrid.loadData(tDatas);
        });
      });
    },
    fileChange(file) {
      if (file) {
        this.fileRaw = file.raw;
      } else {
        this.fileRaw = false;
      }
    },
    dialogClose1() {
      this.$emit("update:visiable", false);
      this.showContent = false;
    },
    async dialogPrimary1() {
      let that = this;
      let option = this.option;
      let saveUrl = option.saveUrl;
      if (!saveUrl) {
        this.dialogPrimary3();
        return false;
      }

      if (!(this.fileRaw)) {
        this.$baseAlert(this.$t2('请上传附件', 'components.excelImport.warmMsg1'));
        return false;
      }
      this.createImportTimer();
      this.showImportDialog = false;
      if (!option.onConfirm) {
        this.showImportDialog2 = true;
      }
      this.$nextTick(() => {
        try {
          this.readExcel(this.fileRaw, function (resultData) {
            if (option.onConfirm) {
              option.onConfirm(resultData.data, that.fileRaw);
            } else {
              that.syncDataForImport({
                multi: false,
                data: resultData,
                saveUrl: saveUrl
              });
            }
          });
        } catch (et) {
          that.clearImportTimer();
          console.error(et);
        }
      });
    },
    async langdialogPrimary() {
      let that = this;
      let option = this.option;
      let saveUrl = option.saveUrl;
      if (!saveUrl) {
        this.dialogPrimary3();
        return false;
      }

      if (!(this.fileRaw)) {
        this.$baseAlert(this.$t2('请上传附件', 'components.excelImport.warmMsg1'));
        return false;
      }
      this.createImportTimer();
      this.showImportDialog = false;
      if (!option.onConfirm) {
        this.showImportDialog2 = true;
      }
      this.$nextTick(() => {
        try {
          this.readExcel(this.fileRaw, function (resultData) {
            if (option.onConfirm) {
              option.onConfirm(resultData.data, that.fileRaw);
            } else {
              that.syncDataForImport({
                multi: false,
                data: resultData,
                saveUrl: saveUrl
              });
            }
          });
        } catch (et) {
          that.clearImportTimer();
          console.error(et);
        }
      });
    },
    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 {
          /*const arrayBuffer = ev.target.result;
          const decoder = new TextDecoder('gbk'); // 指定为 GBK 编码
          const fileContent = decoder.decode(arrayBuffer);*/

          let fileContent = ev.target.result
          const data = JSON.parse(fileContent);

          var titles = Object.keys(data[0]);
          var fields = titles;
          var columns = [];
          var cols = fields.map(item => {
            return {
              field: item,
              title: item,
              width: 100,
            }
          });
          var oriCols = JSON.parse(JSON.stringify(cols));//列信息
          this.oriCols = oriCols;

          resultData = {
            data: data,
            titles: titles,
            fields: fields,
            oriCols: oriCols
          };
          this.resultData = resultData;
          callback(resultData);
        } catch (et) {
          that.showContent = false;
          that.clearImportTimer();
          console.error(et)
        }
      };
      // fileReader.readAsBinaryString(file);
      fileReader.readAsText(file, 'UTF-8');


    },
    syncDataForImport(opts) {
      let that = this;
      var multi = this.option.multi;
      var resultData = opts.data;
      var datas = resultData.data;
      var titles = resultData.titles;
      var fields = resultData.fields;
      let uniqueFields = resultData.uniqueFields || [];
      var saveUrl = opts.saveUrl;
      var size = datas.length;
      var index = 0;
      var successNum = 0;
      var failNum = 0;
      var dialogObj = this.$refs.importDialog.$el;
      var successNumObj = dialogObj.querySelector(".successNum");
      var failNumObj = dialogObj.querySelector(".failNum");
      var percentageObj = dialogObj.querySelector(".percentage");
      var doneNumObj = dialogObj.querySelector(".doneNum");
      dialogObj.querySelector(".dataSize").innerText = size;

      that.successRows = [];
      that.failRows = [];

      var multiSize = opts.multiSize || 2;

      let groupIndex = 0;
      let groupDatas = [];

      var compareV = function (property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
        }
      }

      var prevHandleData = function (percentageStr, excNum) {

        successNumObj.innerText = successNum;
        failNumObj.innerText = failNum;
        doneNumObj.innerText = successNum + failNum;
        that.percentageNum = percentageStr;
        let isEnd = false;
        if (uniqueFields.length) {
          isEnd = groupIndex + 1 >= groupDatas.length;
        } else {
          isEnd = index + excNum >= size;
        }
        if (!isEnd) {
          index = index + excNum;
          groupIndex = groupIndex + 1;
          setTimeout(function () {
            handleData();
          }, 1);
        } else {
          setTimeout(function () {
            that.clearImportTimer();
          }, 300);
        }
      };

      let getDefaultValue = (row) => {
        let value = null;
        let defaultValue = this.option.defaultValue;
        if (defaultValue) {
          if (typeof defaultValue == "function") {
            value = defaultValue(row) || {};
          } else {
            value = defaultValue || {};
          }
        }
        return value;
      }

      let handleData = () => {
        if (!that.isEnd && index < size) {
          let a = 1
          var param;
          var excNum;

          var data = datas[index];
          data.impSeq = index;
          data.impNumber = index + 1;
          excNum = 1;
          datas[index] = data;

          param = data;
          let defaultValue = getDefaultValue(data);
          if (defaultValue) {
            Object.assign(param, defaultValue);
          }

          var percentageStr = parseInt((index + excNum) * 100 / size);
          if (param == null || param.length == 0) {
            if (that.showContent) {
              prevHandleData(percentageStr, excNum);
            }
            return;
          }

          that.$http({
            url: saveUrl,
            method: "post",
            data: param,
            resultType: "special",
            modal: false,
            callback: (resultMsg) => {
              var data = datas[index];
              data._resultType = resultMsg.type;
              data._resultContent = (resultMsg.type == "success") ? this.$t2('导入成功', 'components.excelImport.importSucess') : resultMsg.content;

              if (resultMsg.type == "success") {
                successNum++;
                that.successRows.push(data);
              } else {
                failNum++;
                that.failRows.push(data);
              }
              if (that.showContent) {
                prevHandleData(percentageStr, excNum);
              }
            }
          }).catch(function (et) {
            that.isEnd = true;
            that.clearImportTimer();
            console.error(et);
          });
        }
      }
      handleData();
    },
    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;
