<!-- @desc:照片墙组件  @auth:张潇木  @time:2022-6-21 18:54 -->
<template>
  <div>
    <div class="upload-box">
      <Upload
        :disabled="disabled"
        :headers="{Authorization: 'Bearer ' + $store.state.user.token}"
        v-if="!onlyShow"
        ref="upload"
        :show-upload-list="false"
        :on-success="uploadSuccess"
        :on-format-error="handleFormatError"
        :on-exceeded-size="handleMaxSize"
        :accept="accept||$config.uploadFileConfig.acceptPicType+','+$config.uploadFileConfig.acceptVideoType"
        :format="$config.uploadFileConfig.format"
        style="display: inline-block;width:120px;"
        type="drag"
        :max-size="$config.uploadFileConfig.maxSize"
        :multiple="multiple"
        :action="uploadUrl"
        :data="{'folder':folderData}"
        :before-upload="beforeUpload">
        <div style="width: 120px;height:120px;line-height: 120px;">
          <Icon type="ios-camera" size="32"/>
        </div>
      </Upload>
      <!--    <span style="display:block;margin-bottom: 10px;color:#a9a9a9;">-->
      <!--        文件大小不得超过100k。建议图片宽高比为1:1-->
      <!--    </span>-->
      <!--照片墙部分-->
      <div v-for="(item,index) in uploadListInner" :key="index"
           style="margin-left:5px;margin-bottom: 5px;display: inline-block;vertical-align: top;">
        <div @dragover="allowDropIn($event,index)" @drop="drop(index)"
             @dragstart="handleDragStart(index)"
             @dragover.prevent="handleDragOver(index)"
             @dragenter="handleDragEnter(index)"
             @dragend="handleDragEnd(index)" draggable="true"
             style="z-index:0; overflow:hidden;border:1px dashed #d3d3d3;border-radius: 3px; width: 120px;height:120px;position: relative;"
             :style="{backgroundImage: 'url('+(item.type == 'img'?(item.fullPath ? item.fullPath:$config.imgUrl+item.path):item.vPath)+')',backgroundSize:'contain',backgroundPosition:'center',backgroundRepeat:'no-repeat'}">
          <div class="hover-zz" style="text-align:center;height:120px;width:120px;position: absolute;">
            <Icon class="hover-zz-icon" v-if="item.type=='video'" @click="openModal(item)"
                  style="cursor: pointer;line-height: 120px;font-size: 40px;opacity: 0;color: #fff;"
                  type="md-arrow-dropright-circle"/>
            <Icon class="hover-zz-icon" v-if="item.type=='img'" @click="openModal(item)"
                  style="cursor: pointer;line-height: 120px;font-size: 40px;opacity: 0;color: #fff;" type="md-eye"/>
            <div v-if="item.type!='img' && item.type!='video'" class="other">
              <Icon type="md-document" size="30"/>
              <a @click="openOther(item)">{{ item.name }}</a>
            </div>
          </div>
          <div v-if="!onlyShow"
               style="width: 240px;height:50px;background-color: #00000096;transform: rotate(45deg);margin-top: -20px;"></div>
          <Icon type="md-close" @click="delItem(index,1)" v-if="!onlyShow"
                style="font-size:20px;color: white;position: absolute;right: 0;top:0;cursor: pointer;"/>
        </div>
      </div>
    </div>
    <Modal
      v-model="modalFlag"
      @on-ok="fullScreenShow"
      okText="下载"
      cancelText="关闭"
      :title="currentItem.name">
      <video :src="currentItem.fullPath ? currentItem.fullPath : $config.imgUrl+currentItem.path" autoplay controls
             v-if="currentItem.type=='video'"
             style="width: 480px;height:320px;"></video>
      <img :src="currentItem.fullPath ? currentItem.fullPath : $config.imgUrl+currentItem.path"
           v-if="currentItem.type=='img'" style="width: 480px;"/>
    </Modal>
  </div>
</template>

<script>
import store from "@/store";

export default {
  name: 'DkPicWall',
  model: {
    prop: "uploadListOuter", // 这个字段，是指父组件设置 v-model 时，将变量值传给子组件的 msg
    event: "update" // 这个字段，是指父组件监听 parent-event 事件
  },
  props: {
    uploadListOuter: {//数据源
      type: Array,
      default: () => [],
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否上传多个
    multiple: {
      type: Boolean,
      default: true
    },
    // 文件夹路径 表名+字段名
    folder: {
      type: String
    },
    // 只展示图片 不上传 不修改
    onlyShow: {
      type: Boolean,
      default: false
    },
    //可传入的文件类型
    accept: {
      type: String
    },
    //支持的文件类型
    format: {
      type: Array
    },
    // 表名
    table: {
      type: String
    }
  },
  data() {
    let self = this
    return {
      uploadUrl: self.$config.uploadUrl,
      videoSrc: '',
      currentItem: {},
      modalFlag: false,
      goodsCode: null,
      dragIndex: null,
      uploadListInner: this.uploadListOuter,
      // 配置存放的文件夹 公司code - 表名 - 年月 -- 日
      folderData: self.$store.state.user.cpCode + '/' + self.table + '/' + new Date().toYearMonth2() + '/' + new Date().toDay(),
    }
  },
  created() {
    // this.uploadListInner=this.uploadListOuter;
    if (store.state.user.svcCode) {
      this.uploadUrl = this.uploadUrl.replace('mdm-server', 'mdm-server' + '-' + store.state.user.svcCode.replace('_', '-'))
    }
  },
  // computed:{
  //   folderData()
  // },
  watch: {
    // 监听uploadList变化
    uploadListInner(n, o) {
      console.log('tt',this.uploadListInner)
      this.$emit("update", this.uploadListInner);

    },
    uploadListOuter(n, o) {
      this.uploadListInner = this.uploadListOuter;
    }
  },
  methods: {
    /**
     * @desc   : 上传文件之前的钩子
     * @author : 张潇木
     * @date   : 2022-5-25 19:20
     */
    beforeUpload(file) {

      if (!this.accept && !(this.$config.uploadFileConfig.acceptPicType + ',' + this.$config.uploadFileConfig.acceptVideoType).split(',').includes(file.type)) {
        this.$Message.warning('图片格式不在允许的范围内')
        return false
      }
      if (file.size / 1024 > this.$config.uploadFileConfig.maxSize) {
        this.$Message.warning(`文件大小超过了${this.$config.uploadFileConfig.maxSize}KB`)
        return false
      }
      console.log('ttt')
    },
    /**
     * @desc   : 上传普通图片成功事件
     * @author : 张潇木
     * @date   : 2022-5-25 20:01
     */
    uploadSuccess(res, file) {
      if (res.code == 200 && res.data) {
        console.log('res.data',res.data)
        if (!this.multiple) {
          // this.uploadListInner = [
          //   {
          //     'type': this.getFileType(res.data),
          //     'path': res.data,
          //     'name': file.name,
          //     'createTime': new Date().format()
          //   }
          // ]
          this.uploadListInner = [...res.data]
        } else {
          if (!this.uploadListInner) {
            this.uploadListInner = []
          }
          this.uploadListInner.push(res.data)
          // this.uploadListInner.push(
          //   {
          //     'type': this.getFileType(res.data),
          //     'path': res.data,
          //     'name': file.name,
          //     'createTime': new Date().format()
          //   }
          // )
        }
      } else {
        this.$Message.warning(res.message)
      }
    },

    /**
     * @desc   : 识别文件类型
     * @author : 张潇木
     * @date   : 2022-6-18 16:28
     */
    getFileType(fileName) {
      let arr = fileName.split('.')
      let fileType = arr[arr.length - 1].toLowerCase()

      if (fileType === 'jpg' || fileType === 'jepg' || fileType === 'png') {
        return 'img'
      }
      if (fileType === 'mp4' || fileType === 'avi' || fileType === 'mov') {
        return 'video'
      }
      if (fileType === 'xls' || fileType === 'xlsx') {
        return 'excel'
      }
      if (fileType === 'pdf') {
        return 'pdf'
      }
      return ''
    },
    fullScreenShow() {
      // window.location.href = this.currentItem.path
      window.open(this.currentItem.fullPath ? this.currentItem.fullPath : this.$config.imgUrl + this.currentItem.path)
    },
    openModal(item) {

      this.currentItem = item
      this.modalFlag = true
    },
    /**
     * @desc   : 打开其他类型文件
     * @author : 洪旭东
     * @date   : 2022-07-21 19:59
     */
    openOther(item) {
      window.open(this.$config.imgUrl + item.path)
    },
    getVideoBase64(list, returnList) {
      return new Promise(resolve => {
        let tlist = [...list]
        if (tlist.length <= 0) {
          returnList.forEach(item => {
            this[`uploadList${item.position}`].push(item)
          })
        }
        let rlist = returnList
        if (tlist.length > 0) {

          if (tlist[0].type === 2) {
            // this.openModal(item)
            // this.modalFlag = false
            const width = 120
            const height = 120
// 创建一个video节点
            const video = document.createElement('video')
//               const video = document.getElementById('video-haha')
            video.setAttribute('src', this.$config.imgUrl + tlist[0].path)
            video.setAttribute('crossOrigin', 'anonymous')
            // video.preload = 'preload'
            video.crossOrigin = 'anonymous'
            video.width = width
            video.height = height
            video.autoplay = 'autoplay'
            video.currentTime = 1 // 第一帧
//创建canvas对象
            const canvas = document.createElement('canvas')
            canvas.crossOrigin = 'Anonymous'
            canvas.width = width
            canvas.height = height
            // 等待video获取到第一帧后
            video.oncanplay = () => {
              // 利用canvas对象方法绘图
              canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
              // 转换成base64形式
              tlist[0].vPath = canvas.toDataURL('image/jpeg') // 这个就是图片的base64
              rlist.push(tlist[0])
              tlist.splice(0, 1)
              this.getVideoBase64(tlist, rlist)
            }
          } else {
            rlist.push(tlist[0])
            tlist.splice(0, 1)
            this.getVideoBase64(tlist, rlist)
          }
        }
      })
    },
    allowDropIn(e, i) {
      // console.log('this.dragIndex',i)
    },
    drop(index) {
      let arr = this.uploadListInner;
      [arr[this.dragIndex], arr[index]] = [arr[index], arr[this.dragIndex]];//es6解构赋值，交换元素位置
      this.uploadListInner = [...arr];
    },
    handleDragStart(e) {
      this.dragIndex = e
      // console.log('handleDragStart',e)
    },
    handleDragOver(e) {
      // console.log('handleDragOver',e)
    },
    handleDragEnter(e) {
      // console.log('handleDragEnter',e)
    },
    handleDragEnd(e) {
      // console.log('handleDragEnd',e)
    },


    delItem(index, type) {
      this.uploadListInner.splice(index, 1)
    },
    //校验是否是图片
    handleFormatError(file) {
      console.log('fff',file)
      this.$Message.warning('文件' + file.name + '格式不符合要求！')
    },
    //校验图片大小
    handleMaxSize(file) {
      this.$Message.warning('文件' + file.name + '太大，建议上传100k以内的图片、视频')
    },
    //校验图片大小

    handleBeforeUpload(position) {
      return () => {
        return new Promise((resolve, reject) => {
          // reject()

        })
      }
    },

    compare(key) {
      return function (a, b) {
        let value1 = a[key]
        let value2 = b[key]
        return value2 - value1
      }
    },
  },
}
</script>

<style scoped>
.upload-box {
  width: 100%;
  overflow: auto;
  display: inline;
}

.hover-zz:hover {
  background-color: #00000096;
}

.hover-zz:hover > .hover-zz-icon:nth-child(n) {
  opacity: 1 !important;
}

.modal-pic-div:hover {
  background-color: #00000096;
}

.modal-pic-div:hover > .modal-pic-div-icon:nth-child(n) {
  opacity: 1 !important;
}

.other {
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 40px 0;
  overflow: hidden;
  height: 100%
}
</style>
