<template>
  <div class="upload-album-list">
    <ul>
      <li
        v-for="(item, index) in albumList"
        :key="index"
      >
        <div
          class="album-progress-bxo"
          v-if="item.progress !== 100 && !item.key"
        >
          <el-progress
            class="album-progress"
            type="circle"
            :percentage="item.progress"
            :width="width"
          ></el-progress>
        </div>
        <div class="album-list-img-box">
          <span
            v-if="item.cover"
            class="img-tip"
          >封面</span>
          <template v-if="item.url && item.url!==''">

            <el-image
              v-if="urlType(item.url)==='image'"
              class="album-list-img"
              :src="item.url + '?x-oss-process=image/auto-orient,0/resize,m_fill,limit_0,h_154,w_154'"
              :z-index="index"
              :preview-src-list="[item.url]"
            />

            <img
              v-if="urlType(item.url)==='video'"
              class="album-list-img"
              :src="item.url + '?spm=a2c4g.11186623.2.1.yjOb8V&x-oss-process=video/snapshot,t_7000,f_jpg,m_fast'"
            />

            <img
              v-if="urlType(item.url)==='audio'"
              class="album-list-img"
              src="https://chinavisionary-test.oss-cn-beijing.aliyuncs.com/4468ce9bde6f42e2b601dcdc3eff7a16[-]1593686321892[-]WechatIMG155.png?x-oss-process=image/auto-orient,0/resize,m_fill,limit_0,h_154,w_154'"
            />

          </template>
        </div>
        <div
          class="handle-box"
          v-if="!readonly && item.url"
        >
          <div class="handle-btn-box">
            <template v-for="(setItem,setIndex) in setList">
              <span
                v-if="isSet"
                :key="setIndex"
                @click="setItemClick(item, setItem)"
              >{{ setItem.name }}</span>
            </template>
            <span @click="deleteItem(item.key, index)"><i class="el-icon-delete"></i></span>
          </div>
        </div>
      </li>
      <li
        class="null-li"
        v-if="limit>albumList.length&&!readonly"
      >
        <el-upload
          :action="actionUrl"
          :accept="accept"
          :data="albumData"
          :headers="headers"
          :limit="limit"
          :on-exceed="handleExceed"
          :multiple="multiple"
          :on-progress="handleProgress"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="handleBeforeUpload"
          :show-file-list="false"
        >
          <div
            class="add-img-box"
            :style="`width:${width}px;height:${height}px;`"
          >
            <i class="el-icon-plus"></i>
          </div>
        </el-upload>
      </li>

    </ul>
  </div>
</template>
<script>

import { reqDeleteFile, reqDeleteFolderFile, photosList } from './api';

export default {
  name: 'UploadPhotoList',

  props: {

    viewType: {
      type: String,
      default: function () {
        return 'photo'
      }
    },

    itemData: {
      type: Object,
      default: function () {
        return {};
      }
    },

    fileList: {
      type: Array,
      default: function () {
        return [];
      }
    },

    width: {
      type: Number,
      default: 100
    },

    height: {
      type: Number,
      default: 100
    },

    // 只读
    readonly: {
      type: Boolean,
      default: false
    },

    // 图片文件夹key
    folderKey: {
      type: String,
      default: function () {
        return '';
      }
    },

    // 设置
    isSet: {
      type: Boolean,
      default: false
    },

    setList: {
      type: Array,
      default: function () {
        return [];
      }
    },

    multiple: {
      type: Boolean,
      default: false
    },

    acceptType: {
      type: String,
      default: 'image'
    },

    action: {
      type: String,
      default: ''
    },
    limit: {// 单次最大允许上传个数
      type: Number,
      default: 100
    },
    maxFileSize: {// 上传单个文件不得超过2G
      type: Number,
      default: 2000
    }, 
    // 删除是否请求接口
    deleteRequest: {
      type: Boolean,
      default: true
    },
  },

  data() {
    return {
      headers: {
        token: localStorage.getItem('token') // 获取token
      },
      ins: -1,
      dialogFormVisible: false,
      photoIndex: '',
      albumList: [],
      fileType: {
        image: '.jpg,.jpeg,.png,.gif,.bmp,',
        video: '.mp4, .m3u8,.flv,.f4v,.webm,.mov,.m4v,.3gp,.avi,.wmv,',
        audio: '.mp3,.wma,.wav,.amr,.m4a,'
      },
    };
  },
  watch: {
    fileList(val) {
      if (val.length) {
        this.albumList = val
      }
    }
  },

  computed: {
    // 进度条宽度
    progressWidth() {
      let percent = 100;
      if (parseInt(this.width) > parseInt(this.height)) {
        percent = parseInt(this.height) * 0.7
      } else {
        percent = parseInt(this.width) * 0.7
      }
      return percent
    },

    accept() {
      let types = '';
      if (this.acceptType.indexOf('image') > -1) {
        types = this.fileType.image
      }
      if (this.acceptType.indexOf('video') > -1) {
        types += this.fileType.video
      }
      if (this.acceptType.indexOf('audio') > -1) {
        types += this.fileType.audio
      }
      return types
    },

    actionUrl() {
      let url = this.action || window.ajaxBase.uploadUrl;
      return url
    },

    albumData() { 
      return {
        albumKey: this.folderKey || null
      }
    },
  },

  mounted() {
    if (this.fileList.length) {
      this.albumList = this.fileList
    }
  },

  methods: {

    urlType(url) {
      if (!url) {
        return
      }

      let type = '';
      let urlList = url.split('.');
      let urlType = urlList.pop();
      urlType = urlType.toLowerCase();
      if (this.fileType.image.indexOf(urlType) > -1) {
        type = 'image'
      } else if (this.fileType.video.indexOf(urlType) > -1) {
        type = 'video'
      } else if (this.fileType.audio.indexOf(urlType) > -1) {
        type = 'audio'
      }
      return type
    },

    handleProgress(event, file, fileList) {
      let tempArr = this.albumList
      this.albumList.forEach((element, index) => {
        if (element.uid === file.uid) {
          // 更新这个uid下的进度
          const progress = Math.floor(event.percent);

          const loaded = event.loaded
          const timeStamp = event.timeStamp
          let mark = false

          let speed = element.speed
          let diffTime = 0
          if (element.timeStamp > 0) {
            diffTime = timeStamp - element.timeStamp
            if (diffTime >= 1000) {
              mark = true
              speed = Math.floor(1000 * (loaded - element.loaded) / (timeStamp - element.timeStamp))
            }
          } else {
            mark = true
          }
          // 防止上传完接口还没有返回成功值，所以此处给定progress的最大值为99，成功的钩子中再置为100
          element.progress = progress === 100 ? 99 : progress
          element.speed = speed
          if (mark) {
            element.loaded = loaded
            element.timeStamp = timeStamp
          }
          this.$set(tempArr, index, element);
          this.$emit('changeFileList', tempArr);
        }
      });
    },

    /***
     * 添加数据
     */
    objAddItem(tempArr, file) {
      const tempObj = {
        uid: file.uid, // uid用于辨别文件
        originalName: file.name, // 列表显示的文件名
        progress: 0, // 进度条
        speed: 0, // 上传速度
        timeStamp: 0, // 时间戳
        loaded: 0 // 已上传
      };
      tempArr.push(tempObj);
    },

    /**
     * 文件超出个数限制时的钩子
     */
    handleExceed(files, fileList) {
      console.log("🚀 ~ file: UploadPhotoList.vue ~ line 326 ~ handleExceed ~ files, fileList", files, this.albumList.length)
      if ((this.albumList.length+files.length) > this.limit) {
        this.$message.error(`最多允许上传${this.limit}个文件`);
        return false;
      }
    },

    handleBeforeUpload(file) {
      console.log("🚀 ~ file: UploadPhotoList.vue ~ line 334 ~ handleBeforeUpload ~ file", file)
      // 文件大小限制
      const result = file.size / 1024 / 1024 < this.maxFileSize;
      if (!result) {
        this.$message.warning(`上传文件大小不得超过${this.maxFileSize}M`);
        return result;
      }
      // 验证都通过后，给自定义的列表中添加需要的数据
      this.objAddItem(this.albumList, file);
    },

    handleSuccess(response, file, fileList) {
      let tempArr = this.albumList;
      this.albumList.forEach((element, index) => {
        if (element.uid === file.uid) {
          if (response.success) {
            const {
              key,
              url,
              sourceUrl,
              name
            } = response.data.rows[0]
            element.progress = 100
            element.key = key
            element.url = url
            element.sourceUrl = sourceUrl
            element.name = name

            let param = {
              dataList: this.albumList,
              itemData: this.itemData
            };
            this.$emit('successChange', param);
          } else {
            tempArr.splice(index, 1); // 上传失败删除该记录
            this.$message.error(`"${element.originalName}"上传失败,${response.message}`);
            this.$emit('onUploadFailed', file, tempArr);
          }
          this.$emit('getAlbumList', this.albumList);
        }
      });
    },

    handleError(errorObj, file, fileList) {
      if (errorObj.message.indexOf('666') > 0) {
        this.$router.replace({
          name: 'login'
        });
        this.$message.warning('登录超时，请重新登录')
      }
      let tempArr = this.fileList;
      this.fileList.forEach((element, index) => {
        if (element.uid === file.uid) {
          tempArr.splice(index, 1); // 上传失败删除该记录
          this.$message.error(`文件上传失败:${element.originalName}`);
          this.$emit('onUploadFailed', file, fileList);
        }
      });
    },

    async getPhotosList() {
      const res = await photosList(this.folderKey)
      if (res.rows.length > 0) {
        this.albumList = res.rows
      } else {
        this.albumList = []
      }
      this.$emit('getAlbumList', this.albumList);
    },

    /**
     * 删除上传选项
     * @param index
     */
    async deleteItem(key, index) {
      const tempArr = this.albumList;
      if (key) {
        if (this.deleteRequest) {
          try{
            this.viewType == 'photo' ? await reqDeleteFolderFile(key) : await reqDeleteFile(key);
          }catch(e){
            console.log(e)
          }
        }
        tempArr.splice(index, 1);
        this.albumList = tempArr;
        let param = {
          dataList: tempArr,
          itemData: this.itemData
        }
        this.$emit('deleteChange', param);
        this.$emit('getAlbumList', this.albumList);
      }
    },

    setItemClick(file, item) {
      let param = {
        file: file,
        setItem: item
      }
      this.$emit('setItemClick', param);
    }
  },
  components: {

  }
};
</script>

<style lang="scss" scoped>
  .upload-album-list {
    .add-img-box {
      overflow: hidden;
      border-radius: 3px;
      border: 1px dashed #d9d9d9;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      position: relative;

      i {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
      }

      .img-progress {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        background: rgba(0, 0, 0, .2);
        display: inline-flex;
        justify-content: center;
        align-items: center;
        align-content: center;

        .el-progress__text {
          color: #409EFF;
        }
      }
    }

    ul {
      width: 100%;
      display: -webkit-flex;
      display: flex;
      flex-wrap: wrap;
      align-content: space-between;

      li {
        margin-right: 23px;
        margin-bottom: 20px;
        border-radius: 3px;
        width: 100px;
        height: 100px;
        overflow: hidden;
        position: relative;
        border: 1px solid #d9d9d9;

        .album-progress-bxo {
          height: 100px;
          width: 100%;
          position: absolute;
          top: 0px;
          left: 0px;
          z-index: 99;
          background: rgba(0, 0, 0, 0.3);

          .album-progress {
            position: absolute;
            top: 50%;
            left: 0px;
            z-index: 99;
            transform: translateY(-50%);
            -ms-transform: translateY(-50%);
            /* IE 9 */
            -moz-transform: translateY(-50%);
            /* Firefox */
            -webkit-transform: translateY(-50%);
            /* Safari 和 Chrome */
            -o-transform: translateY(-50%);
            /* Opera */
          }
        }

        .album-list-img-box {
          position: relative;
          left: -2px;
          width: 100px;
          height: 100px;
          overflow: hidden;
          img{
            width: 100px;
            height: 100px;
          }
          .img-tip{
            position: absolute;
            color: #fff;
            right: 0px;
            top: 0px;
            font-size: 9px;
            line-height: 16px;
            padding: 0 5px;
            background: rgba(230, 162, 60, 0.7);
            border-radius: 5px 1px 5px 1px;
          }
        }

        .handle-box {
          position: absolute;
          right: 0;
          bottom: 0;
          padding: 0px 5px;
          box-sizing: border-box;
          text-align: right;
          display: flex;

          .handle-btn-box{
            width: 100%;
            position: relative;
            right: -15%;
            white-space: nowrap;
            -webkit-transform: scale(0.7,0.7);
            -moz-transform: scale(0.7,0.7);
            -ms-transform: scale(0.7,0.7);
            -o-transform: scale(0.7,0.7);
            transform: scale(0.7,0.7);
          }

          span {
            line-height: 14px;
            font-size: 10px;
            color: #fff;
            background: rgba(64, 158, 255, .7);
            padding: 3px 5px;
            border-radius: 2px;
            overflow: hidden;
            margin-left: 5px;
            cursor: pointer;

          }

          .del {
            background: rgba(245, 108, 108, .7);
          }
        }
      }

      .null-li {
        border: 0px;
      }
    }
  }
</style>
