<template>
  <div>
    <file-pond
      ref="pond"
      name="file"
      label-idle="选择视频或者拖动视频到此处"
      label-file-processing="视频正在上传，请稍后"
      label-file-processing-aborted="视频上传被取消"
      label-tap-to-retry="尝试重试"
      label-file-processing-complete="视频上传成功！"
      accepted-file-types="video/*, .flv, .mkv"
      :allow-multiple="false"
      :instant-upload="true"
      :server="server"
      :files="myFiles"
      @init="handleFilePondInit"
      @processfile="success"
    />
  </div>
</template>

<script>
// Import Vue FilePond
import vueFilePond from 'vue-filepond'
// Import FilePond styles
import 'filepond/dist/filepond.min.css'
// Import FilePond plugins
// Please note that you need to install these plugins separately
// Import image preview plugin styles
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css'
// Import image preview and file type validation plugins
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type'
import FilePondPluginImagePreview from 'filepond-plugin-image-preview'

import CryptoJS from 'crypto-js'

// Create component
const FilePond = vueFilePond(FilePondPluginFileValidateType, FilePondPluginImagePreview)

let videMessage = {}

export default {
  name: 'FilePondUpdate',
  components: {
    FilePond
  },
  videMessage,
  data() {
    return {
      videMessage: {},
      myFiles: [],
      server: {
        url: '/api/file/upload/video',
        process: {
          headers: {
            'X-XSRF-TOKEN': this.$cookies.get('XSRF-TOKEN')
          },
          ondata: (formData) => {
            // TODO 根据登录状态获取 userId
            formData.append('userId', 1101269176320)
            return formData
          },
          onload(res) {
            var resp = JSON.parse(res)
            // 返回上传数据
            videMessage = resp
          }
        }
      }
    }
  },
  created() {
  },
  methods: {
    handleFilePondInit() {
      console.log('FilePond has initialized')
      // FilePond instance methods are available on `this.$refs.pond`
    },
    success() {
      this.$emit('video', videMessage)
    },
    cancelUpload() {
      console.log('取消上传的文件')
    },
    // TODO 计算文件的 sha256 值，然后传递给后端做判断后再确定是否需要上传文件
    uploadCrt(param) {
      var contractFile = param.file
      var reader = new FileReader(); var self = this
      var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice
      var chunkSize = 6 * 1024 * 1024
      var chunks = Math.ceil(contractFile.size / chunkSize)
      var currentChunk = 0
      var hasher = CryptoJS.algo.SHA256.create()
      var start = currentChunk * chunkSize
      var end = start + chunkSize >= contractFile.size ? contractFile.size : start + chunkSize
      reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end))
      reader.onload = function(evt) {
        var fileStr = evt.target.result
        var tmpWordArray = self.arrayBufferToWordArray(fileStr)
        hasher.update(tmpWordArray)
        currentChunk += 1
        fileStr = null
        tmpWordArray = null
        if (currentChunk < chunks) {
          var start = currentChunk * chunkSize
          var end = start + chunkSize >= contractFile.size ? contractFile.size : start + chunkSize
          reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end))
        }
      }
      reader.onloadend = function() {
        contractFile = null
        var hash = hasher.finalize()
        hash.toString()// 计算结果
        hasher = null
        blobSlice = null
        reader = null
        hash = null
      }
    },
    arrayBufferToWordArray(ab) {
      var i8a = new Uint8Array(ab)
      var a = []
      for (var i = 0; i < i8a.length; i += 4) {
        a.push(i8a[i] << 24 | i8a[i + 1] << 16 | i8a[i + 2] << 8 | i8a[i + 3])
      }
      return CryptoJS.lib.WordArray.create(a, i8a.length)
    }
  }
}
</script>
