const OSS = require('ali-oss')
const router = require('@/router');
const Minio = require('minio')
const stream = require('stream')
import Vue from 'vue'
const { GenerateSTS, GetObjectStoreToken } = require('../api/user.js')
import { getToken } from '@/utils/auth'

Vue.prototype.OSSclientConfig = {
}

function blobToBuffer(blob, fileName) {
  return new Promise((resolve, reject) => {
    const file = new File([blob], fileName);
    resolve(file)
  })
}

async function ossGenerateSTS() {
  let res = await GetObjectStoreToken()
  Vue.prototype.OSSclientConfig = { ...res.Result[res.Result.ObjectStoreUse] }
  Vue.prototype.OSSclientConfig.ObjectStoreUse = res.Result.ObjectStoreUse;
  Vue.prototype.OSSclientConfig.basePath = Vue.prototype.OSSclientConfig.viewEndpoint
  switch (res.Result.ObjectStoreUse) {
    case 'AliyunOSS':
      Vue.prototype.OSSclientConfig.bucket = Vue.prototype.OSSclientConfig.bucketName
      Vue.prototype.OSSclientConfig.timeout = 10 * 60 * 1000
      let OSSclient = new OSS(Vue.prototype.OSSclientConfig)
      Vue.prototype.OSSclient = {
        put: function (objectName, object, timestamp = true) {
          return new Promise(async (resolve, reject) => {
            try {
              let _vm = router.default.app
              if (_vm._route.path !== '/trials/trials-panel/visit/crc-upload' && timestamp) {
                var objectItem = objectName.split('/')
                objectItem[objectItem.length - 1] = new Date().getTime() + '_' + objectItem[objectItem.length - 1]
                objectName = objectItem.join('/')
              }
              let res = await OSSclient.put(objectName, object)
              if (res && res.url) {
                resolve({
                  name: objectName,
                  url: res.url
                })
              } else {
                reject()
              }
            } catch (e) {
              console.log(e)
              reject()
            }
          })
        }
      }
      break
    case 'MinIO':
      let minioClient = new Minio.Client(Vue.prototype.OSSclientConfig);
      Vue.prototype.OSSclient = {
        put: function (objectName, object, timestamp = true) {
          return new Promise(async (resolve, reject) => {
            try {
              var name = objectName.split('/')[objectName.split('/').length - 1]
              let _vm = router.default.app
              if (_vm._route.path !== '/trials/trials-panel/visit/crc-upload' && timestamp) {
                var objectItem = objectName.split('/')
                objectItem[objectItem.length - 1] = new Date().getTime() + '_' + objectItem[objectItem.length - 1]
                objectName = objectItem.join('/')
              }
              const reader = new FileReader();
              reader.onload = (ex) => {
                const bufferStream = new stream.PassThrough()
                bufferStream.end(Buffer.from(ex.target.result))
                // minioClient.bucketExists('ecgdata'
                minioClient.putObject(Vue.prototype.OSSclientConfig.bucketName, objectName, bufferStream, function (err, etag) {
                  if (err) {
                    console.log(err)
                    reject()
                  } else {
                    resolve({
                      name: objectName,
                      url: Vue.prototype.OSSclientConfig.viewEndpoint + decodeUtf8(objectName)
                    })
                  }
                })
              };
              reader.readAsArrayBuffer(object);
            } catch (e) {
              console.log(e)
            }
          })
        }
      }
      break
  }
  return
}

function decodeUtf8(bytes) {
  let str = bytes.split('?');
  let str2 = str[0].split('/');
  let name = str2[str2.length - 1];
  name = encodeURIComponent(name);
  str.shift();
  str2.pop();
  return str2.join("/") + '/' + name;
}

export const OSSclient = ossGenerateSTS
