<script setup lang="ts">
import { getCreateAuth, updateAuth } from '@/api/base'
import { ElMessage } from 'element-plus'
/**
 * upload 上传状态  {code: -1（待上传）0(成功) 1(开始上传) 2(上传失败), msg: '上传信息'}
 * progress 上传进度
 **/
interface IUpload {
  code: number
  name?: string
  msg?: string
  progress?: number
  videoId?: string
}
let uploadData = $ref<IUpload>({ code: -1 })

const emit = defineEmits(['upload'])
const form: any = reactive({
  timeout: '',
  partSize: '',
  parallel: '',
  retryCount: '',
  retryDuration: '',
  region: 'cn-shanghai',
  userId: '1303984639806000',
  file: null,
  authProgress: 0,
  uploader: null,
  statusText: ''
})
const fileChange = (e: any) => {
  form.file = e.target.files[0]
  if (form.file.name.indexOf('.mp4') === -1) {
    ElMessage('请上传mp4格式视频')
    return
  }
  var userData = '{"Vod":{}}'
  if (form.uploader) {
    form.uploader.stopUpload()
    form.authProgress = 0
    form.statusText = ''
  }
  form.uploader = createUploader()
  form.uploader.addFile(form.file, null, null, null, userData)
  form.uploader.startUpload()
}

const createUploader: any = () => {
  const w = window as any
  const uploader = new w.AliyunUpload.Vod({
    timeout: form.timeout || 60000,
    partSize: form.partSize || 1048576,
    parallel: form.parallel || 5,
    retryCount: form.retryCount || 3,
    retryDuration: form.retryDuration || 2,
    region: form.region,
    userId: form.userId,
    // 开始上传
    onUploadstarted: function (uploadInfo: any) {
      const fileData = JSON.parse(window.localStorage.fileData || '{}')
      // 判断有没有上传过
      const isFile = !!fileData.sourceId
      if (!isFile) {
        // 没上传过请求凭证上传
        getCreateAuth({ title: uploadInfo.file.name, file_name: uploadInfo.file.name }).then((data: any) => {
          window.localStorage.fileData = JSON.stringify({
            uploadAuth: data.data.upload_auth,
            uploadAddress: data.data.upload_address,
            videoId: data.data.source_id,
            fileName: uploadInfo.file.name,
            fileSize: uploadInfo.file.size
          })
          uploader.setUploadAuthAndAddress(
            uploadInfo,
            data.data.upload_auth,
            data.data.upload_address,
            data.data.source_id
          )
        })
      } else {
        // 上传过判断一下上次上传的文件和本次上传的文件一不一样，一样的话继续上传
        if (fileData.fileName === uploadInfo.file.name && fileData.fileSize === uploadInfo.file.size) {
          uploader.setUploadAuthAndAddress(uploadInfo, fileData.uploadAuth, fileData.uploadAddress, fileData.videoId)
        } else {
          getCreateAuth({ title: uploadInfo.file.name, file_name: uploadInfo.file.name }).then((data: any) => {
            uploader.setUploadAuthAndAddress(
              uploadInfo,
              data.data.upload_auth,
              data.data.upload_address,
              data.data.source_id
            )
          })
        }
      }
      uploadData = {
        code: 1,
        name: uploadInfo.file.name,
        msg: '开始上传'
      }
    },
    // 文件上传成功
    onUploadSucceed: function (uploadInfo: any) {
      const fileData = window.localStorage.fileData ? JSON.parse(window.localStorage.fileData) : {}
      uploadData = {
        code: 0,
        name: uploadInfo.file.name,
        videoId: fileData.videoId,
        msg: '上传成功'
      }
      emit('upload', { videoId: fileData.videoId, name: uploadInfo.file.name })
    },
    // 文件上传失败
    // code:any, message:any
    onUploadFailed: function (uploadInfo: any) {
      uploadData = {
        code: 2,
        name: uploadInfo.file.name,
        msg: '文件上传失败'
      }
    },
    // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
    onUploadProgress: function (uploadInfo: any, totalSize: any, progress: any) {
      let progressPercent = Math.ceil(progress * 100)
      form.authProgress = progressPercent
      uploadData.progress = progressPercent
    },
    // 上传凭证超时
    onUploadTokenExpired: function (uploadInfo: any) {
      const fileData = JSON.parse(window.localStorage.fileData || '{}')
      updateAuth({ source_id: fileData.videoId }).then(({ data }) => {
        let uploadAuth = data.UploadAuth
        window.localStorage.fileData = JSON.stringify({
          uploadAuth: data.data.upload_auth,
          uploadAddress: data.data.upload_address,
          videoId: data.data.source_id,
          fileName: uploadInfo.file.name,
          fileSize: uploadInfo.file.size
        })
        uploader.resumeUploadWithAuth(uploadAuth)
      })
    }
  })
  return uploader
}
</script>
<template>
  <div>
    <div class="upload-video">
      <div class="upload-btn">
        本地文件
        <!-- accept=".mp4" -->
        <input accept=".mp4" type="file" id="fileUpload" @change="fileChange($event)" />
      </div>
      <div class="demo-progress" v-if="uploadData.code === 1">
        <el-progress style="width: 340px" :percentage="uploadData.progress" />
        <!-- <span> {{ uploadData.progress }}% </span> -->
      </div>
      <div class="error video-info" v-if="uploadData.code === 2">
        <div class="name">上传失败（请重新选择文件进行上传）</div>
      </div>
      <div class="video-info" v-if="uploadData.code === 0">
        <div class="name">{{ uploadData.name }}</div>
      </div>
    </div>
    <div class="tips">推荐视频格式：帧率为25fps\输出码率为4M\输出格式为mp4，建议采用格式工厂等工具处理后上传。</div>
  </div>
</template>
<style lang="scss">
.demo-progress {
  width: 350px;
  display: flex;
  span {
    color: #999999;
    font-size: 14px;
    transform: translateX(-20px);
  }
}
#fileUpload {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0.00001;
}
.tips {
  font-size: 12px;
  line-height: 100%;
  color: #999999;
  margin-top: 8px;
}
.upload-video {
  display: flex;
  align-items: center;
  .upload-btn {
    position: relative;
    width: 94px;
    line-height: 36px;
    background: rgba(250, 223, 230, 0.39);
    border: 1px solid #aa1941;
    border-radius: 20px;
    font-size: 14px;
    color: #aa1941;
    margin-right: 30px;
    text-align: center;
  }
  .video-info {
    display: flex;
    .name {
      color: #333333;
      font-size: 16px;
      line-height: 100%;
    }
    .view {
      font-size: 16px;
      line-height: 100%;
      color: #399ee8;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}
</style>
