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

import { Container } from 'typescript-ioc';
import { v4 as uuidv4 } from 'uuid';
const OSS = require('ali-oss');

/**
 * ali-oss客户端实例,依赖ioc配置config.aliOss,配置参考插件ali-oss
 */
export let aliOssClient = null;

let config = Container.getValue('config.aliOss');
if (config) aliOssClient = new OSS(config);

/**
 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 new Error(`ali-oss返回值文件地址为空,返回值:${JSON.stringify(aliOssResponse)}`);
}

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

const tapdId = Container.getValue('config.basic.tapdId');

/**
 * 上传base64图片到ali-oss
 */
export async function putBase64Image(base64ImageStr: string): Promise<AliOssResponse> {
    if (!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(`/${tapdId}/${uuidv4()}.${extension || 'jpg'}`, buffer);
}