<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { createVideoUploader } from '@/utils/videoUpload'

const emit = defineEmits(['upload'])

const uploadState = reactive({
  code: -1,
  name: '',
  progress: 0,
})

const { files, uploading, addFile, stopUpload } = createVideoUploader({
  onUploadStarted(file) {
    uploadState.code = 1
    uploadState.name = file.name
    uploadState.progress = 0
  },
  onUploadProgress(_file, progress) {
    uploadState.code = 1
    uploadState.progress = progress
  },
  onUploadSucceed(file) {
    uploadState.code = 0
    uploadState.name = file.name
    uploadState.progress = 100
    emit('upload', file)
  },
  onUploadFailed(file) {
    uploadState.code = 2
    uploadState.name = file.name
  },
})

const fileChange = (e: any) => {
  const file = e.target.files[0]
  if (!file) return
  if (file.name.indexOf('.mp4') === -1) {
    ElMessage('请上传mp4格式视频')
    return
  }
  if (files.value.length) {
    stopUpload()
  }
  addFile(file)
}
</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="uploading || uploadState.code === 1">
        <el-progress style="width: 340px" :percentage="uploadState.progress" />
        <!-- <span> {{ uploadData.progress }}% </span> -->
      </div>
      <div class="error video-info" v-if="uploadState.code === 2">
        <div class="name">上传失败（请重新选择文件进行上传）</div>
      </div>
      <div class="video-info" v-if="uploadState.code === 0">
        <div class="name">{{ uploadState.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>
