<template>
  <div class="uploadVideo">
    <van-uploader
      v-model="fileList"
      @delete="onDelete"
      :after-read="afterRead"
      :disabled="disabled"
      v-bind="$attrs"
    />
    <van-progress v-if="isShow" :percentage="authProgress" />
  </div>
</template>

<script>
import { uploadVideoAuth } from '@/api/index'

export default {
  name: 'UploadVideo',
  props: { value: {} },
  data() {
    return {
      fileList: [],
      client: null,
      tempCheckpoint: null,
      result: null,
      statusText: '',
      uploader: null,
      authProgress: 0,
      endpoint: [],
      disabled: false,
      isShow: false
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (!value) {
          this.fileList = []
        }
      }
    }
  },
  methods: {
    isRepeat(arr) {
      var hash = {}
      for (var i in arr) {
        if (hash[arr[i]]) {
          return true
        }
        hash[arr[i]] = true
      }
      return false
    },
    removal(arr) {
      let newArr = []
      let obj = {}
      newArr = arr.reduce((cur, next) => {
        if (!obj[next.file.name]) {
          obj[next.file.name] = true && cur.push(next)
        }
        return cur
      }, [])
      return newArr
    },
    afterRead(file) {
      if (!file) {
        this.$toast('请上传文件')
        return
      }
      if (this.fileList.length > 1) {
        let arr = this.fileList.map(k => k.file.name)
        if (this.isRepeat(arr)) {
          this.$toast('请勿上传重复文件')
          file.message = '重复'
          this.fileList = this.removal(this.fileList)
          return
        }
      }
      this.isShow = true
      this.disabled = true
      this.$emit('fileStatus', this.isShow)
      uploadVideoAuth({ file_name: file.file.name })
        .then(response => {
          let userData = '{"Vod":{}}'
          if (this.uploader) {
            this.uploader.stopUpload()
            this.authProgress = 0
            this.statusText = ''
          }
          this.uploader = this.createUploader(file, response.auth)
          this.uploader.addFile(file.file, null, null, null, userData)
        })
        .catch(() => {
          file.status = 'failed'
          this.statusText = '获取失败'
        })
    },
    authUpload() {
      if (this.uploader !== null) {
        this.uploader.startUpload()
      }
    },
    createUploader(file, auth) {
      let self = this
      let uploaders = new window.AliyunUpload.Vod({
        timeout: 60000,
        partSize: 1048576,
        parallel: 5,
        retryCount: 3,
        region: 'cn-shanghai',
        retryDuration: 2,
        userId: '1731345321362117',
        addFileSuccess: function() {
          file.message = '添加文件成功, 等待上传...'
          self.authUpload()
        },
        onUploadstarted: function(uploadInfo) {
          uploaders.setUploadAuthAndAddress(
            uploadInfo,
            auth.upload_auth,
            auth.upload_address,
            auth.video_id
          )
          self.statusText = '文件开始上传...'
        },
        onUploadSucceed: function(uploadInfo) {
          let endpointUrl = new URL(uploadInfo.endpoint)
          let url = `${endpointUrl.protocol}//${uploadInfo.bucket}.${endpointUrl.hostname}/${uploadInfo.object}`
          self.endpoint.push({
            name: uploadInfo.file.name,
            url: url
          })
          self.isShow = false
          self.$emit('input', self.endpoint)
          self.$emit('fileStatus', self.isShow)
          self.statusText = '文件上传成功!'
          self.disabled = false
          self.authProgress = 0
          self.$toast('文件上传成功')
        },
        onUploadFailed: function() {
          self.statusText = '文件上传失败!'
          self.disabled = false
          self.isShow = false
          self.$emit('fileStatus', self.isShow)
          self.$toast('文件上传失败')
        },
        onUploadProgress: function(uploadInfo, totalSize, progress) {
          let progressPercent = Math.ceil(progress * 100)
          self.authProgress = progressPercent
          self.statusText = '文件上传中...'
        },
        onUploadTokenExpired: function() {
          self.statusText = '文件超时...'
          self.disabled = false
          self.authProgress = 0
          self.$toast('文件超时')
          self.isShow = false
          self.$emit('fileStatus', self.isShow)
        },
        onUploadEnd: function() {
          self.isShow = false
          self.$emit('fileStatus', self.isShow)
          self.statusText = '文件上传完毕'
        }
      })
      return uploaders
    },
    onDelete(value) {
      if (this.endpoint.filter(k => k.name === value.file.name).length === 0) {
        this.isShow = false
        this.disabled = false
        this.$emit('fileStatus', this.isShow)
        if (this.uploader) {
          this.uploader.stopUpload()
        }
      }
      this.endpoint = this.endpoint.filter(k => k.name !== value.file.name)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .van-uploader__upload,
::v-deep .van-uploader__preview-image {
  width: 100px;
  height: 100px;
  background-color: #eee;
  border-radius: 0;
}
::v-deep .van-uploader__upload-icon {
  color: #666;
}
.uploadVideo {
  width: 100%;
}
</style>
