<template>
  <div class="component-upload-image">
    <el-upload
      multiple
      :action="uploadImgUrl"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :show-file-list="false"
      :headers="headers"
      :file-list="fileList"
      :class="{ hide: this.fileList.length >= this.limit }"
    >
      <!-- <i class="el-icon-plus"></i> -->
      <div
        class="imgbox"
        style="border: none"
        v-for="(item, index) in fileList"
        :key="index"
        @click.stop="() => {}"
      >
        <video
          width="100%"
          height="100%"
          preload="auto"
          v-if="item.isVideo"
          style="object-fit: fill"
        >
          <source
            width="100%"
            height="100%"
            style="width: 100%; height: 100%"
            :src="item.url"
            type="video/mp4"
          />
        </video>
        <img :src="item.url" v-else style="width: 100%; height: 100%" />
        <span class="actions">
          <a
            class="actions-item"
            @click.stop="handlePreview(item)"
            href="javascript:;"
            style="margin-right: 15px"
          >
            <i class="el-icon-view"></i>
          </a>
          <a
            class="actions-item"
            @click.stop="handleDelete(index)"
            href="javascript:;"
          >
            <i class="el-icon-delete"></i>
          </a>
        </span>
      </div>
      <div class="imgbox" v-if="fileList.length < limit">
        <i class="el-icon-plus" style="font-size: 28px; color: #8c939d"></i>
      </div>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      height="400"
      append-to-body
    >
      <div v-if="dialogVisible">
        <video
          style="
            display: block;
            width: 100%;
            height: 100%;
            margin: 0 auto;
            object-fit: fill;
          "
          v-if="dialogFileType"
          autoplay
          controls="controls"
        >
          <source :src="dialogImageUrl" type="video/mp4" />
        </video>
        <img
          v-else
          :src="dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { UPLOAD_TYPE_MAP, UPDALOD_API_MAP } from '@/utils/constants';
import { getToken } from '@/utils/auth';
import { assign, last, isArray, split, startsWith } from 'lodash-es';

export default {
  // props:['message'],//接收psMsg值
  props: {
    value: [String, Object, Array],
    // 图片/视频 数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg', 'mp4']
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    uploadType: {
      type: String,
      default: UPLOAD_TYPE_MAP.COMMON
    }
  },
  data() {
    return {
      videoTypeLibrary: [
        'mp4',
        'avi',
        'mov',
        'wmv',
        'flv',
        'mkv',
        '3gp',
        'mpeg'
      ],
      number: 0,
      uploadList: [],
      dialogImageUrl: '',
      dialogFileType: '',
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_RESOURCE_PREFIX,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: [],
      UPDALOD_API_MAP
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          if (typeof val === 'string') {
            return;
          }

          // 首先将值转为数组
          const list = Array.isArray(val) ? val : [val];

          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            let data = assign({}, item);
            const type = last(split(item.url, '.'));
            const isVideo = this.videoTypeLibrary.indexOf(type) >= 0;

            if (
              item.url &&
              !startsWith(item.url, 'http') &&
              !startsWith(item.url, this.baseUrl)
            ) {
              data = {
                name: this.baseUrl + item.url,
                url: this.baseUrl + item.url,
                resId: item.resId || item.resIds || '',
                isVideo: isVideo
              };
            } else {
              data = {
                name: item.url,
                url: item.url,
                resId: item.resId || item.resIds || '',
                isVideo: isVideo
              };
            }
            console.log(data);
            return data;
          });
          // console.log(this.fileList)
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    uploadImgUrl() {
      return process.env.VUE_APP_BASE_API + UPDALOD_API_MAP[this.uploadType];
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  methods: {
    // 上传前loading加载
    handleBeforeUpload(file) {
      console.log(file.type);
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = '';
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg =
          file.type.indexOf('image') > -1 || file.type.indexOf('video') > -1;
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join('/')}图片/视频 格式文件!`
        );
        return false;
      }
      if (file.size / 1024 / 1024 > this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(
            `上传图片/视频大小不能超过 ${this.fileSize} MB!`
          );
          return false;
        }
      }
      this.$modal.loading('正在上传图片/视频，请稍候...');
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {
      const { resUrl, url, resId, resOssUrl } = res.data;
      if (res.code === '000000') {
        this.uploadList.push({
          resId: resId,
          name: url || resUrl,
          url: resOssUrl || resUrl
        });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },

    // 上传失败
    handleUploadError() {
      this.$modal.msgError('上传 图片/视频 失败，请重试');
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;

        this.$emit(
          'input',
          isArray(this.value) ? this.fileList : last(this.fileList)
        );
        this.$modal.closeLoading();
      }
    },
    // 删除图片/视频
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit(
        'input',
        isArray(this.value) ? this.fileList : last(this.fileList)
      );
    },
    // 预览
    handlePreview(item) {
      console.log(item);
      this.dialogImageUrl = item.url;
      this.dialogFileType = item.isVideo;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = '';
      separator = separator || ',';
      for (const i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, '') + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
.imgbox {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  cursor: pointer;
  line-height: 146px;
  vertical-align: top;
  display: inline-block;
  margin-right: 10px;
  position: relative;
  .actions {
    display: none;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 20px;
    color: #fff;
    background: rgba(0, 0, 0, 0.4);
  }
}
.imgbox:hover {
  .actions {
    display: initial;
  }
}
</style>
