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

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

/**
 * ali-oss客户端实例
 * 
 * 如果项目已添加配置依赖[NsConfig](https://me.keytop.cn/service/config)，
 * 那么模块被加载时，从`@Value`获取`ali-oss`配置({@link ConfigCenterConfigProvider})并自动创建该实例，否则为空
 * 
 * ```ts
 * import { aliOss, aliOssClient } from "refs/nslib";
 * 
 * //非标/上传base64图片到ali-oss
 * let res = await aliOss.putBase64Image('data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAA...');
 * 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;

init();

async function init() {
    try {
        let config = await ConfigCenterConfigProvider.getAliOssConfig();
        if (!config) return;

        //默认启用安全配置secure(使用https文件地址)
        config = Object.assign({ secure: true }, config);
        aliOssClient = new OSS(config);

        logger.info(`ali-oss客户端实例创建成功`);
    } catch (error) {
        logger.error('ali-oss客户端实例创建失败', error);
    }
}

/**
 * ali-oss响应类
 */
type AliOssResponse = {
    name: string;

    /**
     * 文件地址
     */
    url: string;

    res: {
        status: number;
        statusCode: number;
        statusMessage: string;
    };
}

/**
 * 如果`ali-oss`接口返回的文件地址为空，则抛出异常
 */
export function throwIfUrlIsEmpty(aliOssResponse: AliOssResponse) {
    throw new Error(`ali-oss返回文件地址为空,返回值:${JSON.stringify(aliOssResponse)}`);
}

const basic_config = IocConfigProvider.getBasicConfig();

/**
 * 上传base64图片到ali-oss
 * 
 * 文件名：`{tapdId}/{uuid}.{extension}`
 * 
 * 需配置tapdId @see {@link Config}, 否则会抛出异常
 */
export async function putBase64Image(base64ImageStr: string): Promise<AliOssResponse> {
    if (!basic_config?.tapdId) throw new Error(`未配置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);
}