const OSS = require('ali-oss')
const router = require('@/router');
import Vue from 'vue'
const { GetObjectStoreToken } = require('../api/user.js')

Vue.prototype.OSSclientConfig = {
}


async function ossGenerateSTS() {
  let res = null;
  if (localStorage.getItem('stsToken')) {
    res = JSON.parse(localStorage.getItem('stsToken'))
  } else {
    res = await GetObjectStoreToken()
    localStorage.setItem('stsToken', JSON.stringify(res))
  }

  // res.Result.ObjectStoreUse = 'AWS';
  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.stsToken = Vue.prototype.OSSclientConfig.securityToken
      Vue.prototype.OSSclientConfig.timeout = 10 * 60 * 1000
      let OSSclient = await RefreshClient(OSSclient)
      Vue.prototype.OSSclient = {
        put: async function (objectName, object) {
          OSSclient = await RefreshClient(OSSclient)
          return new Promise(async (resolve, reject) => {
            try {
              let _vm = router.default.app
              if (_vm._route.path !== '/trials/trials-panel/visit/crc-upload') {
                var objectItem = objectName.split('/')
                // objectItem[objectItem.length - 1] = new Date().getTime() + '_' + objectItem[objectItem.length - 1]
                objectItem[objectItem.length - 1] = `${objectItem[objectItem.length - 1].substring(
                  0,
                  objectItem[objectItem.length - 1].lastIndexOf('.')
                )}__${new Date().getTime()}${objectItem[objectItem.length - 1].substring(
                  objectItem[objectItem.length - 1].lastIndexOf('.')
                ).toLocaleLowerCase()}`
                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
  }
  return
}
// client过期刷新
async function RefreshClient(client) {
  let config = await getSTSToken(Vue.prototype.OSSclientConfig.expiration);
  if (config) {
    // config.Result.ObjectStoreUse = 'AWS'
    switch (config.Result.ObjectStoreUse) {
      case 'AliyunOSS': {
        Vue.prototype.OSSclientConfig = { ...config.Result[config.Result.ObjectStoreUse] }
        Vue.prototype.OSSclientConfig.ObjectStoreUse = config.Result.ObjectStoreUse;
        Vue.prototype.OSSclientConfig.basePath = Vue.prototype.OSSclientConfig.viewEndpoint;
        Vue.prototype.OSSclientConfig.bucket = Vue.prototype.OSSclientConfig.bucketName
        Vue.prototype.OSSclientConfig.stsToken = Vue.prototype.OSSclientConfig.securityToken
        Vue.prototype.OSSclientConfig.timeout = 10 * 60 * 1000
        return new OSS(Vue.prototype.OSSclientConfig);
      }
    }

  } else {
    return client;
  }
}
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;
}
const queue = []
let loading = false;
// 获取凭证
function getSTSToken(credentials) {
  return new Promise(async (resolve, reject) => {
    let isExpired = isCredentialsExpired(credentials);
    if (isExpired) {
      if (loading) {
        queue.push({ resolve, reject })
      }
      if (!loading) {
        loading = true;
        let res = await GetObjectStoreToken();
        loading = false;
        localStorage.setItem('stsToken', JSON.stringify(res))
        resolve(res)
        let p = queue.shift();
        while (p) {
          p.resolve(res)
          p = queue.shift();
        }
      }

    } else {
      // console.log("凭证未过期");
      resolve(false)
    }

  })
}
/**
* oss判断临时凭证是否到期。
**/
function isCredentialsExpired(credentials) {
  if (!credentials) {
    return true;
  }
  const expireDate = new Date(credentials);
  const now = new Date();
  // 如果有效期不足五分钟，视为过期。
  return expireDate.getTime() - now.getTime() <= 300000;

}

export const OSSclient = ossGenerateSTS
