<template>
  <Modal v-model="showUploadModal"
         :mask-closable="false"
         :closable="false"
         :title="title"
         :value="value" width="520"
         v-draggable="options">
    <Steps style="margin-bottom: 20px" :current="current" :status="stepStatus">
      <Step title="上传文件"></Step>
      <Step title="导入数据"></Step>
      <Step title="完成"></Step>
    </Steps>
    <Card dis-hover :bordered="false" v-show="stepUpload" style="height: 320px">
      <Row>
        <i-col :span="24">
          <span>一、请按照数据模板的格式准备要导入的数据。</span>
        </i-col>
        <i-col :span="24">
          <div style="margin-left: 30px">
            <p style="margin-top: 10px"><a :href="tempUrl" :download="tempName">下载文件模板</a></p>
            <Poptip trigger="click" :title="mattersTitle" :content="mattersContent" word-wrap width="380px"
                    placement="bottom-start">
              <p style="margin-top: 5px"><a href="#">查看注意事项>></a></p>
            </Poptip>
          </div>
        </i-col>
      </Row>
      <Row style="margin-top: 20px">
        <i-col :span="24">
          <span>二、请选择导入方式：</span>
        </i-col>
        <i-col :span="24">
          <div style="margin-left: 30px;margin-top: 10px">
            <Select v-model="uploadParams.method" style="width: 200px">
              <Option v-for="(item,index) in importTypeList" :key="index" :value="item.value">{{item.name}}</Option>
            </Select>
          </div>
        </i-col>
      </Row>
      <Row style="margin-top: 20px">
        <i-col :span="24">
          <span>三、请选择需要导入的文件：</span>
        </i-col>
        <i-col :span="24">
          <div style="margin-left: 30px;margin-top: 10px">
            <Upload ref="upload" :action="myImportUrl"
                    style="text-align: center;display: inline-block;"
                    :show-upload-list="false"
                    :max-size="maxSize"
                    :disabled="disabled"
                    :accept="fileType"
                    :data="uploadParams"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    :on-error="uploadError">
              <p>
                <Button icon="ios-cloud-upload-outline" :disabled="disabled" type="primary" style="width: 200px">
                  选择导入文件
                </Button>
              </p>
              <p style="text-align: left">{{ importFileName }}</p>
            </Upload>
          </div>
        </i-col>
      </Row>
    </Card>
    <Card dis-hover :bordered="false" v-show="stepImport" style="height: 320px">
      <Row>
        <i-col :span="24">
          <Progress :percent="percent" :stroke-width="30" text-inside></Progress>
        </i-col>
        <i-col :span="24">
          <p style="margin-top: 10px">{{importMsg}}</p>
        </i-col>
      </Row>
      <Row v-show="prompt">
        <i-col :span="24">
          <p style="margin-top: 50px">提示：</p>
          <p style="margin-top: 5px">1、如果导入时间较长，您可以关闭此页面、进行其他操作。</p>
          <p style="margin-top: 5px">2、数据导入结束后，将自动发送结果通知给您。</p>
        </i-col>
      </Row>
      <Row v-show="errMsg">
        <i-col :span="24">
          <p style="margin-top: 50px">下载错误报告，查看失败原因：</p>
          <p style="margin-top: 5px"><a href="#" @click="downErrorInfo">error_report.xlsx</a></p>
        </i-col>
      </Row>
    </Card>
    <!--<Card dis-hover :bordered="false" v-show="stepFinish" style="height: 320px">

    </Card>-->
    <template #footer>
    <div>
      <Button size="large" v-if="showCancelBtn" @click="cancel">取 消</Button>
      <Button size="large" v-if="showCloseBtn" @click="cancel">关 闭</Button>
      <!--<Button type="primary" v-if="showImportBtn" size="large" :loading="loading" @click="importFile">
        <span v-if="!loading">开始导入</span>
        <span v-else>导入中...</span>
      </Button>-->
      <Button type="primary" v-if="showImportBtn" size="large">导入中...</Button>
    </div>
    </template>
  </Modal>
</template>

<script>

  let _this
  import { importExcel, exportToExcel } from './excel'
  import {getToken, TOKEN_KEY} from "../bc-libs/token-util";

  export default {
    name: 'bcImport',
    props: {
      show: Boolean,
      value: Object,
      title: { type: String, default: '导入数据' },
      type: { type: String, default: 'front' },//导入方式：前端导入(front)、后端导入(backstage)
      //resultList:Array,//前端导入返回结果
      tempUrl: String,
      tempName: String,
      uploadUrl: String,
      importUrl: String,
      mattersTitle: { type: String, default: '注意事项' }, //注意事项标题
      mattersContent: { type: String, default: '' }, //注意事项内容
      maxSize: { type: Number, default: 2048 },  //
      disabled: { type: Boolean, default: false },
      fileType: { type: String, default: '.xls,.xlsx' },
      params: { type: Object, default: null },
      noticeTitle: { type: String, default: '导入结果' },
      importTypeList:{
        type:Array,
        default:()=>{
          return [
          {name:'新数据导入',value:'1'},
          {name:'覆盖导入',value:'2'}
          ]
        }
      }
    },
    data () {
      return {
        myImportUrl: '',
        showUploadModal: false,
        current: 0,
        stepStatus: 'process',
        stepUpload: true,
        stepImport: false,
        stepFinish: false,
        showCloseBtn: false,
        showCancelBtn: true,
        showImportBtn: false,
        loading: false,
        options: {
          trigger: '.ivu-modal-header',
          body: '.ivu-modal',
          recover: true
        },
        uploadParams: {
          method: '1'
        },
        rules: {
          /*areaId: [
            {required: true, message: '开通区域不能为空!', trigger: 'change' },
          ]*/
        },
        importFileName: '',
        percent: 10,
        importMsg: ' 数据正在导入中...',
        prompt: true,
        errMsg: false,
        file: null,
        fileBase: null,
        resultList: [],//前端导入结果
        resultMap: {},//后台导入结果
        success: 0,
        fail: 0,
        failInfo: [],
      }
    }, methods: {
      cancel () {
        this.showUploadModal = false
        this.$emit('update:show', false)
      },
      importFile () {
        if (this.importFileName == '') {
          this.$Message.warning('请选择导入文件!')
          return false
        }
        this.current = 1
        this.stepUpload = false
        this.stepImport = true
        this.showCancelBtn = false
        this.showCloseBtn = true
        this.loading = true

        for (this.percent = 0; this.percent < 9; this.percent++)
          setTimeout(() => {
            if (this.percent < 100) {
              for (this.percent = 0; this.percent < 22; this.percent++);
            }

          }, 1000)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 39; this.percent++);
          }
        }, 3000)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 68; this.percent++);
          }
        }, 4500)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 91; this.percent++);
          }
        }, 6000)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 99; this.percent++);
          }
        }, 10000)
        if (this.type == 'front') {//前端导入
          //this.uploadParams.dataList = this.resultList
          this.uploadParams.file = this.file

        } else {//后端导入
          //this.params.dataMap = this.resultMap
          this.uploadParams.file = this.file
        }
        this.$post(this.myImportUrl, { file: this.file }).then(res => {
          if (res.result) {
            this.fail = res.result.fail
            this.success = res.result.success
            if (this.fail > 0) {
              this.errMsg = true
              let failInfo = res.result.failInfo
              failInfo.forEach(item => {
                this.failInfo.push({
                  '错误信息': item
                })
              })
            }
            this.showImportBtn = false
            this.percent = 100
            this.current = 2
            this.prompt = false
            if (this.success){
              this.importMsg = '导入完成，其中 ' + this.success + ' 条导入成功，' + this.fail + ' 条导入失败。'
            }else {
              this.importMsg = '导入完成'
            }
            if (!this.showUploadModal) {
              this.renderFunc()
            }
          } else {
            this.uploadError(res)
          }
          this.$emit('getImportResult', res)
        }).catch(err => {
          this.$Message.error('导入失败！')
          console.log(err)
          this.uploadError(err)
        })
      },
      beforeUpload (file) {
        if (file.size > this.maxSize * 1000) {
          this.$Message.error('文件大小超出限制!')
          return false
        }
        let suffix = file.name
        suffix = suffix.substring(suffix.indexOf('.'), suffix.length)
        if (this.fileType.indexOf(suffix) < 0) {
          this.$Message.error('错误的文件类型!')
          return false
        }
        this.importFileName = file.name
        this.file = file

        this.current = 1
        this.stepUpload = false
        this.stepImport = true
        this.showImportBtn = true
        this.showCancelBtn = false
        this.showCloseBtn = true
        this.loading = true
        if (this.type == 'front') {//前端导入
          let result = importExcel(this.file, 0)
          result.then(val => {
            this.resultList = val
            this.uploadParams.dataList = this.resultList
            this.$emit('getUploadResult', this.resultList)
          })
        }

        for (this.percent = 0; this.percent < 9; this.percent++)
          setTimeout(() => {
            if (this.percent < 100) {
              for (this.percent = 0; this.percent < 22; this.percent++);
            }
          }, 1000)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 39; this.percent++);
          }
        }, 3000)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 68; this.percent++);
          }
        }, 4500)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 91; this.percent++);
          }
        }, 6000)
        setTimeout(() => {
          if (this.percent < 100) {
            for (this.percent = 0; this.percent < 99; this.percent++);
          }
        }, 10000)
        //return false;
      },
      uploadSuccess (response, file, fileList) {
        if (response.result) {
          this.$emit('reloadData')
          this.fail = response.result.fail
          this.success = response.result.success
          if (this.fail > 0) {
            this.errMsg = true
            let failInfo = response.result.failInfo
            failInfo.forEach(item => {
              this.failInfo.push({
                '错误信息': item
              })
            })
          }
          this.showImportBtn = false
          this.percent = 100
          this.current = 2
          this.prompt = false
          if (this.success){
            this.importMsg = '导入完成，其中 ' + this.success + ' 条导入成功，' + this.fail + ' 条导入失败。'
          }else {
            this.importMsg = '导入完成'
          }
          if (!this.showUploadModal) {
            this.renderFunc()
          }
        }else{
          this.percent = 100
          this.prompt = false
          this.$Modal.error({
            title: '导入失败',
            content: response.error && response.error.message?response.error.message:response,
          })
        }
        this.$emit('getImportResult', response)
      },
      uploadError (response, file, fileList) {
        this.percent = 100
        this.prompt = false
        this.$Modal.error({
          title: '导入失败',
          content: response.error && response.error.message?response.error.message:response,
        })
        return false
      },
      renderFunc () {
        this.$Notice.info({
          title: this.noticeTitle,
          duration: 0,
          desc: '',
          render: h => {
            return h('span', [
              '导入完成，其中 ' + this.success + ' 条导入成功，' + this.fail + ' 条导入失败。下载错误报告，查看失败原因：',
              h('a', {
                on: {
                  click: () => {
                    this.downErrorInfo()
                  }
                }
              }, 'error_report.xlsx'),
            ])
          }
        })
      },
      downErrorInfo () {
        exportToExcel('error_report', this.failInfo, '错误信息')
        this.failInfo=[]
      }
    }, mounted: function () {
      _this = this
    }, watch: {
      show: {
        immediate: true,
        handler: function () {
          this.showUploadModal = this.show
          if (this.show) {
            this.uploadParams = this.params
            this.uploadParams.method = '1'
          }
          this.current = 0
          this.showImportBtn = false
          this.showCancelBtn = true
          this.showCloseBtn = false
          this.stepUpload = true
          this.stepImport = false
          this.loading = false
          this.percent = 0
          this.importMsg = ' 数据正在导入中...'
          this.errMsg = false
          this.prompt = true
        },
      },
      importUrl: {
        immediate: true,
        handler: function () {
          //初始化导入地址
          if (!this.importUrl) return
          this.myImportUrl = this.importUrl
          if (this.myImportUrl.indexOf('?') > 0) {
            this.myImportUrl += '&'
          } else {
            this.myImportUrl += '?'
          }
          this.myImportUrl += TOKEN_KEY + '=' + getToken()
        }
      },
    }
  }
</script>

<style scoped>

</style>
