<template>
  <view
    class="sp-uploader"
    :class="{ 'sp-uploader-media-list': !isAll, 'sp-uploader-list': isAll }"
    :style="style"
  >
    <template v-if="!isAll">
      <!-- 媒体：图片/视频 -->
      <view
        class="show-box"
        v-for="(item, index) in fileList"
        :key="index + 'media'"
        :style="cardStyle"
      >
        <template v-if="isVideo(item)">
          <!-- #ifdef H5 -->
          <video
            class="full full-container"
            :src="item.tempUrl || item.url"
            :disabled="false"
            :controls="false"
            :autoplay="false"
          >
            <cover-view
              v-if="item.isVideo"
              class="image-upload-item-video-fixed"
              @click="previewVideo(item)"
            ></cover-view>
            <cover-view v-if="updating" class="delect-icon" @tap="deleteConfirm(item, index)">
              <image class="full" :src="clearIcon" />
            </cover-view>
          </video>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN || APP-PLUS -->
          <div
            @click="previewVideo(item)"
            class="full full-container"
            style="background: #000; display: flex; align-items: center; justify-content: center;"
          >
            <image :src="playIcon" style="width: 24px; height: 24px;" />
            <view v-if="updating" class="delect-icon" @tap="deleteConfirm(item, index)">
              <image class="full" :src="clearIcon" />
            </view>
          </div>
          <!-- #endif -->
        </template>

        <template v-else>
          <image
            v-if="hanleUrl(item)"
            class="full"
            :src="hanleUrl(item)"
            @tap="previewImage(item.tempUrl || item.url)"
          />
          <div v-else class="flex-column-center fail-img-tips">
            <div
              class="fail-img-name"
              v-if="item.orgFileName"
            >{{ item.orgFileName.replace(item.suffix, '') }}</div>
            <span>{{ item.suffix || item.orgFileName }}</span>
            <span>暂不支持显示</span>
          </div>
          <view v-if="updating" class="delect-icon" @tap="deleteConfirm(item, index)">
            <image class="full" :src="clearIcon" />
          </view>
        </template>
      </view>
      <!--视频-->
      <!-- <view class="show-box" v-for="(item1, index1) in videoList" :key="index1 + 'video'">
        <video class="full full-container" :src="item1" :disabled="false" :controls="false">
          <cover-view class="image-upload-item-video-fixed" @click="previewVideo(item1)"></cover-view>
        </video>
        <view class="delect-icon" @tap="delectVideo(index1)">
          <image class="full" :src="clearIcon" />
        </view>
      </view>-->
      <view v-if="selectBtnShow" @tap="chooseVideoImageFile()" class="box-mode" :style="cardStyle">
        <image class="full" :src="selectfile" />
      </view>
    </template>
    <template v-else>
      <!-- 所有文件 -->
      <div @click="selecteFile">
        <slot name="trigger">
          <view v-if="updating" class="attach-button">{{ buttonText }}</view>
        </slot>
      </div>
      <transition-group name="slide">
        <view
          v-for="(item, index) in fileList"
          :key="index + 'file'"
          class="attach-list-layout"
          @click="previewAttach(item)"
        >
          <img class="attach-icon" fit="fill" :src="suffixType(item.suffix)" />
          <span class="attach-title" :title="item.orgFileName">
            <span>{{ item.orgFileName }}</span>
            <span v-if="fileSize" class="attach-size">({{ parseSize(item) }})</span>
          </span>
          <img
            :src="deleteImg('delete')"
            v-if="updating"
            class="attach-operation"
            @click.stop="deleteConfirm(item, index)"
          />
        </view>
      </transition-group>
    </template>

    <!-- 全屏预览视频 -->
    <view class="preview-full" v-if="previewVideoSrc != ''">
      <video
        :autoplay="true"
        :src="previewVideoSrc"
        @loadedmetadata="loadedmetadata"
        :show-fullscreen-btn="false"
      >
        <!-- 退出全屏预览按钮 -->
        <cover-view class="preview-full-download" @click="downloadVideo(previewItem, false)">下载</cover-view>
        <cover-view class="preview-full-close" @click="previewVideoClose">×</cover-view>
      </video>
    </view>
  </view>
</template>
<script>
import {
  ApiUpload,
  ApiDelete,
  getOssToken,
  ApiAttachList,
  ApiComplete,
} from './api.js'

import { suffixImg, deleteImg, xhrRequest } from './tool'

import Bridge from '../../libs/util/bridge.js'

var sourceType = [['camera'], ['album'], ['camera', 'album']]
import MixinOut from './mixin-out'

export default {
  mixins: [MixinOut],
  data() {
    const map = new Map()
    return {
      deleteImg,
      image: '',
      // 图标
      clearIcon:
        'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMCAyMCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3Z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KKQHBRoxB0MQsc52eSs6z8DzZBs7zTq78JV8Cgg3ZiH6Jxb8R+FzjQiosk/GYy9L4HY056GeNEv0FCG0z0WABgBfd33L1kXyqQHMWhuN1XnSvX2AM7ZsFIKnYiIsrgAQYAHE9dHxqwP3xqUE6BcdwjCZZZGksG0BCK1oPOAuQoNaQw5r/D1UwnKKZZXhsVAyg0YLERxzp5zYMCtLFe7f0cxta9yKj003/ACs7ViD3XcxfAAAAAElFTkSuQmCC',
      fileList: [], //存放文件列表
      sourceType: ['拍摄', '相册', '拍摄或相册'],
      sourceTypeIndex: 2,
      cameraList: [
        {
          value: 'back',
          name: '后置摄像头',
          checked: 'true',
        },
        {
          value: 'front',
          name: '前置摄像头',
        },
      ],
      cameraIndex: 0, //上传视频时的数量
      maxCount: 0, // 图片和视频允许上传的总数

      //
      previewVideoSrc: '',
      previewItem: {},

      //
      fileMap: map,
      ossToken: '',
    }
  },
  watch: {
    length() {
      this.setCount()
    },
    value(val, oldVal) {
      if (val != oldVal) {
        this.getFileList()
      }
    },
  },
  computed: {
    // 页面图片或视频数量超出后，拍照按钮隐藏
    selectBtnShow() {
      if (!this.updating) {
        return false
      }
      if (this.fileList.length >= this.maxCount) {
        return false
      } else {
        return true
      }
    },
    widthHeight() {
      if (this.cardSize) {
        if (Number(this.cardSize) == this.cardSize) {
          return this.cardSize + 'rpx'
        } else {
          return this.cardSize
        }
      }
      return '240rpx'
    },
    cardStyle() {
      return { width: this.widthHeight, height: this.widthHeight }
    },
    isAll() {
      return !this.mode || this.mode == 'all'
    },
    style() {
      let obj = {}
      if (this.isAll && !this.blank) {
        obj['margin-left'] = 0
        obj['margin-right'] = 0
      } else if (!(this.blank || this.isAll)) {
        obj['margin-left'] = '-10px'
      }
      return obj
    },
  },
  onUnload() {
    ;(this.fileList = []),
      (this.sourceTypeIndex = 2),
      (this.sourceType = ['拍摄', '相册', '拍摄或相册'])
  },
  mounted() {
    this.setCount()
    this.getFileList()
  },
  methods: {
    setCount() {
      let num = Number(this.length)
      if (num <= 0) {
        num = 1
      }
      this.maxCount = num
    },
    async selecteFile() {
      const list = ['图片', '视频', '拍照', '录像']
      if (this.file) {
        // #ifdef H5
        list.push('文件')
        // #endif
      }
      this.chooseVideoImageFile(list, true)
    },
    //点击上传图片或视频
    chooseVideoImageFile(modeType = ['图片', '视频', '拍照', '录像']) {
      if (this.mode == 'image') {
        modeType = ['图片', '拍照']
      } else if (this.mode == 'video') {
        modeType = ['视频', '录像']
      }
      uni.showActionSheet({
        title: '选择上传类型',
        itemList: modeType,
        success: (res) => {
          const chooseKey = modeType[res.tapIndex]
          console.log('选择上传类型', chooseKey)
          switch (chooseKey) {
            case '图片':
              this.chooseImages()
              break
            case '视频':
              this.chooseVideo()
              break
            case '拍照':
              this.chooseImages('camera')
              break
            case '录像':
              this.chooseVideo('camera')
              break
            case '文件':
              this.chooseFile()
              break
            default:
              this.chooseImages()
              break
          }
        },
      })
    },

    //上传图片
    chooseImages(type) {
      let sourceType = ['album']
      if (type == 'camera') {
        sourceType = ['camera']
      }
      uni.chooseImage({
        count: this.maxCount, //允许选择的数量
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: sourceType, //从相册选择
        success: (res) => {
          console.log('chooseImages', res.tempFilePaths)
          this.validFile(res.tempFilePaths)
          // this.fileList = this.fileList.concat(res.tempFilePaths)
          // console.log(res)
          // if (this.fileList.length + this.videoList.length == this.maxCount) {
          //   this.VideoOfImagesShow = false //图片上传数量和count一样时，让点击拍照按钮消失
          // }
        },
      })
    },
    //上传视频
    chooseVideo(type) {
      let sourceType = ['album']
      if (type == 'camera') {
        sourceType = ['camera']
      }
      uni.chooseVideo({
        maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
        count: this.maxCount,
        camera: this.cameraList[this.cameraIndex].value, //'front'、'back'，默认'back'
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: sourceType,
        // sourceType: sourceType[this.sourceTypeIndex],
        compressed: false,
        success: (res) => {
          let file = []
          file = file.concat(res.tempFilePath)

          console.log('chooseVideo', file)
          this.validFile(file)

          // this.fileList = this.fileList.concat(res.tempFilePath)
          // // this.videoList = this.videoList.concat(res.tempFilePath)
          // if (this.fileList.length + this.videoList.length == this.maxCount) {
          //   this.VideoOfImagesShow = false
          // }
          // console.log(this.videoList)
        },
      })
    },
    async chooseFile() {
      uni.chooseFile({
        count: this.maxCount,
        type: this.accept ? '' : 'all',
        extension: this.accept || [],
        success: (res) => {
          console.log('chooseFile', res.tempFilePaths)
          let attach = res.tempFilePaths
          this.validFile(attach)
        },
      })
    },
    //预览图片
    previewImage: function (e) {
      let list = []
      this.fileList.forEach((e) => {
        if (this.isImage(e)) {
          list.push(e.url)
        }
      })
      uni.previewImage({
        current: e,
        urls: list,
      })
    },
    // 删除
    deleteConfirm(item, index) {
      uni.showModal({
        title: '提示',
        content: '是否要删除该文件',
        success: (res) => {
          if (res.confirm) {
            this.delFile(item, index)
          }
        },
      })
    },
    async delFile(item, index) {
      if (this.isEmpty(this.value)) {
        return
      }
      let request = {
        attachId: this.value,
        removeFileCode: item.fileCode,
      }
      let res = await ApiDelete(request, this.ossToken)
      if (res.data && res.data.success) {
        this.fileList.splice(index, 1)
      }
    },
    // 删除视频
    delectVideo(index) {
      uni.showModal({
        title: '提示',
        content: '是否要删除此视频',
        success: (res) => {
          if (res.confirm) {
            this.fileList.splice(index, 1)
          }
        },
      })
    },
    previewVideo(item) {
      // #ifdef H5
      this.previewVideoOpen(item)
      return
      // #endif

      if (!item.tempUrl) {
        uni.showLoading({
          title: '正在加载中',
        })
        uni.downloadFile({
          url: item.url,
          success: ({ tempFilePath, statusCode }) => {
            item.tempUrl = tempFilePath
            uni.hideLoading()
            this.previewVideoOpen(item)
          },
          fail: (error) => {
            uni.hideLoading()
          },
        })
      } else {
        this.previewVideoOpen(item)
      }
    },
    previewVideoOpen(item) {
      // #ifdef H5 || MP-WEIXIN
      uni.showLoading({
        title: '正在加载中...',
      })
      // #endif

      // 打开预览视频
      this.previewVideoSrc = item.tempUrl || item.url
      console.log('item.tempUrl || item.url', this.previewVideoSrc)
      this.previewItem = item
    },
    previewVideoClose() {
      this.previewVideoSrc = ''
      this.previewItem = {}
    },
    validFile(tempFilePaths) {
      let attach = tempFilePaths
      if (this.beforeUpload(attach)) {
        this.afterUpload(attach)
      }
    },
    beforeUpload(attach) {
      if (this.fileList.length > this.maxCount) {
        this.toast(`不能超过 ${this.maxCount} 个附件`)
        return false
      }
      if (Array.isArray(attach)) {
        if (this.fileList.length + attach.length > this.maxCount) {
          this.toast(`不能超过 ${this.maxCount} 个附件`)
          return false
        }
      } else {
        if (this.fileList.length + 1 > this.maxCount) {
          this.toast(`不能超过 ${this.maxCount} 个附件`)
          return false
        }
      }
      return true
    },
    async afterUpload(attach) {
      if (this.isEmpty(this.ossToken)) {
        let res = await getOssToken()
        this.ossToken = res.data.data.token
      }
      if (this.isEmpty(this.ossToken)) {
        // this.hindLoading()
        return fasle
      }
      let value
      if (this.isEmpty(this.value)) {
        value = this.uuid(32).replace(/-/g, '')
        this.$emit('input', value)
      }
      if (Array.isArray(attach)) {
        let fileCount = attach.length
        attach.forEach((file) => {
          this.uploadFile(file, value)
        })
      } else {
        this.uploadFile(attach, value)
      }
    },
    isEmpty(text) {
      return typeof text == 'undefined' || text == null || text == ''
    },
    async uploadFile(filePath, value) {
      uni.showLoading({
        title: '正在处理中...',
        mask: false,
      })
      let upload = await ApiUpload(
        filePath,
        value || this.value,
        this.ossToken
      ).catch((e) => {
        uni.hideLoading()
      })
      if (upload.data && upload.data.data && upload.data.data.files) {
        // 显示新文件
        let nf = upload.data.data.files[0]
        nf.tempUrl = filePath // 写入本地缓存地址，以便预览
        this.fileMap.set(nf.fileCode, nf)
        if (this.reverse) {
          this.fileList.push(nf)
        } else {
          this.fileList.unshift(nf)
        }
        uni.hideLoading()
        return true
      }
      uni.hideLoading()
      return false
    },
    complete() {
      // 确认附件
      if (this.isEmpty(this.value)) {
        return
      }
      if (this.fileList) {
        let request = {
          attachId: this.value,
        }
        ApiComplete(request, this.ossToken).then((res) => {})
      }
    },
    async getFileList() {
      if (this.isEmpty(this.value)) {
        return
      }
      if (this.isEmpty(this.ossToken)) {
        let res = await getOssToken()
        this.ossToken = res.data.data.token
      }
      let list = await ApiAttachList(this.value, this.ossToken, this.showTemp)
      let data = list.data.data
      if (data) {
        if (this.reverse) {
          data = data.reverse()
        }
        this.fileList = data
      }
    },
    toast(e) {
      uni.showToast({
        title: e,
        duration: 2000,
        icon: 'none',
        position: 'bottom',
      })
    },
    //获取随机id
    uuid(len, binary) {
      len = !len ? 36 : len
      binary = !binary ? 16 : binary
      return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxxxxxx'
        .replace(/[xy]/g, function (c) {
          var r = (Math.random() * binary) | 0,
            v = c == 'x' ? r : (r & 0x3) | 0x8
          return v.toString(binary)
        })
        .substring(0, len)
    },
    fileType(item) {
      return 'img'
      return 'video'
      return 'file'
    },
    isImage(item) {
      let suffix = item.suffix
      if (suffix) {
        suffix = suffix.toLowerCase()
        let type = ['.png', '.jpg', '.jpeg', '.gif', '.svg']
        if (type.includes(suffix)) {
          item.isImage = true
          return true
        }
      }
      return false
    },
    isVideo(item) {
      let suffix = item.suffix
      if (suffix) {
        suffix = suffix.toLowerCase()
        let types = [
          '.ogm',
          '.wmv',
          '.mpg',
          '.webm',
          '.ogv',
          '.mov',
          '.asx',
          '.mpeg',
          '.mp4',
          '.m4v',
          '.avi',
        ]
        if (types.includes(suffix)) {
          item.isVideo = true
          return true
        }
      }
      return false
    },
    hanleUrl(item = {}) {
      let suffix = item.suffix
      suffix = suffix.toLowerCase()
      if (item.suffix == '.webp') {
        return ''
      } else {
        return item.url
      }
    },
    suffixType(suffix) {
      return suffixImg(suffix)
    },

    previewAttach(item) {
      let type = item.suffix
      if (type) {
        type = type.toLowerCase()
      }
      if (this.isVideo(item)) {
        this.previewVideo(item)
      } else if (this.isImage(item)) {
        this.previewImage(item.tempUrl || item.url)
      } else {
        this.downloadFile(item, true)
      }
    },
    windowDownload(data = {}) {
      const handleDownload = (fileBlob) => {
        let fileName = data.orgFileName || '下载文件' + data.suffix
        // let blob = new Blob([fileBlob], {
        //   type: 'application/octet-stream;charset=UTF-8',
        // })

        let link = document.createElement('a')
        link.download = fileName
        link.href = data.url
        // link.href = window.URL.createObjectURL(blob)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        // window.URL.revokeObjectURL(link.href) //释放内存
        uni.hideLoading()
      }
      try {
        handleDownload()
        //
        // uni.showLoading({
        //   title: '下载中...',
        // })
        // xhrRequest({
        //   url: data.url,
        //   onProgress: ({ loaded, total }) => {
        //     let title = '下载中...'
        //     if (loaded && total) {
        //       title = title + ((loaded / total) * 100).toFixed(0) + '%'
        //     }
        //     uni.showLoading({
        //       title,
        //     })
        //   },
        // })
        //   .then((file) => {
        //     handleDownload(file)
        //   })
        //   .finally(() => {
        //     uni.hideLoading()
        //   })
      } catch (e) {
        uni.hideLoading()
      }
    },
    downloadFile(data, tips = false) {
      if (!data.url) {
        uni.showToast({
          title: '下载失败',
          duration: 2000,
        })
        return
      }
      const confirmDownload = () => {
        const mobileTag = uni.getStorageSync('mobile')
        const isMobile = mobileTag == 'android' || mobileTag == 'ios'
        uni.showLoading({
          title: '文件下载中',
        })

        // #ifdef MP-WEIXIN
        uni.downloadFile({
          url: item.url,
          success: ({ tempFilePath, statusCode }) => {
            // 保存
            uni.saveFile({
              tempFilePath: tempFilePath,
              success: function () {
                // 成功提示
                uni.showToast({
                  title: '保存成功',
                  duration: 2000,
                })
              },
            })
            uni.hideLoading()
          },
          fail: (error) => {
            uni.showToast({
              title: '下载异常',
              duration: 2000,
            })
            uni.hideLoading()
          },
        })
        return
        // #endif

        if ((process.env.NODE_ENV === 'development' && window) || window) {
          // #ifdef H5
          if (isMobile) {
            // APP内
            // data.type = 'local'  // 不传:第三方应用打开;local:本地打开
            Bridge.call('download_attach', data, () => {
              uni.hideLoading()
            })
            return
          }
          // window.open(data.url)
          this.windowDownload(data)
          return
          // #endif
        }

        try {
          uni.sendNativeEvent('download_attach', data, function (e) {
            uni.hideLoading()
            console.log('-->>>NativeEvent-----回调' + JSON.stringify(e))
          })
        } catch (error) {
          uni.hideLoading()
        }
      }
      if (tips) {
        uni.showModal({
          title: '提示',
          content: '该文件暂无法预览，是否确定下载？',
          success: (res) => {
            if (res.confirm) {
              confirmDownload()
            }
          },
        })
      } else {
        confirmDownload()
      }
    },
    // MARK: 文件大小单位转换
    parseSize(file) {
      let size = file.fileSize || 0
      return size >= 1024 * 1024
        ? `${Math.round(size / 1024 / 1024)}MB`
        : `${Math.round(size / 1024)}KB`
    },
    downloadVideo(item) {
      let path = item.tempUrl || item.url

      // #ifdef H5
      // window.open(path)
      this.windowDownload(item)
      return
      // #endif

      // 保存视频到手机相册
      uni.saveVideoToPhotosAlbum({
        filePath: path,
        success: function () {
          // 成功提示
          uni.showToast({
            title: '保存成功',
            duration: 2000,
          })
        },
      })
    },
    loadedmetadata() {
      uni.hideLoading()
    },
  },
}
</script>
<style lang="scss" scoped>
$main-theme-color: #165dff;

/* 统一上传后显示的盒子宽高比 */
.box-mode {
  border-radius: 8rpx;
  overflow: hidden;
  margin: 10rpx 10rpx;
}

.sp-uploader {
  width: 100%;

  .full {
    width: 100%;
    height: 100%;
  }

  .fail-img-name {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 90%;
    text-align: center;
  }
  .fail-img-tips {
    font-size: 12px;
    color: #aaa;
    line-height: 21px;
    background: #f2f3f5;
  }

  .flex-column-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  // 媒体
  &.sp-uploader-media-list {
    display: flex;
    flex-wrap: wrap;
    display: flex;
    padding: 10rpx 10rpx;
    .show-box:nth-child(3n) {
      // margin-right: 0;
    }
    .show-box {
      position: relative;
      @extend .box-mode;

      .delect-icon {
        height: 40rpx;
        width: 40rpx;
        position: absolute;
        right: 0rpx;
        top: 0rpx;
        z-index: 997;
      }

      ::v-deep .uni-video-cover-play-button {
        width: 40%;
        height: 40%;
        max-width: 40px;
        max-height: 40px;
      }
    }
  }

  // 附件列表
  &.sp-uploader-list {
    margin: 12rpx 32rpx;

    .attach-button {
      width: auto;
      height: 70rpx;
      font-size: 32rpx;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 8rpx;
      text-align: center;
      line-height: 24rpx;
      background-color: $main-theme-color;
      margin-bottom: 20rpx;
    }

    .attach-list-layout:active {
      background-color: rgba(0, 0, 0, 0.15);
    }

    .attach-list-layout {
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 0rpx;
      height: 52rpx;
      margin: 8rpx 0rpx;
      background-color: #ffffff;
      border-radius: 4rpx;

      .attach-icon {
        width: 36rpx;
        height: 36rpx;
        margin-left: 8rpx;
      }

      .attach-title {
        font-family: PingFangSC-Regular, PingFang SC;
        font-size: 24rpx;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
        display: inline-block;
        flex: 1;
        width: 260rpx;
        line-height: 52rpx;
        margin-left: 16rpx;
        margin-right: 26rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .attach-size {
        color: rgba(0, 0, 0, 0.45);
        font-size: 20rpx;
        margin-left: 10rpx;
      }

      .attach-operation {
        font-size: 32rpx;
        text-align: center;
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }
    }
  }
}

//
.image-upload-item-video-fixed {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 996;
}

.preview-full {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 1002;

  video {
    width: 100%;
    height: 100%;
    z-index: 1002;
  }

  .preview-full-close {
    position: fixed;
    right: 16px;
    top: 12px;
    width: 40px;
    height: 40px;
    line-height: 30px;
    text-align: center;
    z-index: 1003;
    color: #fff;
    font-size: 32px;
    font-weight: bold;
  }

  .preview-full-download {
    position: fixed;
    right: 58px;
    top: 16px;
    width: 40px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    z-index: 1003;
    color: #fff;
    font-size: 14px;
  }
}

// 新增和删除动画
.slide-enter-active {
  animation: slide-in 0.3s ease-out;
}

.slide-leave-active {
  animation: slide-out 0.3s ease-out;
}

.slide-move {
  transition: all 0.3s;
}
@keyframes slide-in {
  from {
    transform: translateX(-40rpx);
  }

  to {
    transform: translateX(0);
  }
}

@keyframes slide-out {
  from {
    transform: translateX(0);
  }

  to {
    transform: translateX(-40rpx);
  }
}
</style>
