import * as request from "request-promise";
import { RequestError } from "request-promise/errors";
import { BANTU_VID_ADDR, BANTU_VID_APP_KEY, HTTP_METHOD } from '../consts';
import { checkVidObjSign, get37CheckChatMd5Sign, get37Md5SignA, get37Md5SignB, getVidObjSign } from "./sdkUtil";
import { STATUS } from '../consts'
import { resResult } from "./util";
import { Chat37Params, CheckGuild37Params, CheckName37Params, GetWordParam } from "../domain/sdk";

// 通用，请求http
export async function httpRequest(url: string, method: string, body: any, headers?: any, timeout = 150) {
    console.log(`httpRequest*********:   ${url}, ${method}, ${JSON.stringify(headers)}, ${JSON.stringify(body)}`)

    if(!headers) {
        headers = {
            'content-type': 'application/json;charset=utf-8',
        }
    }

    let options = {
        url,
        method,
        headers,
        body: JSON.stringify(body),
        timeout,
        JSON: true
    }

    try {
        let res = await request(options);
        console.log('*****request result*****');
        console.log(JSON.stringify(res));
        return res;
    } catch (e) {
        console.error('******', e);
        let code = (<RequestError>e).cause?.code;
        if(code == 'ESOCKETTIMEDOUT') {
            return resResult(STATUS.REQUEST_TIME_OUT);
        } else {
            return resResult(STATUS.REQUEST_TIME_OUT);
        }
    }
}

export async function httpRequestForm(url: string, method: string, form: any, timeout = 150, printRes = true) {
    console.log(`httpRequest*********:   ${url}, ${method}, ${JSON.stringify(form)}`)

    let options = {
        url,
        method,
        headers: {
            'content-type': 'application/x-www-form-urlencoded'
        },
        timeout,
        JSON: true
    }
    if(method == HTTP_METHOD.GET) {
        options['qs'] = form;
    } else if (method == HTTP_METHOD.POST) {
        options['form'] = form;
    }

    try {
        let res = await request(options);
        console.log('*****request result*****');
        if (printRes) {
            console.log(JSON.stringify(res));
        }
        return res;
    } catch (e) {
        console.error('******', e);
        let code = (<RequestError>e).cause?.code;
        if(code == 'ESOCKETTIMEDOUT') {
            return resResult(STATUS.REQUEST_TIME_OUT);
        } else {
            return resResult(STATUS.REQUEST_TIME_OUT);
        }
    }
}

/************** 厚土防沉迷接口 **************/
/**
 * 在线报告 暂时不使用
 * @param userCode 账号
 * @param packageName 包名 
 */
export async function reportOnline(userCode: string, packageName: string) {
    if (!packageName || packageName == '') {
        packageName = 'com.bantu.nfsg'
    }

    let result = await vidHttpRequest(BANTU_VID_ADDR.REPORT_ONLINE, {
        account: userCode,
        package: packageName
    });
    if (result && result.code !== 1) {
        console.error(result.msg);
    }

    return result;
}

/**
 * 实名认证 暂时不使用
 * @param name 真实姓名
 * @param idNum 身份证号
 * @param userCode 账号
 * @param packageName 包名 
 */
export async function authenticate(name: string, idNum: string, userCode: string, packageName: string) {
    if (!packageName || packageName == '') {
        packageName = 'com.bantu.nfsg'
    }

    let result = await vidHttpRequest(BANTU_VID_ADDR.IDCARD, {
        account: userCode,
        cardno: idNum,
        name,
        appkey: BANTU_VID_APP_KEY,
        package: packageName
    });
    if (result && result.code !== 1) {
        console.error(result.msg);
    }

    return result && result.code == 1;
}

export async function vidHttpRequest(addr: string, body: any) {
    body['sign'] = getVidObjSign(body);
    console.log('body: ', JSON.stringify(body))

    let options = {
        url: BANTU_VID_ADDR.HOST + addr,
        method: 'POST',
        body: body,
        json: true
    }

    try {
        let res = await request(options);
        let check = checkVidObjSign(res);
        if (!check) return false;
        // console.log('*****request result*****');
        // console.log(JSON.stringify(res));
        return res;
    } catch (e) {
        console.error(e);
        return false
    }
}

// 37sdk请求

export async function request37(url: string, body: any, key: string) {
    body['sign'] = get37Md5SignA(body, key);

    let result = await httpRequestForm(url, HTTP_METHOD.POST, body, 1000);
    console.log('******result', result)
    return result;
}

export async function request37Post(url: string, body: CheckName37Params|CheckGuild37Params, key: string) {
    body.setSign(get37Md5SignB(body.getBody(), key));

    let result = await httpRequestForm(url, HTTP_METHOD.POST, body, 1 * 60 * 1000);
    console.log('*******', result != 1, result.code != STATUS.REQUEST_TIME_OUT.code)
    if(result.code == STATUS.REQUEST_TIME_OUT.code) {
        return STATUS.REQUEST_TIME_OUT.code;
    }
    if(result != 1) {
        return 0
    }
    return 1;
}

export async function request37CheckChat(url: string, body: Chat37Params, key: string) {
    body.setSign(get37CheckChatMd5Sign(body, key));

    let result = await httpRequestForm(url, HTTP_METHOD.GET, body, 3 * 60 * 1000);
    if(result != 1 && result.code != STATUS.REQUEST_TIME_OUT.code) {
        return false
    }
    return true;
}

export async function request37GetWord(url: string, body: GetWordParam, key: string) {
    body.setSign(get37Md5SignB(body.getBody(), key));

    let result = await httpRequestForm(url, HTTP_METHOD.GET, body, 5 * 60 * 1000, false);
    return result;
}
