<template>
  <uploader :options="options" :file-status-text="statusText" :autoStart="false" class="uploader-example" ref="uploader"
            @file-complete="fileComplete" @complete="complete">
    <uploader-unsupport></uploader-unsupport>
    <uploader-drop>
      <p>Drop files here to upload or</p>
      <uploader-btn>select files</uploader-btn>
      <uploader-btn :attrs="attrs">select images</uploader-btn>
      <uploader-btn :directory="true">select folder</uploader-btn>
    </uploader-drop>
    <uploader-list></uploader-list>
  </uploader>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import { getAction, postAction } from '@/api/manage'
import qs from 'qs'

export default {
  data() {
    return {
      options: {
        target: window._CONFIG['domianURL'] + '/sys/uploader/chunk',
        testChunks: true,
        simultaneousUploads: 1,
        chunkSize: 9 * 1024 * 1024,
        headers: function() {
          const headers = {}
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token) {
            headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
          }
          //update-begin-author:taoyan date:2020707 for:多租户
          let tenantid = Vue.ls.get(TENANT_ID)
          if (!tenantid) {
            tenantid = 0
          }
          headers['tenant-id'] = tenantid
          return headers
        }
      },
      attrs: {
        accept: 'image/*'
      },
      statusText: {
        success: '成功',
        error: '出错',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      }
    }
  },
  methods: {
    // 上传完成
    complete() {
      console.log('complete', arguments)
    },
    // 一个根文件（文件夹）成功上传完成。
    fileComplete() {
      console.log('file complete', arguments)
      const file = arguments[0].file
      postAction('/sys/uploader/mergeFile', qs.stringify({
        filename: file.name,
        identifier: arguments[0].uniqueIdentifier,
        totalSize: file.size,
        type: file.type
      })).then(function(response) {
        console.log(response)
      }).catch(function(error) {
        console.log(error)
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      window.uploader = this.$refs.uploader.uploader
    })
  }
}
</script>