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

import { getBasicConfig } from "./Config";
import { v4 as uuidv4 } from 'uuid';
const OSS = require('ali-oss');

export const config = {
    region: 'oss-cn-hangzhou',
    accessKeyId: 'LTAI4G8RxhsSFBdmwYf6jq4U',
    accessKeySecret: 'hS4U6mytw7CW5vgUDLpIAhxjm33Lqh',
    bucket: 'ddd-nonstandar',
    secure: true //默认启用https
}

/**
 * ali-oss客户端实例
 */
export const aliOssClient = new OSS(config);

/**
 ali-oss响应

 examples:
 {
    "name":"1074441/95f89c80-528c-11ec-b4dd-4ba549db7aee.jpeg",
    "url":"http://ddd-nonstandar.oss-cn-hangzhou.aliyuncs.com/1074441/95f89c80-528c-11ec-b4dd-4ba549db7aee.jpeg",
    "res":{"status":200,"statusCode":200,"statusMessage":"OK",
    "headers":{"server":"AliyunOSS","date":"Wed, 01 Dec 2021 09:53:50 GMT","content-length":"0","connection":"keep-alive","x-oss-request-id":"61A7462EC4D54E39343E2EC3","etag":"\"0D155E6C9B11D2361A0DB4A2BBA70300\"","x-oss-hash-crc64ecma":"17687524894934510770","content-md5":"DRVebJsR0jYaDbSiu6cDAA==","x-oss-server-time":"35"},
    "size":0,"aborted":false,"rt":180,"keepAliveSocket":false,
    "data":{"type":"Buffer","data":[]},"requestUrls":["http://ddd-nonstandar.oss-cn-hangzhou.aliyuncs.com/1074441/95f89c80-528c-11ec-b4dd-4ba549db7aee.jpeg"],"timing":null,"remoteAddress":"47.110.23.21","remotePort":80,"socketHandledRequests":1,"socketHandledResponses":1}
}
 */

/**
 * ali-oss响应
 */
export class AliOssResponse {
    name: string;
    url: string;
    res: {
        status: number;
        statusCode: number;
        statusMessage: string;
    };
}

/**
 * 上传base64图片到ali-oss，自动过滤base64头信息
 * @param base64ImageStr base64图片字符串
 */
export async function putBase64Image(base64ImageStr: string): Promise<AliOssResponse> {
    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');
    }

    let fileName = `/${getBasicConfig().tapdId}/${uuidv4()}.${extension || 'jpg'}`;
    
    return await aliOssClient.put(fileName, buffer);
}