<template>
  <view @click="fileUpload">
    <slot></slot>
  </view>
</template>
<script>
import {upload} from '../../api/upload'
export default {
  props:{
    // uploadSuccess: {
    //   type: Function,
    //   default: null
    // },
  },
  methods:{
    fileUpload(){
      let _this = this
       uni.chooseImage({
        count:1,
        success:(res)=>{
          // debugger
          console.log(res);
          // #ifdef MP-WEIXIN
          let index =  res.tempFilePaths[0].lastIndexOf('.')
          res.name ='01'+res.tempFilePaths[0].substring(index)
          // #endif
          // #ifndef MP-WEIXIN
          res.name = res.tempFiles[0].name
          // #endif
          upload('avatar',res.name).then(result=>{
            if (result.data.code === 0) {
              _this.ossUpload(res, result.data.data);
            } else {
              uni.showToast({
                title: result.data.error || result.data.msg ,
                icon: 'none',
						    duration: 2000
              })
            } 
          })
        }
      })
    },
    ossUpload(file, ossToken) {
      let _this = this
      console.log(file,ossToken);
      // #ifndef MP-WEIXIN
      _this.bucketName = ossToken.bucket
      
      let formData = new FormData();
      formData.append('key', ossToken.dir +'/'+ file.name); //存储在oss的文件路径
      formData.append('OSSAccessKeyId', ossToken.accessid); //accessKeyId
      formData.append('policy', ossToken.policy); //policy
      formData.append('Signature', ossToken.signature); //签名
      formData.append('callback', ossToken.callback); //回调
      formData.append('success_action_status', 200); //成功后返回的操作码
      formData.append("file", file.tempFiles[0]);

      let xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open("POST", ossToken.host);
      xhr.onload = () => {
        console.log(xhr.response); //输出结果
        _this.ossUploadFinished(JSON.parse(xhr.response))
      };
      xhr.send(formData);
      // #endif
      // #ifdef MP-WEIXIN
      wx.uploadFile({
        url:ossToken.host,
        header: {
          'Content-Type': 'multipart/form-data'
        },
        filePath:file.tempFilePaths[0],
        name:'file',
        formData:{
          key:ossToken.dir +'/'+ file.name,
          OSSAccessKeyId:ossToken.accessid,
          policy:ossToken.policy,
          Signature: ossToken.signature,
          // success_action_status: '200',
        },
        success: function (res) {
          if (res.statusCode === 204) {
            let  url=ossToken.host+'/'+ossToken.dir +'/'+ file.name
            _this.ossUploadFinished(url)
          } else {
            console.log('上传失败');
          }
        },
        fail: function (err) {
          console.info(err)
        }
      })
      // #endif
    },
    ossUploadFinished(res) {
      // #ifdef MP-WEIXIN
      let data = {url : res}
      this.$emit('upload',data)
      // this.uploadSuccess(data);
      // #endif
      // #ifndef MP-WEIXIN

      if (res.code === 0) {
        console.log(res);
        // if (this.uploadSuccess) {
          let data = {
            original: res.data.name,
            fileSize: res.data.size,
            url: res.data.url,
            fileName: res.data.filename,
            bucketName: this.bucketName
          }
          // this.uploadSuccess(data);
          this.$emit('upload',data)
        // }
      } else {
        uni.showToast({
          title: res.data.error || res.data.msg ,
          icon: 'none',
          duration: 2000
        })
      }
      // #endif
    }
  }
}
</script>