<template>
    <div>
      <v-header :title="title" :isShowPrevPage="true"></v-header>
      <div class="content">
        <div v-show="step === 1">
          <ul class="explain_wrapper">
            <li class="item">1. <a href="javascript:;" @click="handleDownloadTemplate">下载Excel表模板 </a></li>
            <li class="item" v-for="(item,index) in importExplainArr " :key="index">{{ `${index + 2}. ${item}`}}</li>
            <li class="item">{{ importExplainArr.length + 2}}.
              <el-upload
                action="#"
                ref="uploadFile"
                class="upload-btn"
                :limit="1"
                :multiple="false"
                :auto-upload="false"
                :on-change="changeFile"
                :show-file-list="false"
                accept=".xlsx,.xls,.xsl">
                <a href="javascript:;">上传Excel表</a>
              </el-upload>（提示：只能上传1个Excel表）</li>
              <li v-if="fileInfo.file !== ''"  class="item file-name">
                <i class="iconfont" >&#xe613;</i>{{ fileInfo.fileName }} <a href="javascript:;"  class="delete-btn" @click="handleDeleteClick">删除</a>
              </li>
          </ul>
          <div class="upload-btn_box">
            <el-button size="small" type="primary" @click="uploadFile">上传</el-button>
          </div>
        </div>
        <el-progress :percentage="progress" v-show="step === 2" ></el-progress>
        <div v-show="step === 3">
          <div class="error-list">
            <div style="font-size: 16px; font-weight: 600;margin-bottom: 8px;color: #666;">共检测到{{ errorInfo.total }}条记录，成功导入{{ errorInfo.successCount }}条记录。</div>
            <div class="error-item" style="margin-bottom: 8px;font-size: 15px;">失败记录{{ errorInfo.failCount }}条：</div>
            <template v-if="Object.keys(errorInfo).length && errorInfo.errorInfoListArr && errorInfo.errorInfoListArr.length">
              <div class="error-item" v-for="(item,index) in errorInfo.errorInfoListArr " :key="`error_${index}`">{{ `${index+1}. ${item}` }}</div>
            </template>
          </div>
          <div class="upload-btn_box">
            <el-button size="small" type="primary" @click="handleSubmitSuccClick">完成</el-button>
          </div>
        </div>
      </div>
    </div>
</template>
<script>
import VHeader from '@/common/header/VHeader'
import { isEmpty } from '@/assets/utils/util.js'
export default {
    name: 'Import',
    data () {
        return {
            title: '标题',
            code: Number(this.$route.params.code), // 模块code
            // params: JSON.parse(decodeURIComponent(this.$route.query.params)),
            importExplainArr: [], //  导入说明信息
            downloadTemplateUrl: '', // 模板下载url
            templateUrlType: 0, //  0-请求下载  1-直接下载
            importExcelUrl: '', // 导入url
            fileList: [],
            fileInfo: {
                fileName: '',
                file: ''
            },
            errorInfo: {
                total: 0,
                successCount: 0,
                failCount: 0,
                errorInfoListArr: []
            },
            progress: 20,
            step: 1, // 1-上传前 2-上传中 3-上传成功后
            customColors: [
                {color: '#f56c6c', percentage: 20},
                {color: '#e6a23c', percentage: 40},
                {color: '#5cb87a', percentage: 60},
                {color: '#1989fa', percentage: 80},
                {color: '#6f7ad3', percentage: 100}
            ]
        }
    },
    components: {
        VHeader
    },
    computed: {
        params () {
            let params = this.$route.query.params
            return isEmpty(params) ? {} : JSON.parse(decodeURIComponent(params))
        }
    },
    methods: {
    // 获取导入模板信息
        getImportTemplateInfo () {
            let { code } = this
            this.$api.commonApi.getPlugInfo({ code }).then(res => {
                const data = res.data
                if (data.Status) {
                    const info = data.Data
                    this.importExplainArr = info.remark ? info.remark.split(',') : []
                    this.title = info.title
                    this.downloadTemplateUrl = info.template_url
                    this.importExcelUrl = info.server_url
                    this.templateUrlType = info.template_url_type
                }
            }).catch(err => {
                console.log(err)
            })
        },
        // 下载模板
        handleDownloadTemplate () {
            let { downloadTemplateUrl: url, params: data, templateUrlType } = this
            if (isEmpty(url)) {
                this.$message.warning('参数错误')
                return
            }
            if (templateUrlType === 0) {
                this.$api.commonApi.exportTemplate({ url, data }).then(res => {
                    let data = res.data
                    if (data.Status === undefined) {
                        const fileName = res.headers['content-disposition'] ? decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1]) : '_.xlsx'
                        const blob = new Blob([data])
                        if (!!window.ActiveXObject || 'ActiveXObject' in window) {
                            window.navigator.msSaveOrOpenBlob(blob, fileName)
                        } else {
                            const a = document.createElement('a')
                            a.download = fileName
                            a.href = URL.createObjectURL(blob)
                            document.body.appendChild(a)
                            a.click()
                            document.body.removeChild(a)
                        }
                    } else {
                        if (!data.Status) {
                            this.$message.error(data.ResponseError.LongMessage)
                        }
                    }
                }).catch(err => {
                    console.log(err)
                })
            } else {
                window.location.href = url
            }
        },
        changeFile (file, fileList) {
            this.fileInfo.fileName = file.name
            this.fileInfo.file = file.raw
            this.$refs.uploadFile.clearFiles()
        },
        handleDeleteClick () {
            this.fileInfo.file = ''
            this.fileInfo.fileName = ''
        },
        uploadFile (e) {
            if (this.fileInfo.file === '') {
                this.$message({
                    message: '请先添加文件',
                    type: 'warning'
                })
                return
            }
            let { params, code, importExcelUrl: url } = this
            if (isEmpty(url)) {
                this.$message.warning('参数错误')
                return
            }
            this.step = 2
            params.upload_code = code
            let formData = new FormData()
            Object.keys(params).forEach(function (key) {
                formData.append(key, params[key])
            })
            formData.append('file', this.fileInfo.file)
            this.$api.commonApi.importExcelTable({
                url,
                data: formData
            }, (e) => {
                this.progress = e.loaded / e.total * 100
            }).then(res => {
                let data = res.data
                if (data.Status) {
                    this.step = 3
                    this.errorInfo.total = data.Data.total
                    this.errorInfo.successCount = data.Data.success_count
                    this.errorInfo.failCount = data.Data.error_count
                    this.errorInfo.errorInfoListArr = data.Data.err_message
                } else {
                    this.step = 1
                    this.$message.error(data.ResponseError.LongMessage)
                }
                this.progress = 0
                this.$refs.uploadFile.clearFiles()
                // this.fileList = [];
            }).catch(err => {
                console.log(err)
            })
        },
        handleSubmitSuccClick () {
            this.$router.go(-1)
        }
    },
    created () {
        this.getImportTemplateInfo()
    },
    mounted () {}
}
</script>
<style lang="less" scoped>
.content {
  padding: 25px 40px;
  margin: 15px auto;
  border: 1px solid #ddd;
  width: 60%;
  box-shadow: 2px 2px 3px #e9ecea;
  border-radius: 5px;
  font-size: 14px;
  min-height: 255px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  .explain_wrapper {
    .item {
      color: #666;
      margin-bottom: 8px;
      font-size: 15px;
    }
    .file-name {
      display: flex;
      align-items: center;
      text-indent: 1em;
      i {
        margin-right: 10px;
      }
      .delete-btn {
        color: red;
        margin-left: 10px
      }
    }
  }
  .upload-btn {
    display: inline-block;
  }
  /deep/.el-progress {
    .el-progress-bar {
      padding-right: 55px;
      .el-progress-bar__outer {
        height: 18px !important;
      }
    }
    .el-progress__text {
      font-size: 16px !important;
    }
  }
  .upload-btn_box{
    text-align: center;
    margin-top: 30px;
    .el-button {
      width: 100px;
    }
  }
  .error-list {
    margin: 20px 0 20px;
    max-height: 235px;
    overflow-y: scroll;
    .error-item {
      color: red;
      margin-bottom: 5px;
    }
  }
}
</style>
