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

                <el-row v-for="(fileObj,key) in files" :key="key" class="disflex">
                    <el-col :span="6">{{fileObj.name}} </el-col>
                    <el-col :span="8"><el-progress :percentage="fileObj.percentage"></el-progress></el-col>
                    <el-col :span="5">{{fileObj.msg}}</el-col>
                    <el-col :span="5"><el-button size="mini" type="danger" @click="fileDel(fileObj.id)" icon="el-icon-delete" circle></el-button></el-col>
                </el-row>
                <!-- <el-button size="mini" @click="uploader.upload()">开始上传</el-button> -->
        </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';
import { Message, MessageBox } from "element-ui";
import { connect } from 'echarts/lib/echarts';
// let Message = new ElMessage()
export default {
    data(){
        return {
            uploader:undefined,
            fileName:undefined,
            md5:"1212",
            files:[],
           nmllist:[],// 批量上传的数组
            gridFileId:'',
            boundaryFileId:'',
             uuid:'',
             nmlid:'',
             upstate:'1', //状态
           hcfdBoundarys:[],
        }
    },
    updated(){
      //  this.initWebUploader(); 
    },
    mounted(){
  this.initWebUploader();
    },
    props:{//传入参数
        projectId: String,
        solverType: String,
        accept:String,
        upId:String,
        name:String,
        namelist:Array,//文件名的集合
    },
         created(){
     this.getUUID()
   this.uuid= this.getUUID()
 
      
},
    methods:{
   
         getUUID() {
          return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          
              var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
              return v.toString(16);
          })
          
     },
     //HCFDugrid绑定
        bindugrid(bfid){
                let params = {
                            transCode: "D00001",
                            pid: this.projectId,
                            gridFileType:this.solverType,
                            gridFileId:bfid,
                            };
                      
                request(params)
                    .then((res) => {
                     console.log("绑定成功")
                    
                })
                .catch((err) => {});
            },
    //HCFDmapbc绑定
    bindmapbc(mapbcFileId){
        let solverConfigId= sessionStorage.getItem("solverConfigid");
         let params = {
                            transCode: "D00002",
                            solverConfigId: solverConfigId,
                            mapbcFileId:mapbcFileId,
                            };
                      
                request(params)
                    .then((res) => {
                     console.log("绑定成功")
                    this.mapbc();
                    
                })
                .catch((err) => {});
    },
    //调用c0003
    mapbc(){
        let paramsdata=JSON.parse(sessionStorage.getItem("params"))
         request(paramsdata)
          .then((res) => { 
               let data = JSON.parse(res.parameterObj);
              this.hcfdBoundarys= data.hcfdBoundarys
            this.$emit("changedesc",JSON.stringify(this.hcfdBoundarys));

          })
          .catch((err) => {
          })
        
    },
    
        initWebUploader(){
            this.files=[];
            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: 2 * 1024 * 1024,
                threads :4,

            })
            // 当有文件被添加进队列的时候
            this.uploader.on( 'fileQueued', file=> {
                v_this.fileName=file.name;
            //     console.log(  v_this.fileName);
              if(this.upId=='1'||this.upId=='2'||this.upId=='3'){
                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();
              }
              else{
                 
                if(v_this.namelist.includes(v_this.fileName)){
                     v_this.uploader.reset();
                        Message.error("文件名已存在请修改文件名才能上传");
                   return;
                 
                }
                      this.namelist.push(v_this.fileName);
                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.bfid=v_this.uuid;
               data.fileName=v_this.fileName;
            //    data.pid=v_this.projectId;
            //    data.solverType=v_this.solverType;
            //    data.md5=v_this.md5;
            //    data.uploadFlag=2;//1 普通 2覆盖 3续传
               data.channelNo ='service';
               data.clientToken=store.getters.token;
               data.transCode='B00028';
               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.upstate='2';
              sessionStorage.setItem('upstate', this.upstate)
            });
            this.uploader.on( 'uploadSuccess', ( file ,response) =>{
             console.log(response);
                       if(file.ext=='ugrid'){
                        this.gridFileId=response.bfid;
                          let params = {
                            transCode: "B00029",
                            bfid: response.bfid,
                            };
                            request(params)
                                .then((res) => {
                                    sessionStorage.removeItem('upstate');
                                    console.log(res)
                                v_this.files.forEach((fileObj) => {
                                if ((fileObj.id = file.id)){
                                    fileObj.msg = "已上传";
                                    v_this.$emit('upoK')
                                }
                                v_this.bindugrid(response.bfid);
                                });
                                
                            })
                            .catch((err) => {});
                     
                }else if(file.ext=='mapbc'){
                              let params = {
                            transCode: "B00029",
                            bfid: response.bfid,
                            };
                            request(params)
                                .then((res) => {
                                    sessionStorage.removeItem('upstate');
                                    console.log(res)
                                v_this.files.forEach((fileObj) => {
                                if ((fileObj.id = file.id)){
                                    fileObj.msg = "已上传";
                                    v_this.$emit('upoK')
                                }
                                v_this.bindmapbc(response.bfid);
                                });
                                
                            })
                            .catch((err) => {});
                        
                        }else{
                       
                        }
              
            });
            //
            /**
             * 当某个文件上传到服务端响应后，会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为false, 则此文件将派送server类型的uploadError事件。
             * object {Object}
                ret {Object}服务端的返回数据，json格式，如果服务端不是json格式，从ret._raw中取数据，自行解析
             */
            this.uploader.on('uploadAccept',(object,res)=>{
               if(res.returnCode=="000000000"){
                   return true;
               }else{
                   Message.error(res.returnMsg);
                   return false;
               }
            });
            this.uploader.on( 'uploadError', ( file ,reason)=> {
                  sessionStorage.removeItem('upstate');
                $( '#'+file.id ).text(file.name+'上传出错');
                 this.getUUID();
                    this.uuid= this.getUUID();
            });

            this.uploader.on('uploadComplete', file => {
                // $( '#'+file.id ).find('.progress').fadeOut();
            });
            
        },
        uploaderClear(){
             this.uploader.reset();
             this.percentage=0;
             this.files=[];
        },
        fileDel(fileId){
        //     if(sessionStorage.getItem('upstate')=='2'){
        //          Message({
        //   type: "error",
        //   message: "上传中不能删除",
        // });
        //     }else{
            if(this.upId=='1'||this.upId=='2'||this.upId=='3'){
                  this.getUUID();
                    this.uuid= this.getUUID();
                        sessionStorage.removeItem('upstate');
            this.files=this.files.filter(fileObj=>{
                if( fileObj.id == fileId){
                       console.log(fileObj);
                    this.uploader.removeFile(fileId);  
           
                }
               return  fileObj.id != fileId
              
            })
            }else{
                 sessionStorage.removeItem('upstate');
            this.files=this.files.filter(fileObj=>{
                if( fileObj.id == fileId){
                       console.log(fileObj);
                    this.uploader.removeFile(fileId);  
                    this.namelist.splice(this.namelist.findIndex(item => item === fileObj.name), 1)
           
                }
               return  fileObj.id != fileId
              
            })

            }
           
            // }
        
                
  
        },
       
        
    },
    datalish(){
        
    }

   
}

</script>
<style>
.webuploader-container {
	position: relative;
}
.webuploader-pick{
    color: #fff !important;
}
.webuploader-element-invisible {
	position: absolute !important;
	clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px,1px,1px,1px);
}
.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;
}
.disflex{
    display: flex;
    align-items: center;
}
.text_color  .webuploader-pick{
   color: #d5d5d5;
}
.el-progress__text{
 color: #d5d5d5 !important;
}
</style>