<template>
  <view class="file-upload">
    <view class="preview" v-for="(item, index) in fileList" :key="index">
      <image
        class="preview-image"
        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/camera.png"
        alt=""
      />
      <view class="text">添加图片</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";
import CanvasCompress from "canvas-compress";
import { fileToBase64 } from "@/utils";
export default {
  name: "uploadFile",
  props: {
    maxCount: {
      type: Number,
      default: 5,
    },
    catalog: {
      type: String,
      default: "house", // 当前默认租房
    },
  },
  data() {
    return {
      fileList: [],
      disabled: false,
      isPreviewVideo: false,
      videoUrl: "",
    };
  },
  created() {
    this.compressor = new CanvasCompress({
      type: CanvasCompress.MIME.JPEG,
      width: 600,
      height: 600,
      quality: 0.8,
    });
  },
  methods: {
    async compress(file) {
      const res = await this.compressor.process(file);
      return res.result;
    },
    chooseFile() {
      var that = this;
      // #ifdef MP-WEIXIN
      uni.chooseMedia({
        count: this.maxCount,
        mediaType: ["image"],
        sourceType: ["album", "camera"],
        maxDuration: 60,
        camera: "back",
        success(res) {
          const fileInfo = res.tempFiles;
          const fileType = res.type;
          fileInfo.forEach((item) => {
            console.log(item);
            item.fileType = fileType; //兼容ios15.3
            if (fileType === "image" && item.size > 500 * 1024) {
              console.log("压缩再上传");
              uni.compressImage({
                src: item.tempFilePath,
                quality: 80,
                success: (res) => {
                  item.tempFilePath = res.tempFilePath;
                  that.upload(item);
                },
                fail: (err) => console.log(err),
              });
            } else {
              that.upload(item);
            }
          });
        },
        fail(err) {
          console.log(err);
        },
      });
      // #endif

      // #ifdef MP-ALIPAY || H5
      uni.chooseImage({
        count: this.maxCount,
        success(res) {
          console.log(res);
          /*  res.tempFiles.forEach(async (tempFile,index) => {
            const compressedFile=await that.compress(tempFile);
            const fileInfo = await uploadFile({
              file:compressedFile.blob,
              formData: {
                catalog: that.catalog,
              },
            });
            that.fileList.push({
              tempFilePath: res.tempFilePaths[index],
              fileType: "image",
              fileId: fileInfo.data,
            });
          }); */
          /* rpc上传接口有大小限制，iphone相册图片上传413 */
          res.tempFiles.forEach(async (file, index) => {
            const compressedFile = await that.compress(file);
            const fileBase64 = await fileToBase64(compressedFile.blob);
            const fileInfo = await uploadFile({
              fileBase64Vos: [
                { fileName: file.name, contentBase64: fileBase64 },
              ],
              catalog: that.catalog,
            });
            console.log("本地路径地址", res.tempFilePaths[index]);
            that.fileList.push({
              tempFilePath: res.tempFilePaths[index],
              fileType: "image",
              fileId: fileInfo.data,
            });
          });
          if (that.fileList.length >= that.maxCount) {
            that.disabled = true;
          }
        },
        fail(err) {
          console.log(err);
        },
      });
      // #endif
    },
    upload(res) {
      let item = { ...res };
      uploadFile(res.tempFilePath).then((res) => {
        item.fileId = res.data;
        this.fileList.push(item);
        if (this.fileList.length >= this.maxCount) {
          this.disabled = true;
        }
      });
    },
    // 删除选择的文件
    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: 5px;
    border-radius: 5px;
    border: 1px solid #e5e2e2;
    .preview-image {
      width: 70px;
      height: 70px;
      border-radius: 5px;
    }
    .delete-icon {
      width: 22px;
      height: 22px;
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  .upload-btn {
    width: 80px;
    height: 80px;
    margin: 5px;
    border: 0.5px solid #ebe6e6;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .upload-icon {
      width: 35px;
      height: 35px;
    }
    .text {
      font-size: 10px;
      font-weight: 200;
      color: #999999;
      margin-top: 2px;
    }
  }
  .video {
    position: absolute;
    z-index: 999;
    image {
      width: 25px;
      height: 25px;
      position: absolute;
      right: 8px;
    }
  }
}
</style>
