<template>
  <view class="xd-upload-image">
    <view class="xd-upload-image__btn" @click="selectFiles">
      <slot></slot>
    </view>
  </view>
</template>

<script>
export default {
  name: "XdUploadImage",
  props:{
    url: {
      type: String,
      required: true
    },
    count: {
      type: Number,
      default: 1
    },
    size: {
      type: Number,
      default: 2 //单位：M
    },

    timeout:{
      type: Number,
      default: 10 //单位：分钟
    }
  },

  data(){
    return {
      uploadFiles: [],
      uploadFilesPromise:[],
      uploadError:[],

      //文件大小
      uiSize: 0,
    }
  },

  created() {
    this.uiSize = this.size * 1024 * 1024;
  },

  methods:{
    selectFiles(){
      if(!this.url) {
        this.$emit('onError', {code: 1000, message: '请设置上传地址'});
        if(this.$settings['isDebug']) throw new Error('请设置上传地址');
      }

      uni.chooseImage({
        count: this.count,
        success:(files)=>{
          console.log('chooseImage',files);
          this.uploadFiles = files.tempFiles;
          this.checkSize();
        },
        fail: (error) => {
          this.$emit('onError', {code: 1001, message: '选中图片失败'});
          if(this.$settings['isDebug']) throw new Error('选中图片失败');
        },
      })
    },

    checkSize(){
     this.uploadError =  this.uploadFiles.filter(item=>{
      return item.size > this.uiSize;
     });

     console.log(this.uploadFiles,this.uploadError);

     //检查出错
     if(this.uploadError.length > 0) {
       this.$emit('onError', {
         code: 1002,
         message: '上传文件大小错误',
         data:{
          files:  this.uploadError,
           max: this.uiSize
         }
       });
       if(this.$settings['isDebug']) throw new Error(`上传格式错误：${JSON.stringify(this.uploadError)},图片最大体积：${this.uiSize}`);
     }
     else{
       this.getFormData()
     }
    },

    getFormData(){
      this.$emit('onGetParams', ({header, params })=>{
        this.handleAjax(header||{},params||{});
      })
    },

    handleAjax(header,formData){
      this.uploadFilesPromise = this.uploadFiles.map(item=>{
        return this.toUpload(header,formData,item.path);
      });
      this.$xdShowLoading({});
      Promise.all(this.uploadFilesPromise)
        .then(res=>{
          res = res.filter(item=>{
            return item.statusCode === 200
          }).map(item=>{
            return JSON.parse(item.data);
          })
          if(res.length === 1) res = res[0];
          this.$emit('onSuccess', res);
          this.$xdHideLoading();
        })
        .catch(error=>{
          this.$xdHideLoading();
          this.$emit('onError', {code: 1003, message: '上传文件到服务失败', data: error});
          if(this.$settings['isDebug']) throw new Error('上传文件到服务失败');
        })
    },

    toUpload(header,formData, path){
      return new Promise((resolve, reject)=>{
        uni.uploadFile({
          url: this.url,
          header,
          formData,
          filePath: path,
          name: 'file',
          timeout:  this.timeout * 60 * 1000,
          success: (uploadFileRes) => {
            resolve(uploadFileRes)
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
