<template>
  <v-row justify="center" align="center">
    <v-col>
      <v-card
        class="mx-auto"
        outlined
      >
        <v-row justify="center">
          <v-col cols="10">
            <h2>发布视频贴</h2>
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col>
            <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>
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="5">
            <v-card outlined>
              <v-img :src="videoPost.imageUrl" aspect-ratio="1.77" contain max-height="150" alt="封面图，推荐16：9" />
            </v-card>
          </v-col>
          <v-col cols="5">
            <v-file-input
              :rules="rules"
              accept="image/png, image/jpeg, image/bmp"
              prepend-icon="mdi-image"
              placeholder="上传视频封面"
              label="封面"
              @change="setFile"
            />
            <v-btn color="primary" @click="uploadVideoCover">
              上传
            </v-btn>
          </v-col>
        </v-row>
        <v-divider />
        <v-row justify="center">
          <v-col cols="10">
            <h2>稿件信息</h2>
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="5">
            <v-select
              :items="category"
              label="分区"
              @change="getCategory"
            />
          </v-col>
          <v-col cols="5">
            <v-select
              :items="childCategory"
              label="子分区"
              @change="getChildCategory"
            />
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="10">
            <v-text-field
              v-model="videoPost.title"
              placeholder="标题"
              label="标题(50字以内)"
              clearable
            />
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="10">
            <v-textarea
              v-model="videoPost.description"
              label="简介(200字以内)"
              clearable
              placeholder="填写更全面的视频信息，让更多的人找到你！"
            />
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="10">
            <v-combobox
              v-model="videoPost.tags"
              label="添加标签让更多人找到你（最多6个）"
              multiple
              chips
              clearable
            />
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="10">
            <v-select
              :items="scope"
              label="可见范围"
              @change="setVideoScope"
            />
          </v-col>
        </v-row>
        <v-row justify="center">
          <v-col cols="10">
            <v-btn large color="primary" @click="publish">立即投稿</v-btn>
          </v-col>
        </v-row>
      </v-card>
    </v-col>

    <v-snackbar
      v-model="showMessage"
      :top="true"
      :timeout="3000"
    >
      {{ message }}
      <template v-slot:action="{ attrs }">
        <v-btn
          color="pink"
          text
          v-bind="attrs"
          @click="showMessage = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-row>
</template>

<script>
import { videoCategory, submitVideoPost } from '@/api/media/video'
/* import { hashFile } from '@/utils/hash' */

export default {
  data() {
    return {
      options: {
        target: '//api.reghao.cn' + '/api/file/upload/video',
        chunkSize: 1024 * 1024 * 1024 * 5, // 分片大小 5GiB
        forceChunkSize: true,
        fileParameterName: 'file',
        maxChunkRetries: 3,
        testChunks: true,
        checkChunkUploadedByResponse: function(chunk, message) {
          const objMessage = JSON.parse(message)
          console.log('分片文件检验')
          console.log(objMessage)
          if (objMessage.skipUpload) {
            return true
          }

          return (objMessage.uploaded || []).indexOf(chunk.offset + 1) >= 0
        },
        headers: {
          Authorization: 'Bearer ' + this.$store.getters.token
        }
      },
      attrs: {
        accept: 'video/*'
      },
      rules: [
        value => !value || value.size < 2000000 || 'Avatar size should be less than 2 MB!'
      ],
      // 提交给后端的数据
      videoPost: {
        videoFileId: null,
        coverFileId: null,
        title: null,
        description: null,
        categoryId: null,
        tags: [],
        scope: 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: ''
    }
  },
  created() {
    this.getVideoCategory()
  },
  methods: {
    onFileAdded(file) {
      this.setTitle(file.file.name)

      /* 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) {
        const resData = res.data
        if (resData.merged) {
          this.message = '视频已上传'
          this.showMessage = true
          this.videoPost.videoFileId = resData.videoFileId
        }
      }
    },
    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)
      } 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
      }
    }
  }
}
</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;
  }
</style>
