/**
 * ali-oss模块
 * @date 2022-03
 * @author 何华东
 */

 import { logger } from 'mslib';
 import { IocConfigProvider } from './Config';
 import { ConfigCenterConfigProvider } from './ConfigCenter';
 import { uuid } from './Utils';
 const OSS = require('ali-oss');
 
 /**
  * ali-oss客户端实例
  * 
  * ```ts
  * import { aliOss, aliOssClient } from "refs/nslib";
  * 
  * //使用封装好的上传base64图片到ali-oss
  * let res = await aliOss.putBase64Image('data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAA...');
  * //判断返回值是否成功，返回字段多，其实判断url就够了
  * throwIfUrlIsEmpty(res);
  * let imgUrl = res.url;
  * 
  * //使用原生方法上传文件
  * let res = await aliOssClient.put(`${filename}`, buffer);
  * throwIfUrlIsEmpty(res);
  * let url = res.url;
  * ```
  * @see [ali-oss](https://www.npmjs.com/package/ali-oss)
  */
 export let aliOssClient = null;
 
 init();
 
 async function init() {
     try {
         let config = await ConfigCenterConfigProvider.getAliOssConfig();
         if (!config) return;
 
         //默认使用https文件地址
         config = Object.assign({ secure: true }, config);
         aliOssClient = new OSS(config);
 
         logger.info(`ali-oss客户端实例创建成功`);
     } catch (error) {
         logger.error('ali-oss客户端实例创建失败', error);
     }
 }
 
 /**
  * ali-oss响应类
  */
 class AliOssResponse {
     name: string;
     url: string;
     res: {
         status: number;
         statusCode: number;
         statusMessage: string;
     };
 }
 
 /**
  * 如果ali-oss响应的url为空则抛出异常
  */
 export function throwIfUrlIsEmpty(aliOssResponse: AliOssResponse) {
     throw `ali-oss返回文件地址为空,返回值:${JSON.stringify(aliOssResponse)}`;
 }
 
 const basic_config = IocConfigProvider.getBasicConfig();
 
 /**
  * 上传base64图片到ali-oss
  */
 export async function putBase64Image(base64ImageStr: string): Promise<AliOssResponse> {
     if (!basic_config?.tapdId) throw new Error(`ioc未配置基础配置tapdId`);
 
     let extension = null;
     let buffer = null;
 
     //data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAA
     if (base64ImageStr.startsWith('data:')) {
         let [header, base64] = base64ImageStr.split(';');
 
         extension = header.split(':')[1]?.split('/')[1];
         buffer = Buffer.from(base64.split(',')[1], 'base64');
     } else {
         buffer = Buffer.from(base64ImageStr, 'base64');
     }
 
     return await aliOssClient.put(`/${basic_config.tapdId}/${uuid()}.${extension || 'jpg'}`, buffer);
 }