<template>
    <div class="webuploader-container">
        <div :id="'uploader'+upId" class="uploader">
                <el-row class="upname">
                    <el-col :span="12"> {{name}}  </el-col>                   
                    <el-col :span="6"> <div :id="'picker'+upId" >选择文件</div>  </el-col>
                </el-row>

                <el-row class="upname2" v-for="(fileObj,key) in files" :key="key">
                     <el-col :span="5">  {{fileObj.name}} </el-col>
                    <el-col :span="10"><el-progress :percentage="fileObj.percentage"></el-progress></el-col>
                    <el-col :span="5">{{fileObj.msg}}</el-col>
                    <el-col :span="4" class="anniu"><el-button size="mini" type="danger" @click="fileDel(fileObj.id)" icon="el-icon-delete" circle></el-button></el-col>
                </el-row>
        </div>
    </div>

</template>
<script>
import $ from 'jquery' ;
import WebUploader from 'webuploader';
import store from "@/store";
import { request } from "@/utils/request";
import { ElMessage } from '@/utils/message.js'
import { log } from 'three';
let Message = new ElMessage()
export default {
    data(){
        return {
            uploader:undefined,
            fileName:undefined,
            md5:"1212",
            files:[]
        }
    },
    mounted(){
        this.initWebUploader();
    },
    props:{//传入参数
        projectId: String,
        solverType: String,
        accept:String,
        upId:String,
        name:String,
    },
    methods:{
        initWebUploader(){
            var v_this=this;
            this.uploader=WebUploader.create({
                // swf文件路径
                swf: './Uploader.swf',
                // 文件接收服务端。
                server: process.env.VUE_APP_BASE_API+'/TransServlet',
                //文件上传请求的参数表，每次发送都会发送此对象中的参数。
                formData: {
                
                },
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: {
                        id:'#picker'+v_this.upId,
                        multiple:true
                      },
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                  resize: false,
                // 开起分片上传。
                chunked: true,
                chunkSize: 1024 * 1024,
                threads :4,

            })
            // 当有文件被添加进队列的时候
            this.uploader.on( 'fileQueued', file=> {
                v_this.fileName=file.name;
                const fax=v_this.fileName.split(".")[1];
                if(v_this.accept.indexOf(fax)<0){//判断上传支持文件类型
                    v_this.uploader.reset();
                    Message.error("只支持" +v_this.accept+"格式文件!");
                    return;
                }
                v_this.uploader.md5File(file)
                .progress(percentage=> {//显示加密进度
                     console.log('Percentage:', percentage);
                     })
                .then(md5 =>{ // 完成
                     v_this.md5=md5;
             });
                if(v_this.files.length>0){
                    v_this.uploader.removeFile(v_this.files[0].id);
                    v_this.files=[];
                }
              
                v_this.files.push({
                    id:file.id,
                    name:file.name,
                    msg:"等待上传...",
                    percentage:0
                })
               this.uploader.upload();
            });
            
            /**文件发送前
             *  object {Object}
                data {Object}默认的上传参数，可以扩展此对象来控制上传参数。
                headers {Object}可以扩展此对象来控制上传头部
             */
            this.uploader.on('uploadBeforeSend', (file,data,headers)=> {
               data.chunk=file.chunk;
               data.chunks=file.chunks;
               data.pid=v_this.projectId;
               data.solverType=v_this.solverType;
               data.md5=v_this.md5;
               data.fileName=v_this.fileName;
               data.uploadFlag=2;//1 普通 2覆盖 3续传
               data.channelNo ='service';
               data.clientToken=store.getters.token;
               data.transCode='A00113';
               data.userId=store.getters.userId;
               headers.Content='multipart';
               headers.Type='form-data';
            })
           // 文件上传过程中创建进度条实时显示。
            this.uploader.on( 'uploadProgress', ( file, percentage ) =>{
                let prage= Math.floor(percentage*100);
                // v_this.$emit('childFn',{name:v_this.name,percentage:prage})
                v_this.files.forEach(fileObj=>{
                    if(fileObj.id=file.id)
                    fileObj.msg='上传中';
                    fileObj.percentage=prage;
                })
            });
            this.uploader.on( 'uploadSuccess', ( file ,response) =>{
                 v_this.files.forEach(fileObj=>{
                    if(fileObj.id=file.id)
                    fileObj.msg='已上传'
                })
                let params = {
                            transCode: "A00117",
                            uid: v_this.$route
                          
                            };
                  
                request(params)
                    .then((res) => {
                    let rows= res.rows;
                    console.log(rows)
                    rows.forEach(row=>{
                        self.logs += "\n" + row.log;
                    })
                })
                .catch((err) => {});
            });
            /**
             * 当某个文件上传到服务端响应后，会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为false, 则此文件将派送server类型的uploadError事件。
             * object {Object}
                ret {Object}服务端的返回数据，json格式，如果服务端不是json格式，从ret._raw中取数据，自行解析
             */
            this.uploader.on('uploadAccept',(object,res)=>{
               if(res.returnCode=="000000000"){
                   if(res.code=="3"){
                       return true;
                   }else{
                       v_this.uploader.stop(true);//失败暂停当前上传的文件
                       return false;
                   }
               }else{
                   Message.error(res.returnMsg);
                   return false;
               }
            });
            this.uploader.on( 'uploadError', ( file ,reason)=> {
                $( '#'+file.id ).text(file.name+'上传出错');
            });

            this.uploader.on('uploadComplete', file => {
                // $( '#'+file.id ).find('.progress').fadeOut();
            });
            
        },
        uploaderClear(){
             this.uploader.reset();
             this.percentage=0;
             this.files=[];
            //  this.$emit('childFn',{name:v_this.name,percentage:v_this.percentage})
        },
        fileDel(fileId){
            this.files=this.files.filter(fileObj=>{
                if( fileObj.id == fileId){
                    this.uploader.removeFile(fileId);
                }
               return  fileObj.id != fileId
            })
        },
        
    },
    watch:{//数据监听

    },
}

</script>
<style>
.webuploader-container {
	position: relative;
}
.webuploader-element-invisible {
	position: absolute !important;
	clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px,1px,1px,1px);
}
.anniu{
        margin-top: -13px;
}
.webuploader-pick {
	position: relative;
	display: inline-block;
	cursor: pointer;
    padding: 1px 2px;
    font-size: 12px;
	color: #606266;
	text-align: center;
	border-radius: 3px;
	overflow: hidden;
}
.webuploader-pick-hover {
	background: #00a2d4;
}

.webuploader-pick-disable {
	opacity: 0.6;
	pointer-events:none;
}
.uploader{
    display: flex;
}
.upname{
      flex: 0 0 30%;
}
.upname2{
      flex: 0 0 70%;
}
</style>