<template>
    <div class="img-group-con">
      <!-- fileErr -->
      <div :key="'img-box-' + index" ref="img-box" :class="['img-box',item.fileErr == true?'fileErr':'' ]" v-for="(item, index) in imgList">
        <div class="img-box-close" v-if="showDeleBtn && showDelete" @click="() => { deleteEve(item, index) }"><a-icon
            type="delete" /></div>
        <img  :src="item.dataUrl || item.url" class="img" @click="showImg(item)"
          v-if="!errMsg.showDescription && !showItemIcon(item.suffix || getFileSuffix(item.url))">
        <a-empty v-if="errMsg.showDescription" :description="errMsg.description" style="position: absolute;"/>
        <a-result v-if="item.status" :status="item.status" :title="item.statusTitle" style="padding: 6px 32px;"></a-result>
        <!-- 当不是图片时显示相应的图标 -->
        <span :class="['iconfont icon-size img-box-icon', getItemIcon(item.suffix || getFileSuffix(item.url))]"
          v-if="!item.status && showItemIcon(item.suffix || getFileSuffix(item.url))" @click="showImg(item)"></span>
  
        <div v-if="!errMsg.showDescription && item.title && item.title.length > 0" ref="img-title" :title="item.title" class="title img-title"
          @click="showImg(item)">{{ item.title }}</div>
      </div>
      <div v-if="imgList.length == 0" class="img-box-not-data">暂无数据</div>
      <PreviewShow :vhas="vhas" :config="config" :url="url" :name="name" :suffix="suffix" :event="psEvent" :isShowWatermark="isShowWatermark_"></PreviewShow>
    </div>
  </template>
  
  <script>
  import { addWatermark } from './../utils/addWatermark'
  import PreviewShow from './../PreviewShow'
  import {getCaptionFileName, getFileOldName, isBlobUrl, getFileExtension} from './../utils/util'
  import IS from './../utils/is'
  // import { addPDFWaterMark } from './../utils/WaterMark2PDF'
  const getFileSuffix = (filePath) => {
    if (!filePath) {
      return ''
    }
    var startIndex = filePath.lastIndexOf(".");
    if (startIndex != -1)
      return filePath.substring(startIndex + 1, filePath.length).toLowerCase();
    else return "";
  }
  const fileIcon = {
    ofd:'icon-icon-zhuanpiao', // icon-icon-zhuanpiao  icon-OFD
    pdf: 'icon-pdf',
    ppt: 'icon-ppt',
    pptx: 'icon-ppt',
    doc: 'icon-word',
    docx: 'icon-word',
    xlsx: 'icon-excel',
    xls: 'icon-excel',
    zip: 'icon-zip',
    rar: 'icon-zip',
    txt: 'icon-txt',
    jpg: 'icon-tupian',
    png: 'icon-tupian',
    jpeg: 'icon-tupian',
    'wz': 'icon-weizhigeshi',
  }
  
  function convert(url) {
    url = url.replace(/(.*\/)*([^.]+).*/ig, "$2");
    return url;
  }

  function checkImage(url,index,self,bk) {
    return new Promise((resolve) => {
      const suffix = getFileSuffix(url)
      console.log('checkImage 0======>',suffix,url);
      const hzList = ['jpg','png','jpeg']
      if(hzList.indexOf(suffix)<0){
        bk&&bk(true, index,self)
        resolve({res:true, index,self})
        return false
      }
      console.log('checkImage 1======>',suffix,url);
      fetch(url)
        .then(response => {
          if (!response.ok) {
            throw new Error('图片加载失败');
            // bk&&bk(false, index,self)
          }
          // bk&&bk(true, index,self)
          return response.blob();
        })
        .then(blob => {
          const img = new Image();
          img.src = URL.createObjectURL(blob);
          img.onerror = function() {
            // console.log('图片加载失败');
            // img.src = 'path/to/placeholder.jpg';
            bk&&bk(false, index,self)
            resolve({res:false, index,self})
          };
          img.onload=function(){
            bk&&bk(true, index,self)
            resolve({res:true, index,self})
          }
          // document.body.appendChild(img);
        })
        .catch(error => {
          // console.log(error.message);
          // const img = new Image();
          // img.src = 'path/to/placeholder.jpg';
          // document.body.appendChild(img);
          bk&&bk(false, index,self)
          resolve({res:false, index,self})
        });
  });
    
}

  // document.getElementsByClassName('img-box')[0].clientWidth
  export default {
    name: 'PImgGroup',
    components:{PreviewShow},
    props: {
      value: { type: Array,required: true, },
      vhas:{type:String},
      // 判断是否显示深处按钮
      showDeleBtn: { type: Boolean, default: () => { return false } },
      // 删除事件
      deleteEvent: { type: Function },

      showHelp:{type:Boolean, default: () => { return false }}
    },
    data() {
      return {
        errMsg:{
          showDescription:false,
          description:'',
        },
        imgList: [
          // {url:'http://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/qsb/idCard/1667219411398_%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E9%9D%A2(1).jpg', title:'说明：营业执照'},
          // {url:'http://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/qsb/idCard/1667219411398_%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E9%9D%A2(1).jpg', title:'说明：身份证'},
          // {url:'http://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/qsb/idCard/1667219411398_%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E9%9D%A2(1).jpg', title:''},
        ],
        titleList: [],
        config: {
          visible: false,
          title: '',
        },
        url: '',
        suffix: '',
        name:'',
        isShowWatermark_:true,
        showDelete: true,
        conW:198
      }
    },
    watch: {
      deleteEvent: {
        async handler(val) {
          if (Object.prototype.toString.call(val) === '[object Function]') {
            this.showDelete = true
          } else {
            this.showDelete = false
          }
        },
        deep: true,
        immediate: true
      },
      value: {
        async handler(val) {
          const self = this
          // console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2',val);
          if (IS.isArray(val)) {
            const tempArr = []
            const titleArr = []
            // this.imgList = tempArr
            // const pdf = ['pdf', 'PDF']
            for (let index = 0; index < val.length; index++) {
              const item = val[index];
              // console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&77',item,Object.prototype.toString.call(item));
              if (IS.isString(item)) {
                let isErrPush = 0
                try {
                  const res = await addWatermark(item,this,this.$watermarkConfig,null,()=>{
                    const suffix_ = getFileSuffix(item)
                    const tempTitle =getFileOldName(getCaptionFileName(item))  //convert(res.url) +'.'+res.suffix
                    tempArr.push({ url: item, dataUrl: '', title: tempTitle, suffix: suffix_,oldUrl:item, fileErr:true})
                    titleArr.push(this.showTitle(tempTitle))
                    this.$message.error(`第${(index+1)}文件可能添加水印失败或已损坏`,5);
                    isErrPush = 1
                  })
                  console.log('###############1###################',res);
                  if(isErrPush !=1){
                    const tempTitle =getFileOldName(getCaptionFileName(item))  //convert(res.url) +'.'+res.suffix
                    tempArr.push({ url: res.url, dataUrl: '', title: tempTitle, suffix: res.suffix ,oldUrl:item, fileErr:false})
                    titleArr.push(this.showTitle(tempTitle))
                  }
                } catch (error) {
                  const suffix_ = getFileSuffix(item)
                  const tempTitle =getFileOldName(getCaptionFileName(item))  //convert(res.url) +'.'+res.suffix
                  tempArr.push({ url: item, dataUrl: '', title: tempTitle, suffix: suffix_,oldUrl:item, fileErr:true})
                  titleArr.push(this.showTitle(tempTitle))
                  this.$message.error(`第${(index+1)}文件可能添加水印失败或已损坏`,5);
                }
              }
              if (IS.isObject(item)) {
                if (item.status) {
                  tempArr.push({ ...item , fileErr:false})
                } else {
                  const {isShowWatermark,title,name,suffix} = item
                  let tempTitle_ = title || name ||  getFileOldName(getCaptionFileName(item.url))
                  const suffix_ = suffix || getFileExtension(item.url) 
                  if(isShowWatermark===false){
                    // const tempTitle =getFileOldName(getCaptionFileName(item.url))
                    tempArr.push({ url: item.url, dataUrl: '', title: tempTitle_||'', suffix: suffix_|| '', isShowWatermark,oldUrl:item.url, fileErr:false })
                    titleArr.push(this.showTitle(tempTitle_||''))
                    // console.log('222222222222222222',tempTitle);
                  }else {
                    let isErrPush = 0
                    try {
                      const res = await addWatermark(item.url,this,this.$watermarkConfig,null,()=>{
                        tempArr.push({ url: item.url, dataUrl: '', title: tempTitle_ || '', suffix: suffix_||'' ,isShowWatermark,oldUrl:item.url, fileErr:true})
                        titleArr.push(this.showTitle(tempTitle_ || ''))
                        this.$message.error(`第${(index+1)}文件可能添加水印失败或已损坏`,5);
                        isErrPush = 1
                      })
                      console.log('###############2###################',res, isErrPush);
                      if(isErrPush!=1){
                        // const tempTitle =getFileOldName(getCaptionFileName(item.url))
                        tempArr.push({ url: res.url, dataUrl: '', title: tempTitle_ || res.name, suffix: suffix_||res.suffix||'' ,isShowWatermark,oldUrl:item.url, fileErr:false})
                        titleArr.push(this.showTitle(tempTitle_ || res.name))
                      }
                    } catch (error) {
                      tempArr.push({ url: item.url, dataUrl: '', title: tempTitle_ || '', suffix: suffix_||'' ,isShowWatermark,oldUrl:item.url, fileErr:true})
                      titleArr.push(this.showTitle(tempTitle_ || ''))
                      this.$message.error(`第${(index+1)}文件可能添加水印失败或已损坏`,5);
                    }
                  }
                  // console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&77',isShowWatermark,item,tempArr,isShowWatermark===false);
                }
              }
            }
  
            this.titleList = titleArr
            this.imgList = tempArr
          }
  
        },
        deep: true,
        immediate: true
      },
    },
    mounted(){
      if(this.$isShowHelp == true &&this.showHelp === true){
        console.log(`
        组件名称：
            PImgGroup
        使用方法：
            <p-ImgGroup :value="[]" ></p-ImgGroup>
            <p-ImgGroup v-model="[]" ></p-ImgGroup>
        props参数说明：
            props: {
              // 此参数必填  用于显示的数据集合  
              //   例如： [{url:'',title:''}] 
                          或 ['url1','url1'] 
                          或 [{ status:'success' | 'error' | 'info' | 'warning'| '404' | '403' | '500',statusTitle:''}]  表示可以显示指定的结果状态
                          或 [{url:'',title:'', isShowWatermark: true}]  isShowWatermark 可以设置是否显示水印 默认为true 显示水印(下载时带水印)   false 表示不显示水印(下载时不带水印)
              value: { type: Array },
              // 此参数可选 判断是否显示深处按钮
              showDeleBtn: { type: Boolean, default: () => { return false } },
              // 此参数可选 删除事件
              deleteEvent: { type: Function },
              // 此参数可选 用于控制文件下载时是否有水印的权限标识
              vhas:{type:String},
            }
        `);
      }
    },
    updated(){
      const conW = this.$refs['img-box']&& this.$refs['img-box'][0]&& this.$refs['img-box'][0].clientWidth
      localStorage.setItem('conW',conW)
    },
    methods: {
      showTitle(title) {
        if(!title){
          return ''
        }
        // console.log('showTitle===>',title);
        const w_ = localStorage.getItem('conW')
        if(w_ && w_!='undefined'){
          this.conW = ~~w_
        }
        // const conW =document.getElementsByClassName('img-box')[0].clientWidth
        let tempTitle = title
        const conW = this.conW  // this.$refs['img-box'][0].clientWidth || 198
        const titleInfoArr = title.split('.')
        const titleInfoArrLength = titleInfoArr.length
        const  names = [...titleInfoArr]
        names.pop()
        let newName = names.join('.')
        const nameLength = newName.length * 12
        const hzLength =  titleInfoArr[titleInfoArrLength-1].length * 6
        const baseLength = conW - hzLength - 30
        
        const subEndNum = baseLength / 12
        if (baseLength <= nameLength) {
          newName = names.join('.').substring(0, subEndNum)+'...'
        }
        tempTitle = newName + "." + titleInfoArr[titleInfoArrLength-1]
        // console.log('showTitle*******************', conW, nameLength, baseLength, newName,subEndNum,titleInfoArr);
        return tempTitle
      },
      deleteEve(item, index) {
        this.deleteEvent && this.deleteEvent(item, index)
      },
      getItemIcon(fileSuffix) {
        return fileIcon[fileSuffix] || fileIcon['wz']
      },
      showItemIcon(fileSuffix) {
        const notShowList = ['jpg', 'png', 'jpeg']
        if (notShowList.indexOf(fileSuffix) >= 0) {
          return false
        }
        return true
      },
      getFileSuffix: getFileSuffix,
      showImg(imgInfo) {
        // console.log('@@@@@@@@@@@@@@@',imgInfo);
        // if(imgInfo.status){
        //   // 当此值【imgInfo.status】存在时不允许预览
        //   this.$message.info('当前已完成电子签约');
        // }else{
        // }
        this.config.title = imgInfo.title || ''
        this.url = imgInfo.oldUrl || imgInfo.url || ''
        this.suffix = imgInfo.suffix
        this.name = imgInfo.title || ''
        this.isShowWatermark_ = imgInfo.isShowWatermark
        this.config.visible = true
      },
      psEvent(type) {
        if (type == 'close') {
          this.config.visible = false
          this.url = ''
        }
      }
    }
  }
  </script>
  
  <style lang="less">
  .img-group-con {
    width: 100%;
    height: 240px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    // padding: 5px 10px;
    padding: 5px 0;
    overflow: auto;
  
    .img-box {
      width: 250px;
      height: 85%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-direction: column;
      border: 1px dashed #022ea04d;
      border-radius: 4px;
      padding: 5px;
      margin: 5px 5px;
      position: relative;
      overflow: auto;
      &.fileErr{
        border: 3px dashed red !important;
      }
      .img-box-close {
        cursor: pointer;
        position: absolute;
        right: 3px;
        top: 0px;
        z-index: 10;
      }
  
      .img {
        flex: 1;
        width: auto;
        height: calc(100% - 40px);
        cursor: pointer;
      }
  
      .img-box-icon {
        height: calc(100% - 25px);
        font-size: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
      }
      .icon-excel{
        color: rgb(16,124,65);
      }
      .icon-zip{
  
        color: rgb(255,210,87);
      }
      .icon-pdf, .icon-ppt{
        color: rgb(222,0,17);
      }
  
      .title {
        width: 100%;
        height: 25px;
        line-height: 16px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #2a5699;
        overflow: hidden;
        // white-space: nowrap;
        // text-overflow: ellipsis;
        cursor: pointer;
        position: absolute;
        bottom: 0px;
        left: 0px;
        z-index: 5;
        background-color: #e5eaf987;
        // background-color: #e5eaf987;
        padding: 5px 5px;
        text-decoration: underline;
        text-align: center;
      }
    }
  
    .img-box-not-data {
      width: 250px;
      height: 90%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      border: 1px dashed #ccc;
      border-radius: 4px;
      padding: 5px;
      margin: 5px 10px;
      color: rgba(0, 0, 0, 0.25);
    }
  }
  
  .icon-size {
    color: #2a5699; // #f5222d;
    font-size: 100px;
  }
  </style>
  