import http from "@ohos:net.http";
export class CLNetContanst {
    // 测试环境
    // private static readonly BASE_URL  = 'http://wanshu-dev.cm253.com'
    // 生产环境
    private static readonly BASE_URL = 'https://wsapi.253.com';
    private static readonly OCR_IDCARD = '/identity_auth/ocr/new/idCard/v3'; //单面识别
    private static readonly OCR_IDCARD_DOUBLE = '/identity_auth/ocr/new/idCard/doubleSide/v3'; //双面识别
    private static readonly OCR_IDCARDAUTH = '/identity_auth/idCardAuth/v3'; //身份证校验
    private static readonly kPostRandomCode = "/identity_auth/faceAlive/v3/actions";
    private static readonly kPostFaceVideo = "/identity_auth/faceAlive/v3/videoVerify";
    private static readonly kPostFaceImage = "/identity_auth/faceAlive/v3/imageVerify";
    static getOCRIdcard() {
        return CLNetContanst.BASE_URL + CLNetContanst.OCR_IDCARD;
    }
    static getOCRIdcardDouble() {
        return CLNetContanst.BASE_URL + CLNetContanst.OCR_IDCARD_DOUBLE;
    }
    static getOCRIdcardAuth() {
        return CLNetContanst.BASE_URL + CLNetContanst.OCR_IDCARDAUTH;
    }
    static getPostRandomCode() {
        return CLNetContanst.BASE_URL + CLNetContanst.kPostRandomCode;
    }
    static getPostFaceVideo() {
        return CLNetContanst.BASE_URL + CLNetContanst.kPostFaceVideo;
    }
    static getPostFaceImage() {
        return CLNetContanst.BASE_URL + CLNetContanst.kPostFaceImage;
    }
}
export const enum ContentType {
    JSON = "application/json",
    TEXT_HTML = "text/html",
    TEXT_PLAIN = "text/plain",
    FORM_URLENCODED = "application/x-www-form-urlencoded",
    FORM_DATA = "multipart/form-data"
}
// 请求配置
export interface CLRequestOption {
    path: string;
    method: http.RequestMethod;
    data?: string | Object | ArrayBuffer;
    header?: Record<string, string>;
}
export class CLNetworkManager {
    private baseUrl: string = '';
    private readTimeout: number = 10000;
    private connectTimeout: number = 10000;
    private defaultHeaders: Record<string, string> = {
        'Content-Type': "application/json"
    };
    setBaseURL(url: string): void {
        this.baseUrl = url;
    }
    setReadTimeout(timeout: number): void {
        this.readTimeout = timeout;
    }
    setConnectTimeout(timeout: number): void {
        this.connectTimeout = timeout;
    }
    setDefaultHeaders(headers: Record<string, string>): void {
        this.defaultHeaders = headers;
    }
    async request<T = any>(options: CLRequestOption): Promise<T> {
        const url = this.getFullUrl(options.path);
        const httpRequest = http.createHttp();
        let finalUrl = url;
        const headers = options.header || this.defaultHeaders;
        const method = options.method;
        const data = options.data;
        // GET 参数拼接
        if (method === http.RequestMethod.GET && typeof data === 'object' && data !== null) {
            const queryParams: string[] = [];
            const dataObj = data as Record<string, string | number | boolean>;
            const keys = Object.keys(dataObj);
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                const value = encodeURIComponent(String(dataObj[key]));
                queryParams.push(`${key}=${value}`);
            }
            if (queryParams.length > 0) {
                finalUrl += '?' + queryParams.join('&');
            }
        }
        const config: http.HttpRequestOptions = {
            method: method,
            readTimeout: this.readTimeout,
            connectTimeout: this.connectTimeout,
            header: headers,
            extraData: method === http.RequestMethod.GET ? '' : data || ''
        };
        try {
            const response = await httpRequest.request(finalUrl, config);
            if (response.responseCode === http.ResponseCode.OK) {
                // 解析结果，不做结构限制
                return JSON.parse(response.result as string) as T;
            }
            else {
                throw new Error(`Code: ${response.responseCode}, Message: ${response.result}`);
            }
        }
        catch (err) {
            throw new Error(String(err));
        }
        finally {
            httpRequest.destroy();
        }
    }
    get<T = any>(path: string, data?: Object, header?: Record<string, string>): Promise<T> {
        const option: CLRequestOption = {
            path: path,
            method: http.RequestMethod.GET,
            data: data,
            header: header
        };
        return this.request<T>(option);
    }
    post<T = any>(path: string, data?: Object, header?: Record<string, string>): Promise<T> {
        const option: CLRequestOption = {
            path: path,
            method: http.RequestMethod.POST,
            data: data,
            header: header
        };
        return this.request<T>(option);
    }
    private getFullUrl(path: string): string {
        if (path.startsWith('http')) {
            return path;
        }
        return this.baseUrl + path;
    }
}
export default new CLNetworkManager();
