<template>
  <div class="uploadFile-wrap">
    <div class="video-title-wrap">
      <span class="title">视频标题:</span>
      <textarea
        class="content"
        maxlength="30"
        placeholder="请输入视频的标题,最多30个字"
        cols="30"
        rows="10"
        v-model="videoTitle"
      ></textarea>
    </div>

    <div class="choose-video-wrap">
      <span class="title">选择视频:</span>
      <div class="content">
        <van-uploader
          :after-read="afterReadVideo"
          :before-read="beforeReadVideo"
          :max-count="1"
          multiple
          accept="video/*"
        >
          <img
            src="../../static/imgs/uploadVideo.png"
            alt=""
          >
        </van-uploader>
        <p v-show="fileVideo.name" class="video-name">视频文件名: {{fileVideo.name?fileVideo.name:'请选择文件'}}</p>
        <p v-show="!fileVideo.name">请选择需要上传的视频, 视频时长要求90秒以内</p>
      </div>
    </div>

    <div class="choose-cover-wrap">
      <span class="title">选择封面:</span>
      <div class="content">
        <van-uploader
          :after-read="afterRead"
          :before-read="beforeRead"
          :max-count="1"
          multiple
          accept="image/*"
          v-model="fileList"
          @delete="deleteImg"
        >
          <img
            src="../../static/imgs/uploadCover.png"
            alt=""
          >
        </van-uploader>
        <p v-show="fileList.length===0">图片大小建议小于5M</p>
      </div>
    </div>

    <!-- 弹窗显示上传进度条 -->
    <van-overlay :show="popupShow">
      <div class="upload-progress" v-show="circleStatus">
        <p class="popup-title">上传中</p>
        <van-circle
          v-show="circleStatus"
          v-model="currentRate"
          :rate="rate"
          :speed="100"
          :text="text"
          :color="gradientColor"
        />
        <van-button
          type="info"
          class="uploadBtn"
          @click="cancelUpload"
        >取消上传
        </van-button>
      </div>

      <div class="upload-progress" v-show="!circleStatus">
        <p class="popup-title">上传完成</p>
        <img src="../../static/imgs/upload-success-icon.png" alt="">
        <van-button
          type="info"
          class="uploadBtn"
          @click="jumpTo('/myVideos')"
        >我的视频
        </van-button>
      </div>
    </van-overlay>
    <van-button
      type="info"
      class="uploadBtn"
      :disabled="uploadStatus"
      @click="confirmUpload"
    >确认上传
    </van-button>
  </div>
</template>

<script>
import { uploadFile, createUploadVideo, uploadFileByDoctor } from '@/api/ShortVideo/ShortVideo.js'
import upLoaderImg from '../../assets/js/common/uploaderImg'
import { Toast } from 'vant'
import axios from 'axios'
export default {
  name: "UploadFile",
  inject: ['reload'],
  data() {
    return {
      timeout: '',      // 请求过期时间 默认60000
      partSize: '',     // 分片大小 默认1048576
      parallel: '',     // 上传分片数 默认5
      retryCount: '',   // 网络失败重试次数 默认3
      retryDuration: '',    // 网络失败重试间隔 2
      region: 'cn-shanghai',    // 上传视频点播服务器所在的地区
      userId: '1562055921',     // 阿里云账号ID
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: '',
      Title: "",

      //------------------------------------------
      videoTitle: "",        // 用户输入的视频标题
      popupShow: false,      // 是否显示上传进度条
      gradientColor: {
        '0%': '#ff99cc',
        '100%': '#6149f6',
      },
      rate: 0,
      circleStatus: false,
      currentRate: 0,
      uploadStatus: false,    // 视频封面图片
      file: {},               // 视频封面图片文件
      fileList: [],           // 图片文件列表
      fileVideo: {},          // 上传的视频文件
      params: {                // 上传视频归属到医生参数
        VideoId: "",
        ImgUrl: "",
        VideoTitle: ""
      }
    }
  },
  mounted() {
  },
  methods: {
    // 路由跳转
    jumpTo(){
      this.$router.push({
        name: "MyVideos"
      })
    },
    // 取消上传
    cancelUpload() {
      this.popupShow = false
      this.fileList = []
      this.file = []
      this.fileVide = {}
      this.uploadStatus = false
      location.reload();
    },
    // 加载视频文件完成的回调
    afterReadVideo(file) {
      let userData = '{"Vod": {}}'

      this.fileVideo = file.file
      this.Title = file.file.name
      // 创建阿里云视频上传对象
      this.uploader = this.createUploader()
      this.uploader.addFile(this.fileVideo, null, null, null, userData)

    },
    // 加载视频文件前的回调
    beforeReadVideo(file) {
      if (file.type.indexOf('video') === -1) {
        Toast('只允许上传视频文件')
        return false
      } else {
        return true
      }
    },

    // 删除图片
    deleteImg(e) {
      this.file = {};
    },
    // 确认上传视频封面和视频
    async confirmUpload() {
      if(!this.videoTitle.trim()) {
        Toast('请输入视频标题')
        return;
      }
      this.Title = this.Title.split('.')
      this.Title = this.videoTitle + '.' + this.Title[this.Title.length-1]
      if (this.file.name && this.fileVideo.name) {
        this.popupShow = true
        this.circleStatus = true
        this.uploadStatus = true
        this.uploader.startUpload();
        let uploadImg = await upLoaderImg(this.file)  // 使用文件上传的方法
        this.params.ImgUrl = uploadImg.ResultObject[0].AccessoryUrl
      } else {
        if (!this.file.name) {
          Toast('请选择需要上传的视频封面图片文件!')
        } else {
          Toast('请选择需要上传的视频文件!')
        }
      }
    },

    // 选择封面完成前的回调函数
    beforeRead(file) {    // 上传之前校验
      if (file.type !== 'image/png' && file.type !== 'image/jpeg' && file.type !== 'image/jpg') {
        Toast('只允许上传图片格式的文件')
        return false;
      }
      return true;
    },

    // 选择封面完成后的回调函数
    afterRead(file) {   // file为你读取成功的回调文件信息
      this.file = file.file
    },


    // 阿里云上传视频SDK
    createUploader(type) {
      let self = this
      let uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 60000,
        partSize: self.partSize || 1048576,
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        region: self.region,
        userId: self.userId,
        // 开始上传
        onUploadstarted: function (uploadInfo) {
            let createUrl = `http://linyi.natapp1.cc/api/Program/CreateUploadVideo?Title=${self.Title}`
            axios.post(createUrl).then(({ data }) => {
              let uploadAuth = data.ResultObject.UploadAuth
              let uploadAddress = data.ResultObject.UploadAddress
              let videoId = data.ResultObject.VideoId
              self.params.VideoId = videoId
              self.params.VideoTitle = self.Title
              uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
            })
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
          // console.log("上传进度: ", progress)
          // console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
          let progressPercent = Math.ceil(progress * 100)
          self.rate = progressPercent

        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
          axios.get(refreshUrl).then(({ data }) => {
            let uploadAuth = data.UploadAuth
            uploader.resumeUploadWithAuth(uploadAuth)
            // console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
          })
          self.statusText = '文件超时...'
        },
        // 全部文件上传结束
        onUploadEnd: function (uploadInfo) {
          // console.log("onUploadEnd: uploaded all the files")
          uploadFileByDoctor(self.params)
            .then(res => {
              self.fileList = []
              self.file = {}
              self.fileVideo = {}
              setTimeout(() => {
                self.uploadStatus = false
                self.circleStatus = false;
              }, 2000);
              if(!res.data.IsSuccess) {
                Toast.success(res.data.ResultMsg)
              }
            })
            .catch(err => {
              // console.log(err)
            })
        }
      })
      return uploader
    }
  },
  computed: {
    text() {
      return this.currentRate.toFixed(0) + "%"
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  font-size: 0.3rem;
  color: #000;
  width: 1.78rem;
}
.uploadFile-wrap {
  /* 视频标题 */
  .video-title-wrap {
    margin-top: 0.56rem;
    display: flex;
    .title {
      font-size: 0.3rem;
      color: #000;
      width: 1.78rem;
    }

    .content {
      flex: 1;
      margin-right: 0.4rem;
      height: 0.88rem;
      padding: 0.1rem;
    }
  }

  /* 选择视频 */
  .choose-video-wrap {
    display: flex;
    margin-top: 1rem;
    .title {
      min-width: 1.78rem;
    }
    .content {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      flex: 1;
      margin-right: 0.4rem;
    }
  }

  /* 选择封面 */
  .choose-cover-wrap {
    display: flex;
    margin-top: 1rem;
    .title {
    }
    .content {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      flex: 1;
      margin-right: 0.4rem;
    }
  }

  .van-uploader {
    // margin-top: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  img {
    width: 1.5rem;
    height: 1.5rem;
  }
  .video-name {
    display: -webkit-box;
    overflow: hidden;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
  }

  p {
    margin-top: 0.2rem;
    font-size: 0.3rem;
    color: #999999;
    text-align: left;
  }

  .uploadBtn {
    margin-top: 1rem;
    width: 3.2rem;
    height: 0.8rem;
    border-radius: 0.1rem;
  }
  .van-circle {
    display: block;
    width: 2rem !important;
    height: 2rem !important;
    margin: 0.6rem auto 0 auto;
    /deep/ .van-circle__text {
      font-size: 0.3rem;
    }
  }

  /* 弹窗显示进度条 */
  .van-overlay {
    .upload-progress {
      position: absolute;
      padding-bottom: 0.5rem;
      top: 50%;
      left: 50%;
      width: 5.88rem;
      // height: 5.2rem;
      background-color: #fff;
      transform: translate(-50%, -50%);
      img {
        display: block;
        margin: 0 auto;
        margin-top: .4rem;
      }
      .popup-title {
        margin: 0;
        text-align: center;
        font-size: 0.3rem;
        color: #000;
        padding: 0.3rem 0;
        border-bottom: 1px solid #ccc;
      }
    }
  }
}
</style>