<template>
  <div class="leo-excel-uploader">
    <el-upload
        class="excel-uploader-box"
        v-show="uploaderShow"
        :action="uploaderRequestUrl"
        name="file"
        :headers="uploaderHeaders"
        :data="uploaderFormData"
        :show-file-list="false"
        :before-upload="uploaderHandleBefore"
        :on-success="uploaderHandleSuccess"
        :disabled="uploaderDisabled"
        v-loading="uploaderLoading"
    >
      <el-button type="primary">{{uploadBtnTitle}}</el-button>
    </el-upload>
    <el-dialog
        title="进度提示"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        width="30%">
      <el-progress :percentage="importPercent"></el-progress>
    </el-dialog>
  </div>
</template>

<script>
  import {REQUEST_URL, ACCESS_TOKEN_PREFIX} from '@/utils/config'
  import userInfo from '@/utils/userInfo'
  import network from '../utils/network'

  export default {
    name: 'LeoExcelUploader',
    props: {
      uploadBtnTitle: {
        type: String,
        default: '上传',
      },
      requestUploadRoute: {
        type: String,
        required: true,
      },
      requestImportToExcelTableRoute: {
        type: String,
        required: true,
      },
      requestImportExcelTableToDataRoute: {
        type: String,
        required: true,
      },
      importRowCount: {
        required: true,
      },
      uploaderSuccessCanChange: {
        type: Boolean,
        default: true,
      },
      otherParams: {
        type: Object,
        default: {},
      },
      finishCallbackFunc: {
        type:Function,
        default:null,
      },
      excelOption: {
        type: String,
      },
    },
    data() {
      return {
        uploaderShow: true,
        uploaderLoading: false,
        uploaderFormData: {
          'uploadToken': '',
          'excelOption': this.excelOption,
        },
        uploaderRequestUrl: `${REQUEST_URL}${this.requestUploadRoute}`,
        importRequestUrl: `${REQUEST_URL}${this.requestImportRoute}`,
        uploaderHeaders: {
          'Device-Type': 'pc',
          'Suppress-Response-Code': '1',
          'Authorization': '',
        },
        uploaderDisabled: false,
        successImageUrl: null,
        dialogVisible: false,
        importPercent: 0,
      }
    },
    methods: {
      uploaderHandleBefore() {
        if (!this.importRowCount || this.importRowCount <= 1) {
          this.$message({
            message: '请填写文件总行数，并且总行数大于1',
            type: 'warning'
          })
          return false;
        }
        return network.updateToken().then(accessToken => {
          this.uploaderHeaders.Authorization = ACCESS_TOKEN_PREFIX + accessToken
          return network.getData(`file/token`)
        }).then(response => {
          this.uploaderFormData.uploadToken = response
          this.uploaderLoading = true
        }).catch(() => {
          this.uploaderLoading = true
        })
      },
      uploaderHandleSuccess(response, file) {
        if (response.success) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          // 显示进度框
          this.dialogVisible = true
          this.importPercent = 0
          // 导入excel
          this.importToExcelTable(response.data.excelImportId, 1, 1000)

          if (!this.uploaderSuccessCanChange) {
            this.uploaderShow = false
            this.uploaderDisabled = true
            this.uploaderLoading = false
          }
          this.$emit('on-success', response.data)
        } else {
          this.$message({
            message: response.data.message,
            type: 'warning'
          })
          this.uploaderLoading = false
        }
      },
      importToExcelTable(excelImportId, startRow = 0, limit = 1000) {
        let _this = this
        let importRowCount = Number.parseInt(_this.importRowCount)
        let postParams = {
          excelImportId: excelImportId,
          rowCount: importRowCount,
          startRow: startRow,
          limit: limit > importRowCount ? importRowCount : limit,
        }
        for (let key in _this.otherParams ) {
          postParams[key] = _this.otherParams[key]
        }

        network.postData(_this.requestImportToExcelTableRoute, postParams).then(response => {
          if (!response.finish) {
            // 完成一次的进度占50%的多少
            let percent = parseInt(startRow / importRowCount * 50)
            if (_this.importPercent + percent >= 50) {
              _this.importPercent = 50
            } else {
              if (_this.importPercent + percent >= 100) {
                _this.importPercent = 100
              } else {
                _this.importPercent += percent
              }
            }
            _this.importToExcelTable(excelImportId, startRow + limit, limit)
          } else {
            _this.importPercent = 50
            _this.importExcelTableToData(excelImportId, 0, 2)
          }
        }).catch(() => {
          _this.importPercent = 0
          _this.dialogVisible = false
          _this.uploaderLoading = false
        })
      },
      importExcelTableToData(excelImportId, offset = 0, limit = 100) {
        let _this = this
        let postParams = {
          excelImportId: excelImportId,
          offset: offset,
          limit: limit,
        }
        for (let key in this.otherParams ) {
          postParams[key] = this.otherParams[key]
        }
        network.postData(_this.requestImportExcelTableToDataRoute, postParams).then(response => {
          if (!response.finish) {
            let percent = Number.parseInt(offset / _this.importRowCount * 50)
            if (_this.importPercent + percent >= 100) {
              _this.importPercent = 100
            } else {
              _this.importPercent += percent
            }
            _this.importExcelTableToData(excelImportId, offset + limit, limit)
          } else {
            _this.importPercent = 100
            _this.dialogVisible = false
            _this.uploaderLoading = false
            if( _this.finishCallbackFunc !== null ) {
              _this.finishCallbackFunc()
            }
            _this.$message({
              message: '导入完成',
              type: 'success'
            })
          }
        }).catch(() => {
          _this.importPercent = 0
          _this.dialogVisible = false
          _this.uploaderLoading = false
        })
      }
    }
  }
</script>

<style scoped>

</style>
