import { DEBUG_PRICE, REDIS_KEY, SDK_37_ADDR, SDK_37_CONST, WJX_KEY } from '../consts';
import { request37 } from './httpUtil';
import { nowSeconds } from './timeUtil';
import { LoginValidataReturn37, Chat37Params, GetServerListParam } from '../domain/sdk';
import * as crypto from 'crypto'
import { gameData } from './data';

// 通用加密方法

export function md5(str: string, treatStr?: (str: string) => string) {
    if(treatStr) str = treatStr(str);
    // console.log('*****str', str)
    return crypto.createHash('md5').update(str, 'utf8').digest("hex");
};

export function sha1(str: string, treatStr?: (str: string) => string) {
    if(treatStr) str = treatStr(str);
    // console.log('*****str', str)
    return crypto.createHash('sha1').update(str, 'utf8').digest("hex");
}

export function getMd5ObjSign(obj: any, joinMark: string, treatStr?: (str: string) => string) {
    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(joinMark);
    return md5(strs, treatStr);
}

export async function checkMd5Sign(obj: any, treatStr?: (str: string) => string) {
    if (getMd5ObjSign(obj, '', treatStr) === obj.sign) {
        return true;
    }
    console.warn('correct sign:', getMd5ObjSign(obj, '', treatStr), obj.sign);
    return false;
}

/************** 37sdk **************/

export function get37Md5SignA(body: any, key: string) {
    return getMd5ObjSign(body, '&', (str) => `${str}&${key}`);
}

export function get37CheckChatMd5Sign(body: Chat37Params, key: string) {
    let { game_key = '', sid = '', username = '', channel = '', to_username = '', ip = '', time } = body;
    let str = `${game_key}${sid}${username}${to_username}${channel}${ip}${time}${key}`;
    let sign = md5(str);
    console.log('** origin str', body, str, sign);
    return sign;
}

export function get37Md5SignB(body: any, key: string) {
    return getMd5ObjSign(body, '', (str) => `${str}${key}`);
}

export function get37GetServerMd5Sign(body: GetServerListParam, key: string) {
    let { time, appid, gid } = body;
    let str = `${time}${appid}${gid}${key}`;
    let sign = md5(str);
    console.log('** origin str', body, str, sign);
    return sign
}

export function get37BackendMd5Sign(body: {uname: string, time: number}, key: string) {
    let { uname, time } = body;
    let str = `${uname}${time}${key}`;
    let sign = md5(str);
    console.log('** origin str', body, str, sign);
    return sign
}

export async function loginValidate37(clientId: string, pst: string, platform: string, platformAppid: string, childGameId: number = SDK_37_CONST.FX_C_GAME_ID) {
    if(!platformAppid) {
        if(platform == 'android') {
            platformAppid = SDK_37_CONST.PID;
        } else if(platform == 'ios' ){
            platformAppid = SDK_37_CONST.IOS_PID;
        }
    }
    let result: string = await request37(SDK_37_ADDR.LOGIN, {
        clientid: clientId,
        pid: platformAppid,
        game_id: SDK_37_CONST.GAME_ID,
        pst,
        time: nowSeconds(),
        c_game_id: childGameId
    }, SDK_37_CONST.LOGIN_KEY);

    let json: LoginValidataReturn37;
    try {
        json = JSON.parse(result);
    }catch(e) {
        console.log(e);
    }
    if (json && json.code !== 1) {
        console.error(json.msg);
    }

    return json;
}

export async function loginValidata(channelType: string, params: { clientId: string, pst: string, platform: string, platformAppid: string, childGameId: number }) {
    if(channelType == '37') {
        let { clientId, pst, platform, platformAppid, childGameId } = params;
        return await loginValidate37(clientId, pst, platform, platformAppid, childGameId);
    } else {
        return false;
    }
}

export function getChannelId(channelType: string, uid: number|string) {
    return `${channelType}_${uid}`;
}


/********* 厚土防沉迷 *********/

export function getVidObjSign(body: any) {
    return getMd5ObjSign(body, '', treatVid);
}

export function checkVidObjSign(obj: any) {
    return checkMd5Sign(obj, treatVid);
}

function treatVid(str) {
    return 'vId' + str;
}

export function getRedisSubChannel(key: REDIS_KEY, env: string) {
    return `${key}:${env}`;
}

/********* 问卷星加密 *********/

export function checkWjxSign(activity: string, index: string, sign: string) {
    const str = `${activity}${index}${WJX_KEY}`;
    let signResult = sha1(str);
    console.log('##### checkWjxSign', str, signResult, sign);
    if(signResult != sign) return false;
    return true;
}

export function checkParamPrice(orderPrice: number, paramPrice: string) {
    if(!isDebugPay() && orderPrice != parseFloat(paramPrice)) return false;
    if(isDebugPay() && parseFloat(paramPrice) != DEBUG_PRICE) return false;
    return true
}

export function isDebugTime() {
    return gameData.serverConst.DEBUG_TIME === 1;
}

export function isDebugPay() {
    return gameData.serverConst.DEBUG_PAY === 1;
}

export function isCheckWord(isDevelop = false) {
    return gameData.serverConst.CHECK_WORD === 1 && !isDevelop;
}

export function canPay() {
    return gameData.serverConst.CAN_PAY === 1;
}

export function isSkipEncode(isDevelop = false) {
    return gameData.serverConst.SKIP_ENCODE === 1 && isDevelop;
}

export function needRebate() {
    return gameData.serverConst.NEED_REBATE == 1;
}