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

import { logger } from 'mslib';
import { IocConfigProvider } from './Config';
import { ConfigCenterConfigProvider } from './ConfigCenter';
import { IS_DEBUG, IS_PROD } from './Contants';
import { uuid } from './Utils';
const OSS = require('ali-oss');

/**
 * 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响应类
 */
export 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)}`;
}

/**
 * 获取base64字符串的源文件大小
 */
export function getBase64StringFileSize(base64String: string) {
    return (4 * Math.ceil((base64String.length / 3)) * 0.5624896334383812) / 1000;
}

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);
}