<template>
    <div>
              <ul class="el-upload-list el-upload-list--picture-card" v-if="uploadType=='image'">
                  <li class="el-upload-list__item is-ready"
                  v-for="(item,index) in imgsJson['supMainImgs']" :key="index"
                  >
                    <div style="width:100%;height:100%;">
                      <img class="el-upload-list__item-thumbnail" 
                      :src="item.url+'?x-oss-process=image/format,png'" alt="">
                    </div>
                    <!-- 操作按钮 -->
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete">
                        <i class="el-icon-zoom-in" @click="handlePictureCardPreview(item)"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete">
                        <i class="el-icon-delete" @click="handleRemove(item,'supMainImgs',index)"></i>
                      </span>
                    </span>
                  </li>
                  <li class="el-upload-list__item is-ready" 
                  :style="{'border':'none','display':imgsJson['supMainImgs'].length>=hideLength?'none':''}">
                  <el-upload
                      ref="supMainImgs"
                      accept="image/jpeg,image/jpg,image/png"
                      :action="uploadData.host|| '' "
                      :data="uploadData"
                      list-type="picture-card"
                      :on-preview="handlePictureCardPreview"
                      :on-success="(response, file, fileList) => handleSuccess(response, file, fileList)"
                      :on-error="onError"
                      :on-remove="(file) => handleRemove(file,'supMainImgs')" 
                      :show-file-list="false"
                      :on-exceed="(files,fileList) => handleExceed(files,fileList,'supMainImgs')"
                      :before-upload="(file) => beforeUpload(file,'supMainImgs',)"
                      :file-list="imgsJson.supMainImgs"
                      :before-remove="handleError"
                      :multiple="isMultiple"
                      :limit="limitNum"
                      >
                      <!--  支持多张上传 multiple -->
                      <!--  :show-file-list="false" 隐藏状态. 
                      :file-list="imgsJson.supMainImgs" 必须加上这一行，才能在删除图片后，再次上传图片，有超出提示-->
                      
                      <i class="el-icon-plus"></i>

                    </el-upload>
              </li>
          </ul>
          <div class="videoshow0" v-else>
              <el-upload
              ref="video"
                accept="video/mp4,audio/mp4"
                class="avatar-uploader video_pro"
                :action="uploadData.host|| '' "
                :data="uploadData"
                :show-file-list="false"
                :on-success="handleSuccess"
                :on-error="onError"
                :before-remove="(file,fileList) => handleError(file,fileList,'supMainImgs')"
                :on-remove="(file) => handleRemove(file,'supMainImgs')"
                :before-upload="(file) => beforeUpload(file,'supMainImgs')">
                
                <template v-if="imgsJson.supMainImgs.length != 0">
                  <div v-for="(item,index) in imgsJson.supMainImgs" :key="index">
                    <video v-if="item.url" :src="item.url" controls="controls">
                      您的浏览器不支持 video 标签。
                    </video>
                  </div>
                </template>


                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="closebtn" v-if="imgsJson.supMainImgs.length>0" @click="handleRemove('','supMainImgs')">
                <i class="el-icon-circle-close"></i>
              </div>
              
               </div>

        <!-- <el-dialog :visible.sync="dialogVisible" :modal="false">
            <img width="100%" :src="dialogImageUrl +'?x-oss-process=image/format,png'" alt="">
        </el-dialog> -->
          <el-image-viewer
              v-if="showViewer"
              :on-close="closeViewer"
              :url-list="ImageViewerUrl"
          />
    </div>
</template>
<script>
import { _uuid, _getOssToken, _supplierId, _deepClone, _deal,_getStorage } from '@/utils/utils'
import FileVerification from "@/utils/FileVerification"
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
    name:'uploadImg',
    components:{
      ElImageViewer
    },
    props:{
      isMultiple:{
        type:Boolean,
        default:false //多张上传
      },
      limitNum:{
        type:Number,
        default:30 //限量上传
      },
      uploadType:{
        type:String,
        default:'image' //image,video
      },
      uploadSize:{
        type:Number,
        default:1024000 //上传文件大小 kb
      },
      uploadWH:{
        type:Array,
        default:()=>{ return []} //图片宽度+高度
      },
      hideLength:{
        type:Number,
        default:1 //多少张图片后隐藏上传按钮
      }
    },
    computed:{
      ImageViewerUrl(){
        let arr =[]
        this.imgsJson.supMainImgs.map(res=>{
          arr.push(res.url)
        })
        return arr
      }
    },
    data(){
        return {
            uploadData: {keys:[],successNum:0,beforeNum:0}, // 临时存放上传文件
            imgsJson:{
                supMainImgs: [],
            },
            dialogImageUrl: '',
            dialogVisible: false,
            showViewer:false
        }
    },
    methods:{
      closeViewer(){ //关闭
          this.showViewer = false
      },
        loadingStart(tx){
            this.loading = this.$loading({
                lock: true,
                text: tx?tx:'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        },
        loadingEnd(type){
            if(type){
                this.$message.error('网络异常,请重新上传试试！')
            }
            this.loading.close()
        },
        // 处理已上传的图片
        pictureFun() {
            let imgsJson = {}
            for(let k in this.imgsJson){
                let o = this.imgsJson[k]
                let arr = []
                if(typeof(o) == 'object' && o  instanceof Array){
                    o.map(r => {
                    arr.push(r.url?r.url:r)
                    })
                    imgsJson[k] = arr.join(',')
                }else{
                    imgsJson[k] = o
                }
            }
            return imgsJson
        },
          onError(err,file,fileList){
        this.loadingEnd(1)
        },
        handleRemove(file, label,idx) {
      
      let fileList = _deepClone(this.imgsJson[label])
      let index = fileList.indexOf(file);

      this.imgsJson[label].splice(idx,1)
      
        const imgResult = this.pictureFun();
        this.$emit('uploadResult',imgResult.supMainImgs)
      },
      handlePictureCardPreview(file) {
        // this.dialogImageUrl = file.url;
        // this.dialogVisible = true;
          this.showViewer =true
      },
    handleExceed(files, fileList,label) {
 
      this.$message.warning(`超出限制文件个数`);

    },
    beforeUploadCheck(file,label){
      let self = this
      const fv = new FileVerification(file);
      let rules;
   
      if(this.uploadWH && this.uploadWH.length){
         if(this.uploadWH.length==1){
          //[00]只传一个默认设置宽度vImgW
            rules = {
              'supMainImgs':{
                vSize:this.uploadSize,
                vImgW:this.uploadWH
              },
            }
         }else{
            rules = {
              'supMainImgs':{
                vSize:this.uploadSize,
                vImgWH:this.uploadWH
              },
            }
         }
      }else{
        rules = {
          'supMainImgs':{
            vSize:this.uploadSize
          },
        }
      }
      async function getResult(rule){
        let res = true
        for(let i in rule){
          let val = rule[i]
          if(['vImgPercentage','vImgWH','vImgW','vImgH'].indexOf(i) != -1){
            let r = await fv[i](val[0],val[1])
            res = r
          }else{
            res = fv[i](val)
          }
          //只要有一个条件不满足就弹出
          if(res && !res.result){
            return res
          }
        }
        return res
      }

      return getResult(rules[label])

    },
    beforeUploadErr(){
        this.uploadData.keys = []
        this.uploadData.successNum = 0
        this.uploadData.beforeNum = 0
    },
    beforeUpload(file,label) {
      this.uploadData.beforeNum += 1
      this.uploadData['label'] = label // 上传位置标识

      // 文件上传
      return new Promise((resolve, reject) => {

        // 校验上传文件属性
        this.beforeUploadCheck(file,label).then(res => {
          if(!res){
            this.$notify.error(
              "请按要求上传文件"
            );
            this.beforeUploadErr()
            reject();
          }else if (typeof(res) == 'object' && !res.result) {
            let err = res.h?res.w + "*" + res.h:res.w
            this.beforeUploadErr()
            if(res.msg){
                this.$notify.error(res.msg);
            }else{
              this.$notify.error(
                "请上传" + err + "像素的图片格式文件"
              );
            }
            reject();
          }else{
            this.loadingStart()

            _getOssToken.call(this, null).then((res) => {
              let fileExt = /\.[^\.]+$/.exec(file.name);
              let uuid = _uuid()
              let uploadData = this.uploadData
              this.uploadData = {...uploadData, ...res};

              this.uploadData.key = 'ROOT/ETao/gl/' + uuid + fileExt;
              this.uploadData.keys.push('ROOT/ETao/gl/' + uuid + fileExt)
              resolve();

            }).catch((err) => {
              reject(err)
            })

          }
        });

      })
    },
    handleError(file, fileList){

    //   console.log('cuowu--',file,fileList);
      // 处理加上校验后删除前一个已上传文件的问题
      return false
    },
     handleSuccess(response, file, fileList, supMainImgsIndex){
      // 文件上传
      let filterSku = v => {
        // 过滤需要修改
        return v.key == this.skuImageKey;
      };
      let { label, host, keys } = this.uploadData
      let successNum = this.uploadData.successNum += 1

      if( successNum == this.uploadData.beforeNum ){
        keys.map(key => {
          if(label === 'mainImg'){
            // sku图
            this.skuList.filter(filterSku)[0].mainImg = host + "/" + key
          }
          else{
            if(label === 'video' || label === 'model3D'){
              this.imgsJson[label] = [{"url":host + "/" + key,"name":host + "/" + key}]
            }else{
              // 多图
              this.imgsJson[label].push({"url":host + "/" + key,"name":host + "/" + key})
            }
          }
        })

        this.uploadData.keys = []
        this.uploadData.successNum = 0
        this.uploadData.beforeNum = 0
        this.loadingEnd()
        const imgResult = this.pictureFun();
        this.$emit('uploadResult',imgResult.supMainImgs)
      }
    },
    }
}
</script>
<style lang="scss" scoped>
 /deep/ .el-upload--text .el-icon-upload {
    font-size: 67px;
    color: #97a8be;
    margin: 40px 0 16px;
    line-height: 50px;
}
 /deep/ .el-upload--text {
    color: #97a8be;
    font-size: 14px;
    text-align: center;
}
 /deep/ .el-upload--text em {
    font-style: normal;
}
   .videoshow0{
    display: inline-flex;
    position: relative;
    .closebtn{
      position: absolute;
      right: -30px;
      top: -10px;
      font-size: 24px;
      cursor: pointer;
      color: #999;
    }
  }
  .video_pro{
  // height:148px;
  // width:222px;
        // border: 1px dashed #d9d9d9;
      border-radius: 6px;
      box-sizing: border-box;
      position: relative;
  // /deep/ .el-upload--text{
  //   width: 100%;
  //   height: 100%;
  // }
 /deep/ .el-upload--text {
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    box-sizing: border-box;
    width: 360px;
    height: 180px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
  .el-icon-plus{
    font-size: 28px;
    line-height:6;
  }
  video{
    max-width: 100%;
    max-height:100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
  }
}
</style>