<template>
  <div>
    <uploader
      ref="uploader"
      class="uploader-example"
      :options="uploadOptions"
      :auto-start="autoStart"
      :file-status-text="fileStatusText"
      @file-complete="fileComplete"
    >
      <uploader-unsupport />
      <uploader-btn :attrs="attrs">
        选择文件
      </uploader-btn>
      <uploader-list />
    </uploader>
  </div>
</template>

<script>

  const _defaultOptions = {
    //默认不启用秒传测试
    testChunks:false,
    withCredentials:true,
  }

  export default {
    name:'TaSimpleUploader',
    props:{
      //分片上传地址
      url:{
        type:String,
      },
      //合并地址
      mergeUrl:{
        type:String,
      },
      //上传时一同提交的参数
      param:{
        type:Object,
        default:()=>{
          return {}
        },
      },
      //自定义请求头
      headers:{
        type:Object,
        default:()=>{
          return {}
        },
      },
      //上传的配置
      options:{
        type:Object,
      },
      //是否自动上传
      autoStart:{
        type:Boolean,
        default:()=>{
          return true
        },
      },
      //接收文件类型
      accept:{
        type:String,
      },
    },
    data(){
      return {
        fileStatusText:{
          success: '上传成功',
          error: '错误',
          uploading: '上传中',
          paused: '暂停',
          waiting: '等待中',
        },
      }
    },
    computed:{
      uploadOptions(){
        //添加权限验证参数
        let fixedData={... this.param}
        let param=Base.getNowPageParam()
        if(param._modulePartId_){
          fixedData._modulePartId_=param._modulePartId_
        }
        if(window.location.href ){
          fixedData.frontUrl=window.location.href
        }
        let options = {
          target: faceConfig.basePath+this.url,
          query:fixedData,
          headers: {...this.headers,'X-XSRF-TOKEN': Base.getToken('XSRF-TOKEN')},
        }
        return Object.assign(_defaultOptions,options,this.options)
      },
      attrs(){
        let attrsObj = {};
        if(this.accept){
          attrsObj.accept = this.accept;
        }
        return attrsObj;
      },
    },
    methods:{
      fileComplete(rootFile){
        if(this.mergeUrl){
          const file = rootFile.file;
          this.Base.submit(null,{
            url:this.mergeUrl,
            data:{
              filename: file.name,
              identifier: rootFile.uniqueIdentifier,
              totalSize: file.size,
              type: file.type,
            },
          }).then((data)=>{
            //上传成功后触发
            this.$emit("upload-complete",rootFile,data)
          });
        }else{
          this.$emit("upload-complete",rootFile);
        }
      },

      upload(){
        this.$refs.uploader.uploader.resume();
      },


    },
  }
</script>

