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

import { getAliOssConfig, getBasicConfig } from "./Config";
const OSS = require('ali-oss');
let uuid = require('uuid');

/**
 * 默认配置
 */
const defaults = {
    region: 'oss-cn-hangzhou',
    accessKeyId: 'LTAI4G8RxhsSFBdmwYf6jq4U',
    accessKeySecret: 'hS4U6mytw7CW5vgUDLpIAhxjm33Lqh',
    bucket: 'ddd-nonstandar',
    secure: true //默认启用https，
}

/**
 * ali-oss配置
 */
export const config = Object.assign(defaults, getAliOssConfig());

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

export class AliOssResponse {
    name: string;
    url: string;
    res: {
        status: number;
        statusCode: number;
        statusMessage: string;
    };
}

/**
 * 上传base64图片
 * 
 * 自动过滤base64头信息
 * @param base64ImageString base64图片字符串
 */
export async function putBase64Image(base64ImageString: string): Promise<AliOssResponse> {
    let mimeType = 'image/jpg';
    let buffer = null;

    //data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAA
    if (base64ImageString.startsWith('data:')) {
        let [data, base64] = base64ImageString.split(';');

        //如果文件没有后缀名?
        let data_mimetype = data.split(':')[1];
        if (data_mimetype && data_mimetype.includes('/')) mimeType = data_mimetype;

        buffer = Buffer.from(base64.split(',')[1], 'base64');
    } else {
        buffer = Buffer.from(base64ImageString, 'base64');
    }

    let fileExtension = '.' + mimeType.split('/')[1];
    let fileName = `/${getBasicConfig().tapdId}/${uuid.v1()}${fileExtension}`;

    /**
     {"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}}
     */
    return await aliOssClientInstance.put(fileName, buffer);
}

/**
 * 如果ali-oss返回的url为空，则抛出异常
 */
// export function throwIfResponseUrlIsEmpty(response: AliOssResponse) {
//     if (!response?.url) throw `上传文件至ali-oss失败，response：${JSON.stringify(response)}`;
// }