<template>
  <el-col>
    <el-card>
      <el-row>
        <h2>上传视频</h2>
        <uploader
          class="uploader-example"
          :options="options"
          :auto-start="true"
          @file-added="onFileAdded"
          @file-success="onFileSuccess"
          @file-progress="onFileProgress"
          @file-error="onFileError"
        >
          <uploader-unsupport />
          <uploader-drop>
            <p>拖动视频文件到此处或</p>
            <uploader-btn :attrs="attrs">选择视频文件</uploader-btn>
          </uploader-drop>
          <uploader-list />
        </uploader>
      </el-row>
      <el-divider />
      <el-row style="position: center">
        <h2>上传封面</h2>
        <el-upload
          class="avatar-uploader"
          action="//api.reghao.cn/api/file/upload/image"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-row>
      <el-divider />
      <el-row>
        <h2>稿件信息</h2>
      </el-row>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="form.name" style="width: 70%; padding-right: 2px" placeholder="标题不能超过 50 个字符" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.desc" type="textarea" style="width: 70%; padding-right: 2px" />
        </el-form-item>
        <el-form-item label="分区">
          <el-select v-model="category" placeholder="请选择分区">
            <el-option label="区域一" value="shanghai" />
            <el-option label="区域二" value="beijing" />
          </el-select>
          <el-select v-model="childCategory" placeholder="请选择子分区">
            <el-option label="区域一" value="shanghai" />
            <el-option label="区域二" value="beijing" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="form.tags" style="width: 70%; padding-right: 2px" placeholder="多个标签之间使用英文逗号分隔" />
        </el-form-item>
        <el-form-item label="可见范围">
          <el-select v-model="scope" placeholder="选择可见范围">
            <el-option label="区域一" value="shanghai" />
            <el-option label="区域二" value="beijing" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即投稿</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-col>
</template>

<script>
import { videoCategory, submitVideoPost } from '@/api/video'
import { getVideoId } from '@/api/file'

export default {
  name: 'PublishVideo',
  data() {
    return {
      activeName: 'first',
      options: {
        target: '//api.reghao.cn/api/file/upload/video',
        chunkSize: 1024 * 1024 * 1024 * 5, // 5GiB
        fileParameterName: 'file',
        testChunks: false,
        query: (file, chunk) => {
          this.videoPost.urlObjectName = 'video/playback/' + this.videoUrlId
          return { key: this.videoPost.urlObjectName }
        },
        headers: {
        }
      },
      attrs: {
        accept: 'video/*'
      },
      rules: [
        value => !value || value.size < 2000000 || 'Avatar size should be less than 2 MB!'
      ],
      coverUrl: null,
      videoUrlId: null,
      // 提交给后端的数据
      videoPost: {
        videoFileId: null,
        urlObjectName: null,
        coverFileId: null,
        title: null,
        description: null,
        categoryId: null,
        tags: [],
        scope: 1,
        width: null,
        height: null,
        duration: null
      },
      categoryMap: {
        Set: function(key, value) { this[key] = value },
        Get: function(key) { return this[key] },
        Contains: function(key) { return this.Get(key) !== null },
        Remove: function(key) { delete this[key] }
      },
      category: [],
      childCategory: [],
      scope: [
        '所有人可见',
        '验证码可见',
        'VIP 可见',
        '仅自己可见'
      ],
      nowCategory: {},
      coverFile: null,
      showMessage: false,
      message: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      imageList: [],
      imageUrl: '',
      form: {
        videoFileId: null,
        urlObjectName: null,
        coverFileId: null,
        title: null,
        desc: null,
        categoryId: 0,
        tags: null,
        scope: 1,
        width: 0,
        height: 0,
        duration: 0
      }
    }
  },
  created() {
    this.getVideoIdWrapper()
    this.getVideoCategory()
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarSuccess(res, file) {
      this.imageList.push(file)
      console.log(this.imageList)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 选择视频后获取视频的分辨率和时长, 并截取第一秒的内容作为封面
    processVideo(file) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas')
        const canvasCtx = canvas.getContext('2d')

        const videoElem = document.createElement('video')
        const dataUrl = window.URL.createObjectURL(file)
        // 当前帧的数据是可用的
        videoElem.onloadeddata = function() {
          resolve(videoElem)
        }
        videoElem.onerror = function() {
          reject('video 后台加载失败')
        }
        // 设置 auto 预加载数据， 否则会出现截图为黑色图片的情况
        videoElem.setAttribute('preload', 'auto')
        videoElem.src = dataUrl
        // 预加载完成后才会获取到视频的宽高和时长数据
        videoElem.addEventListener('canplay', this.onCanPlay(videoElem, canvas, canvasCtx))
      })
    },
    onCanPlay(videoElem, canvas, canvasCtx) {
      setTimeout(() => {
        // 视频视频分辨率
        const videoWidth = videoElem.videoWidth
        const videoHeight = videoElem.videoHeight
        this.videoPost.width = videoWidth
        this.videoPost.height = videoHeight
        this.videoPost.duration = videoElem.duration

        videoElem.pause()
        /* const ratio = window.devicePixelRatio || 1
        canvasCtx.scale(ratio, ratio)*/
        // 设置画布尺寸
        canvas.width = videoWidth
        canvas.height = videoHeight
        canvasCtx.drawImage(videoElem, 0, 0, canvas.width, canvas.height)
        // 把图标base64编码后变成一段url字符串
        const urlData = canvas.toDataURL('image/jpeg')
        if (typeof urlData !== 'string') {
          alert('urlData不是字符串')
          return
        }

        var arr = urlData.split(',')
        var bstr = atob(arr[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const coverFile = new File([u8arr], 'cover.jpg', { type: 'image/jpeg' })

        if (coverFile instanceof File) {
          const formData = new FormData()
          formData.append('file', coverFile)
          fetch(`//api.reghao.cn/api/file/upload/image`, {
            headers: {},
            method: 'POST',
            credentials: 'include',
            body: formData
          }).then(response => response.json())
            .then(json => {
              if (json.code === 0) {
                this.videoPost.coverFileId = json.data.imageFileId
                this.imageUrl = json.data.imageUrl
              } else {
                this.message = '视频封面上传失败，请重试！' + json.message
                this.showMessage = true
              }
            })
            .catch(e => {
              return null
            })
        }
      }, 1000) // 1000毫秒，就是截取第一秒，2000毫秒就是截取第2秒，视频1秒通常24帧，也可以换算成截取第几帧。
      // 防止拖动进度条的时候重复触发
      // videoElem.removeEventListener('canplay', arguments.callee)
    },
    onFileAdded(file) {
      this.setTitle(file.file.name)
      this.processVideo(file.file)
      /* file.pause()
      hashFile(file.file).then(res => {
        const formData = new FormData()
        formData.append('filename', file.file.name)
        formData.append('size', file.file.size)
        formData.append('sha256sum', res.sha256sum)
        fetch(`//file.reghao.cn` + `/api/file/upload/video/prepare`, {
          headers: {
            Authorization: 'Bearer ' + this.$store.getters.token
          },
          method: 'POST',
          credentials: 'include',
          body: formData
        }).then(response => response.json())
          .then(json => {
            const uploadId = json.data.uploadId
            const exist = json.data.exist
            if (exist) {
              this.message = '视频已存在'
              this.showMessage = true
              file.cancel()
            } else {
              file.uniqueIdentifier = uploadId
              file.resume()
            }
          })
          .catch(e => {
            return null
          })
      })*/
    },
    onFileProgress(rootFile, file, chunk) {
    },
    onFileSuccess(rootFile, file, response, chunk) {
      const res = JSON.parse(response)
      if (res.code === 0) {
        this.message = '视频已上传'
        this.showMessage = true
      }
    },
    onFileError(rootFile, file, response, chunk) {
      console.log('文件上传错误')
    },
    publish() {
      if (!this.videoPost.videoFileId) {
        this.message = '你还没有上传视频'
        this.showMessage = true
        return
      }

      if (!this.videoPost.coverFileId) {
        this.message = '你还没有上传视频封面'
        this.showMessage = true
        return
      }

      if (this.videoPost.title === '' || this.videoPost.categoryId === -1) {
        this.message = '分区和稿件标题不能为空'
        this.showMessage = true
        return
      }

      /* if (this.videoPost.scope === null) {
        this.message = '稿件可见范围不能为空'
        this.showMessage = true
        return
      }*/

      if (this.videoPost.tags.length === 0 || this.videoPost.tags.length > 10) {
        this.message = '标签最少 1 个, 最多 10 个'
        this.showMessage = true
        return
      }

      submitVideoPost(this.videoPost)
        .then(res => {
          if (res.code === 0) {
            this.message = '投稿成功,等待审核通过后其他人就可以看到你的视频了'
            this.showMessage = true
            this.$router.push('/studio')
          } else {
            this.message = res.msg
            this.showMessage = true
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    },
    setFile(value) {
      this.coverFile = value
    },
    setTitle(title) {
      if (title.length > 50) {
        this.videoPost.title = title.substring(0, 50)
        this.videoPost.description = title
      } else {
        this.videoPost.title = title
      }
    },
    /* uploadVideoCover() {
      if (this.coverFile === null) {
        this.message = '请先选择视频封面，然后上传！'
        this.showMessage = true
        return
      }

      if (this.videoPost.videoFileId === null) {
        this.message = '等待视频上传完成后再上传封面！'
        this.showMessage = true
        return
      }

      const formData = new FormData()
      formData.append('videoFileId', this.videoPost.videoFileId)
      formData.append('file', this.coverFile)
      fetch(`//api.reghao.cn/api/file/upload/video/cover`, {
        headers: {
          'Authorization': 'Bearer ' + this.$store.getters.token
        },
        method: 'POST',
        credentials: 'include',
        body: formData
      }).then(response => response.json())
        .then(json => {
          if (json.code === 0) {
            this.message = '封面已上传'
            this.showMessage = true
            this.videoPost.coverFileId = json.data.imageFileId
            this.videoPost.imageUrl = json.data.imageUrl
          } else {
            this.message = '上传失败，请重试！' + json.message
            this.showMessage = true
          }
        })
        .catch(e => {
          return null
        })
    },*/
    getVideoCategory() {
      videoCategory()
        .then(res => {
          if (res.code === 0) {
            for (let i = 0; i < res.data.length; i++) {
              const name = res.data[i].name
              this.category.push(name)
              this.categoryMap.Set(name, res.data[i])
            }
          } else {
            console.error(res.msg)
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    },
    getCategory(name) {
      // 重置子分区，清除前一次选择分区时留下的缓存
      this.childCategory = []
      this.currentCategory = this.categoryMap.Get(name)
      this.videoPost.categoryId = this.currentCategory.id

      const c = this.currentCategory.children
      if (c) {
        for (let i = 0; i < c.length; i++) {
          this.childCategory.push(c[i].name)
        }
      }
    },
    getChildCategory(name) {
      const c = this.currentCategory.children
      for (let i = 0; i < c.length; i++) {
        if (c[i].name === name) {
          this.videoPost.categoryId = c[i].id
        }
      }
    },
    setVideoScope(scope) {
      if (scope === '所有人可见') {
        this.videoPost.scope = 1
      } else if (scope === '验证码可见') {
        this.videoPost.scope = 2
      } else if (scope === 'VIP 可见') {
        this.videoPost.scope = 3
      } else if (scope === '仅自己可见') {
        this.videoPost.scope = 4
      }
    },
    getVideoIdWrapper() {
      getVideoId(this.videoPost)
        .then(res => {
          if (res.code === 0) {
            console.log(res.data)
            this.videoPost.videoFileId = res.data.videoFileId
            this.videoUrlId = res.data.videoUrlId
          } else {
            this.message = res.msg
            this.showMessage = true
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    },
    onSubmit() {
      console.log('submit!')
    }
  }
}
</script>

<style>
.uploader-example {
  width: 500px;
  padding: 15px;
  margin: 40px auto 0;
  font-size: 12px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .4);
}
.uploader-example .uploader-btn {
  margin-right: 4px;
}
.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 320px;
  height: 240px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 320px;
  height: 240px;
  display: block;
}
</style>
