<template>
  <div ref="myImportProgress" :class="[ 'importProgress',position,'el-notification']" :style="{'top':top,'z-index':zIndex}" v-if="visible">
    <div class="icon">
        <img class="img" src="@/assets/rar.png" alt="">
    </div>
    <div class="line"></div>
    <div class="message">
        <div class="name">{{ file.name }}</div>
        <div class="progress">
            <div class="progress_title">{{recordMessage}}</div>
            <div>
                <el-progress style="width:100%" :percentage="percentage"></el-progress>
            </div>
        </div>
        <div class="btn">
            <template v-if="state==1">
                <el-button size="mini" v-if="!isStop" @click="stop">暂停</el-button>
                <el-button size="mini" v-else @click="keepOn">继续</el-button>
            </template>
            
            <el-button v-if="state<3" size="mini" @click="cancel">取消</el-button>
        </div>
    </div>
    <div class="close">
        <i class="el-icon-close" @click="del"></i>
    </div>
  </div>
</template>

<script>
import { getFileMD5, createFileChunk } from "@/utils/file";
import router from '@/router'
export default {
  components: {},
  props: {},
  data() {
    return {
        duration:0,
        form:null,
        position:'right',
        visible:false,
        percentage:0,
        top:'16px',
        zIndex:'2200',
        md5:null,
        isStop:false,
        file:{},
        recordMessage:'',
        len:0,
        currentIndex:0,
        resumePromise:null,
        state:0
    };
  },
  watch: {
    visible(val){
        if(val){
            this.getStyle()
            this.init()
            if(this.duration != 0){
                this.timedShutdown()
            }
        }
    },
    percentage(val){
        if(val == 100){
            this.del()
        }
    },
  },
  computed: {},
  created() {},
  mounted() {},
  beforeDestroy() {  
    this.isPaused = true;  
    this.resumePromise = null;  
  }, 
  methods: {
    init(){
        console.log(this.form)
        if(!this.form){
            return
        }
        if(!this.form.file){
            return
        }
        this.file = {
            name:this.form.file.name
        }
       this.upload()
        
    },
    upload(){
         // this.record('等待读取文件MD5')
        this.recordMessage = '等待读取文件MD5'
        let fileChunks = createFileChunk(this.form.file)
        // console.log(fileChunks)
        // return
        // fileChunks = [1,2,3,4,5]
        this.len = fileChunks.length + 3
          getFileMD5(this.form.file, async (md5) => {
            this.record('文件MD5：' + md5)
            var time = new Date().getTime()
            const start = await this.$api.startChunks({md5: md5, fileName: this.form.file.name,sourceId:this.$constants.sourceId,time:time})
            if(!start.data){
                return
            }
            this.state = 1
            await this.uploadChunks(fileChunks, md5, 0,time)
            this.state = 2
            // this.record('等待服务器合并分片')
            this.recordMessage = '等待服务器合并分片'
            const response = await this.$api.mergeChunks({ md5: md5, fileName: this.form.file.name,time:time })
            if(response.code != 200){
                return
            }
            this.state = 3
            this.record('分片合并完成，等待更新专利说明书')
            let params = {
                fileGuid: response.data[0],
                pdfType: this.form.type,
                remark: this.form.remark
            }
            await this.$api.batchUploadPatentInstruction(params)
            this.record('开始更新专利说明书')
            this.getConfirm()
            this.del()
            
          })
    },
      //弹窗
      getConfirm() {
            const h = this.$createElement;
            this.$msgbox({
                title: "提示",
                message: h("p", null, [
                    h("span", null, "任务正在导入，查看任务进度请前往"),
                    h(
                    "span",
                    {
                        class: "MessageBoxClass",
                        on: {
                        click: () => {
                            this.toTaskList();
                            // 通过close关闭消息弹窗，this.$confirm就是this.$confirm.close(false)，其他同理
                            this.$msgbox.close(false);
                        },
                        },
                    },
                    "任务清单"
                    ),
                ]),
                type: "warning",
                showConfirmButton: false,
            }).then((action) => {});
        },
        //跳转到任务清单
        toTaskList() {
            // 传专题库id是查到当前专题库的导入任务，不传是查看所有导入任务
            router.push({
                path: "/taskList",
                // query:{
                //     importToId:this.form.importToId
                // }
            });
        },
    record(status, ) {
      this.recordMessage = status
      this.currentIndex += 1
      this.percentage =parseInt( this.currentIndex / this.len * 100)
    },
    async uploadChunks(fileChunks, md5, index=0,time) {
        for(var i = index;i<fileChunks.length;i++){
           
            await new Promise((resolve,reject) => {
                let formData = new FormData()
                formData.append('file', fileChunks[i].file)
                formData.append('md5', md5)
                formData.append('index', i)
                formData.append('time', time)
                formData.append('sourceId', this.$constants.sourceId)
                // setTimeout(()=>{
                //     const status = `将分片上传至服务器(${i + 1}/${fileChunks.length})`
                //     this.record(status)
                //     resolve()
                    
                // },5000)
                this.$api.uploadChunks(formData).then(async (response) => {
                    const status = `将分片上传至服务器(${i + 1}/${fileChunks.length})`
                    this.record(status)
                    resolve()
                })
            });  
            if (this.isStop) {  
                // 如果循环被暂停，则等待直到被恢复  
                await new Promise(resolve => {  
                    this.resumePromise  = resolve; 
                });  
            }

        }
        return
      return new Promise((resolve, reject) => {
        if (index >= fileChunks.length) {
          resolve(true)
        }
        let formData = new FormData()
        formData.append('file', fileChunks[index].file)
        formData.append('md5', md5)
        formData.append('index', index)
        this.$api.uploadChunks(formData).then(async (response) => {
            const status = `将分片上传至服务器(${index + 1}/${fileChunks.length})`
            this.record(status)
          resolve(this.uploadChunks(fileChunks, md5, index + 1))
        })
      })
    },
    getStyle(){
        var doms = document.getElementsByClassName('el-notification')
        var len = doms.length
        if(len == 0){
            this.top = '16px'
            this.zIndex = '2200'
        }else{
            var dom = doms[len - 1]
            var top = dom.offsetTop
            var height = dom.offsetHeight
            var zIndex = dom.style.zIndex
            this.top = top + height + 16 + 'px'
            this.zIndex = Number(zIndex) + 10
        }
    },
    del(){
        var current = this.$refs.myImportProgress
        var offsetTop = current.offsetTop
        var height =  current.offsetHeight
        this.visible = false
        var doms = document.getElementsByClassName('el-notification')
        for(var i = 0;i<doms.length;i++){
            if(doms[i].offsetTop <= offsetTop){
                continue
            }
            doms[i].style.top = doms[i].offsetTop - height - 16 + 'px'
            doms[i].style.zIndex = Number(doms[i].style.zIndex) - 10
        }
        this.state = 0
    },
    //暂停
    stop(){
        this.isStop = true
    },
    //继续
    keepOn(){
        this.isStop = false
        this.resumePromise()
        this.resumePromise = null;
    },
    //取消
    cancel(){
        this.stop()
        //调用取消接口
        if(this.state>1){

        }
        this.del()
    },
    timedShutdown(){
        setTimeout(function() {
            this.del()
        }, this.duration);
    },
  },
};
</script>
<style lang="scss" scoped>
    .importProgress{
        padding: 0 10px;
        width: 330px;
        height: auto;
        border-radius: 8px;
        border: 1px solid #ebeef5;
        position: fixed;
        background-color: #fff;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
        transition: opacity .3s,transform .3s,left .3s,right .3s,top .4s,bottom .3s;
        overflow: hidden;
        display: flex;
        // align-items: center;
        .close{
            padding-top: 10px;
            width: 20px;
            height: 100%;
        }
        .icon{
            padding-top: 10px;
            width: 50px;
            .img{
                width: 30px;
                height: 30px;
                margin-left: 10px;
            }
        }
        .line{
            width: 1px;
            height: auto;
            background: #d8d8d8;
        }
        .message{
            width: 260px;
            padding: 10px ;
            .name{
                font-size: 14px;
                width: 100%;
                overflow: hidden;
                white-space: nowrap;
                text-overflow:ellipsis;
            }
            .progress_title{
                color: rgb(123 126 130);
                font-size: 12px;
                margin-top: 6px;
                min-height: 0;
                overflow: hidden;
                text-decoration: none;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }
        .btn{
            text-align: left;
        }
    }
    .right{
        right: 16px;
    }
</style>