/**
 * 统一国际化/翻译接口模块
 * 
 * https://pan.keytop.cn:8088/project/677/interface/api/4553
 */

import Axios, { AxiosInstance } from "axios";
import { logger } from "mslib";
import { CryptoUtils, DateUtils, uuid, throwApiErrorFromAxiosError } from "refs/nslib";
import { Singleton } from "typescript-ioc";

/**
 * 统一翻译接口客户端
 */
@Singleton
export default class TyGlobalApiClient {
    /**
     * 获取指定资源
     * 
     * https://pan.keytop.cn:8088/project/677/interface/api/4553
     */
    async get(request: GetRequest): Promise<ApiResponse<GetResponse>> {
        request['reqId'] = uuid();
        request['ts'] = DateUtils.getUnixTimestamp();
        request['sign'] = CryptoUtils.md5(`${request.token}${request['reqId']}${request['ts']}`);

        let axiosResponse = await axiosInstance.post('/ktms-api/api/get', request);
        throwIfResultCodeNoSuccess(axiosResponse.data);

        return axiosResponse.data;
    }

    /**
     * 获取所有资源
     * 
     * https://pan.keytop.cn:8088/project/677/interface/api/4547
     */
    async fetch(request: FetchRequest): Promise<ApiResponse<GetResponse>> {
        let axiosResponse = await axiosInstance.post('/ktms-api/api/fetch', request);
        return axiosResponse.data;
    }
}

export class ApiResponse<T = any> {
    constructor(resultCode: number) {
        this.resultCode = resultCode;
    }

    /**
     * 错误码，200操作成功；其他，操作失败
     */
    resultCode?: number;

    /**
     * 提示信息
     */
    resultMsg?: string;

    data?: T;

    /**
     * 判断响应码是否为成功
     */
    static resultCodeIsSuccess(resultCode: number) {
        return resultCode === 200;
    }
}

export function throwIfResultCodeNoSuccess(apiResponse: ApiResponse) {
    if (!ApiResponse.resultCodeIsSuccess(apiResponse.resultCode)) {
        throw new Error(`统一翻译接口返回错误,返回值:${JSON.stringify(apiResponse)}`);
    }
}

/**
 * 语言包分类,上游系统接口是这么设计的
 */
export enum Token {
    /**
     * 标准-后端
     */
    keytop_nkc_pro_sg = 'keytop_nkc_pro_sg',

    /**
     * 标准-场端/云端c++
     */
    keytop_charge_pro_sg = 'keytop_charge_pro_sg',

    /**
     * 非标/计费
     */
    nonstandard_callfee = '94505439ee1d4fe7853851a75907fa8b',

    /**
     * 非标/后端
     */
    nonstandard_back_end = 'e344d0c953c6023ffd30b14efc46fcbd',

    /**
     * 非标/前端
     */
    nonstandard_front_end = '0c9b6bca050980a891b5d90495c08c20'
}

export type Language = 'zh_CN' | 'en_US';

export class GetRequest {
    /**
     * token
     */
    token: Token;

    /**
     * 语言（符合i18n规范）
     */
    language?: Language;

    /**
     * 翻译类型 1-文本、2-图片、3-声音
     */
    type: 1 | 2 | 3;
}

export class GetResponse {
    /**
     * 语言（符合i18n规范）
     */
    language: string;

    /**
     * 翻译类型 1-文本、2-图片、3-声音
     */
    type: 1 | 2 | 3;

    data: {
        /**
         * i18n-中文简体value
         */
        cn: string;

        /**
         * i18n-key
         */
        key: string;

        /**
         * i18n-value
         */
        value: string;

        language: string;
    }[]
}

export class FetchRequest {
    reqId: string;
    sign: string;
    ts: number;
    token: Token;
}

function generateAxiosInstance() {
    const axiosInstance = Axios.create({
        baseURL: 'https://gpark.keytop.cn',
        timeout: 10000,
    });

    axiosInstance.interceptors.request.use(config => {
        config.headers['Content-Type'] = 'application/json';
        return config;
    }, error => {
        throwApiErrorFromAxiosError(error, '统一翻译接口');
    });

    axiosInstance.interceptors.response.use(response => {
        logger.info(`统一翻译接口${response.config['apiDesc'] || response.config.url}调用成功,请求地址:${response.config.baseURL + response.config.url},请求参数:${response.config.data},返回值:${JSON.stringify(response.data)}`);

        return response;
    }, error => {
        throwApiErrorFromAxiosError(error, '统一翻译接口');
    });

    return axiosInstance;
}

export let axiosInstance: AxiosInstance = generateAxiosInstance();

export { TyGlobalApiClient }