import * as request from "request-promise";
import * as crypto from 'crypto'
import { BANTU_VID_ADDR, BANTU_VID_APP_KEY } from '../consts';

/**
 * 在线报告
 * @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'] = getObjSign(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 = checkSign(res);
        if (!check) return false;
        // console.log('*****request result*****');
        // console.log(JSON.stringify(res));
        return res;
    } catch (e) {
        console.error(e);
        return false
    }
}


export async function httpRequest(url: string, method: string, headers: any, body: any) {
    console.log(`httpRequest*********:   ${url}, ${method}, ${JSON.stringify(headers)}, ${JSON.stringify(body)}`)

    let options = {
        url,
        method,
        headers,
        body,
        json: true
    }

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

export function md5Vid(str: string) {
    str = 'vId' + str;
    return crypto.createHash('md5').update(str, 'utf8').digest("hex");
};

export function getObjSign(obj: any) {
    const str = [];
    Object.keys(obj).sort().forEach((key) => {
        if (key == 'sign') {

        } else {
            str.push(key + '=' + obj[key]);
        }
    });
    if (str.length == 0) {
        console.error('check obj', obj);
    }
    var strs = str.join('');
    return md5Vid(strs);
}

export async function checkSign(obj: any) {
    if (getObjSign(obj) === obj.sign) {
        return true;
    }
    console.warn('correct sign:', getObjSign(obj), obj.sign);
    return false;
}
