<template>
  <div >
    <div class="of-h">
      <el-button
        size ="small"
        :icon ="loadStatus === 'loading' ?'el-icon-loading' : 'el-icon-upload'" 
        id ="mt-file-upload-button" 
        class="mt-5" 
        type ="primary"
        :disabled ="loadStatus === 'loading'">{{loadStatus|ShowButtonText}}</el-button>
      <template v-if ="value" >
        <el-button 
          size="mini" 
          icon ="document"
        >
          {{value|ShowName}}
          <el-button
          type="danger"
          class="ml-5"
          size ="mini" 
          icon ="el-icon-close" 
          @click="_updateName()"
          ></el-button>
        </el-button>
      </template>
    </div>
    <div  class="mt-10 of-h">
      <div id = "mt-file-upload-container" v-show ="load.size > 0">
        <el-progress 
          class="ts-05"
          :text-inside="true" 
          :stroke-width="18"
          :percentage="load.percent" 
          :status= "status"
        ></el-progress>
        <div class="of-h mt-5">
          <el-tag  type ="primary">{{load|ShowProgress}} | {{load|ShowSpeed}}</el-tag>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import qiniu from './qiniu'
// const isDev = process.env.NODE_ENV !== 'production'

qiniu
export default {
  props: {
    value: String,
    bucket: {
      default: 'yihuibao',
      type: String
    },
    isDev: {
      default: false,
      type: Boolean
    }
  },
  data () {
    const UUID = (Math.random() * 1000).toString().split('.')[0]

    return {
      bucketUrl: {
        yihuibao: 'http://video.medmeeting.com/',
        webbucket: 'http://on5q2lha8.bkt.clouddn.com/'
      },
      uuid: UUID,
      status: null,
      percent: 0,
      loadStatus: 'loading',
      load: {
        name: null,
        speed: '0',
        percent: 0,
        loaded: 0,
        size: 0
      },
      Authorization: 'Bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6IuWMu-WunTI2OTcwNCIsInVzZXJJZCI6IjEwMDEwMiIsInJvbGUiOiIxOyIsImNyZWF0ZWQiOjE1MDU4MDcyMDI3MjksImV4cCI6MTUwNDEwNDIzNTQzMywiaXNzIjoiaGVhbGlmZSIsImF1ZCI6IjA5OGY2YmNkNDYyMWQzNzNjYWRlNGU4MzI2MjdiNGY2In0.f-GAg0vxwuDCOQnFvC-2g9bCR_qYjEnYueV9pJ97p8Y'
    }
  },
  filters: {
    ShowButtonText (str) {
      switch (str) {
        case 'wait': return '上传文件'
        case 'loading': return '等待'
        case 'error': return '初始化失败'
        default: return
      }
    },
    ShowName (str) {
      if (str) {
        const name = str.split('/')

        return name[name.length - 1]
      }
    },
    ShowSpeed (item) {
      return `上传速度：${(+item.speed / 1024 / 1024).toFixed(2)}MB/S`
    },
    ShowProgress (item) {
      return item.size > 0 ? `${(item.loaded / 1024 / 1024).toFixed(2)}MB/${(item.size / 1024 / 1024).toFixed(2)}MB` : '等待上传'
    }
  },
  mounted () {
    if (window.plupload) {
      this.init()
    } else {
      this.$load('https://cdn.staticfile.org/plupload/2.1.9/plupload.full.min.js', this.init())
    }
  },
  methods: {
    init () {
      let url = this.isDev ? 'https://testing.medmeeting.com' : 'https://admin.medmeeting.com'

      window.setTimeout(() => {
        this.$http.get(url + '/v1/adminLogin/upToken?', {
          params: {
            bucket: this.bucket
          }
        }, {
          disableLoading: true
        }).then((res) => {
          this._changeStatus('wait')
          this.uploadInit(res.data.extra)
        }).catch((res) => {
          this._changeStatus('error')
        })
      }, 1000)
    },
    uploadInit (token) {
      let self = this

      window.Qiniu.uploader({
        runtimes: 'html5',                // 上传模式,依次退化
        browse_button: 'mt-file-upload-button',       // 上传选择的点选按钮，**必需**
        uptoken: token,                   // Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
                                            // uptoken : '<Your upload token>',
                                            // 若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        unique_names: true,               // 默认 false，key为文件名。若开启该选项，SDK为自动生成上传成功后的key（文件名）。
                                            // save_key: true,
                                            // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK会忽略对key的处理
        domain: self.bucketUrl[self.bucket], // 'http://on5q2lha8.bkt.clouddn.com/',   //bucket 域名，下载资源时用到，**必需**
        get_new_uptoken: false,           // 设置上传文件的时候是否每次都重新获取新的token
        container: 'mt-file-upload-container',           //上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: '10.2gb',           // 最大文件体积限制
        max_retries: 3,                   // 上传失败最大重试次数
        multipart: false,
        dragdrop: false,                   // 开启可拖曳上传
        drop_element: 'mt-file-upload-container',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '4mb',                // 分块上传时，每片的体积
        auto_start: true,                 // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
        init: {
          FilesAdded: function (up, files) {
            window.plupload.each(files, function (file) {
            })
          },
          BeforeUpload: function (up, file) {
            self._updateName()
            self._changeStatus('loading')
            self.status = null
                                            // 每个文件上传前,处理相关的事情
          },
          UploadProgress: function (up, file) {
            self.load = Object.assign(self.load, up.files[up.files.length - 1])
                                            // 每个文件上传时,处理相关的事情
          },
          FileUploaded: function (up, file, info) {
            console.log(up, file, info)
            self._changeStatus('wait')
            self._updateName(self.bucketUrl[self.bucket] + file.target_name)
                                            // 每个文件上传成功后,处理相关的事情
                                            // 其中 info.response 是文件上传成功后，服务端返回的json，形式如
                                            // {
                                            //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                                            //    "key": "gogopher.jpg"
                                            //  }
                                            // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html

                                            // var domain = up.getOption('domain');
                                            // var res = parseJSON(info.response);
                                            // var sourceLink = domain + res.key; 获取上传成功后的文件的Url
          },
          Error: function (up, err, errTip) {
            self.status = 'exception'
            self._changeStatus('error')
          },
          UploadComplete: function (up) {
            self._changeStatus('wait')
            self.status = 'success'
          }
        }
      })
    },
    _updateName (str = '') {
      this.$emit('input', str)
    },
    _changeStatus (str) {
      this.loadStatus = str
      this.$emit('on-change', str)
    }
  }
}
</script>
<style lang ="less">
  .el-progress{
    &.ts-05{
      .el-progress-bar__inner{
        transition: all 0.5s;
      }
    }
  }
</style>
