<template>
  <view class="file-upload">
    <view class="preview" v-for="(item, index) in fileList" :key="index">
      <image
        class="preview-icon"
        mode="aspectFill"
        :src="item.fileType==='image' ? item.tempFilePath : item.thumbTempFilePath"
        @tap="previewFile(index, item)">
      </image>
      <image class="delete-icon" src="@/static/images/upload/delete.png" @tap="deleteFile(index)"/>
    </view>
    <view class="upload-btn" v-if="!disabled" @click="chooseFile">
      <image class="upload-icon" src="@/static/images/upload/jiahao.png" alt="">
      <view>上传附件</view>
    </view>
    <view class="video" v-if="isPreviewVideo">
      <video id="myVideo" :src="videoUrl" autoplay controls @error="videoErrorCallback"></video>
      <image src="@/static/images/upload/delete.png" @tap="closeVideo"/>
    </view>
  </view>
</template>

<script>
import { uploadFile } from '@/api/system';

export default {
  name: "file-upload",
  props: {
    maxCount: {
      type: Number,
      default: 4
    },
  },
  data() {
    return {
      fileList: [],
      disabled: false,
      isPreviewVideo: false,
      videoUrl: '',
    }
  },
  methods: {
    chooseFile() {
      var that = this;
      // #ifdef MP-WEIXIN
      uni.chooseMedia({
        count: this.maxCount,
        mediaType: ['image','video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          const fileInfo = res.tempFiles;
          fileInfo.forEach(item =>{
            uploadFile(item.tempFilePath).then(res => {
              const fileName = item.fileType === 'video' ? 'video.mp4' : 'picture.png'
              item.fileId = { type: item.fileType, name: '', fileId: res.data };
              that.fileList.push(item);
            })
          })
          if (that.fileList.length >= that.maxCount ) {
            that.disabled = true;
          }
        },
        fail(err) {
          console.log(err);
        }
      })
      // #endif

      // #ifdef MP-ALIPAY || H5
      uni.chooseImage({
        count: this.maxCount,
        success(res) {
          res.tempFilePaths.forEach(item =>{
            uploadFile(item).then(res => {
              that.fileList.push({
                tempFilePath: item,
                fileType: 'image',
                fileId: {type: 'image', name: '', fileId: res.data}
              });
            })
          })
          if (that.fileList.length >= that.maxCount ) {
            that.disabled = true;
          }
        },
        fail(err) {
          console.log(err);
        }
      })
      // #endif
    },

    // 删除选择的文件
    deleteFile (val) {
      this.fileList.splice(val, 1);
    },

    // 预览图片和视频
    previewFile (index, val) {
      if(val.fileType === 'image') {
        const imageUrls = [];
        this.fileList.forEach(item => {
          if (item.fileType === 'image') {
            imageUrls.push(item.tempFilePath)
          } else if (item.fileType === 'video') {
            imageUrls.push(item.thumbTempFilePath)
          }
        });
        uni.previewImage({
          current: index,
          urls: imageUrls
        });
      } else if (val.fileType === 'video') {
        this.videoUrl = val.tempFilePath;
        this.isPreviewVideo = true;
      } else if (val.fileType === 'audio') {
        const innerAudioContext = uni.createInnerAudioContext();
        innerAudioContext.autoplay = true;
        innerAudioContext.src = val.tempFilePath;
				innerAudioContext.play();
      }
    },

    // 关闭正在预览的视频
    closeVideo() {
      this.isPreviewVideo = false;
    },

    // 播放视频失败
    videoErrorCallback (e) {
      uni.showModal({
        content: e.target.errMsg,
        showCancel: false
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.file-upload {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .preview {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    margin: 10rpx;
    border-radius: 10rpx;
    border: 1px solid #e5e2e2;
    .preview-icon {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
    }
    .delete-icon {
      width: 45rpx;
      height: 45rpx;
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  .upload-btn {
    width: 120rpx;
    height: 120rpx;
    margin: 10rpx;
    border: 0.5px solid #ebe6e6;
    border-radius: 10rpx;
    font-size: 24rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .upload-icon {
      width: 70rpx;
      height: 70rpx;
    }
  }
  .video {
    position: absolute;
    z-index: 999;
    image {
      width: 50rpx;
      height: 50rpx;
      position: absolute;
      right: 15rpx;
    }
  }
}
</style>