import {serviceProto} from '../shared/protocols/serviceProto';
import {WsClient} from 'tsrpc';
import {encryptUint8Array} from "../encrypt";
import {readFileSync, writeFileSync} from "fs";
import {resolve} from "path";
import {randomUUID} from "crypto";

// 压测用户数量
let userNum = 500

//用户登录等待时间，
let lminTime = 50
let lmaxTime = 300
// 用户操作等待时间，随机数
let minTime = 500
let maxTime = 1500

// 本地地址
let serverSid = 2
let serverName = `内网服务器`
let requestUrl = 'ws://10.0.1.20:10001'
requestUrl = 'ws://10.0.1.20:10001'
// 日测服地址
// let serverSid = 1
// let serverName = `S${serverSid}`
// let requestUrl = `wss://blacklagoon-slb.stg.g123-cpp.com/server-game${serverSid}`
// let mongodbName = `blacklagoon_s${serverSid}`
// let mongodbUrl = `mongodb://blacklagoon:tw2lSJj%23w%25sN3%241q@blacklagoon-mongo-primary.stg.g123-cpp.com:3717,blacklagoon-mongo-secondary.stg.g123-cpp.com:3717/blacklagoon_s${serverSid}?replicaSet=mgset-351473381`

async function main(userNum = 10) {
    for (let j = 0; j < userNum; j++) {
        start(j)
    }
}

//数据在客户端自动采集
let steps = [
    {
        "api": "user/Login",
        "parms": {
            "bindUid": "{{randBindUid}}",
            "sid": 2,
            "serverName": "ciniao"
        }
    }, {
        "api": "equip/GetList",
        "parms": {}
    }, {
        "api": "tanxian/Open",
        "parms": {
            "cache": false
        }
    }, {
        "api": "item/GetList",
        "parms": {}
    }, {
        "api": "shiwu/GetList",
        "parms": {}
    }, {
        "api": "peijian/GetList",
        "parms": {}
    }, {
        "api": "hero/GetList",
        "parms": {}
    }, {
        "api": "email/Open",
        "parms": {}
    }, {
        "api": "friend/Open",
        "parms": {}
    }, {
        "api": "SyncBtn",
        "parms": []
    }, {
        "api": "gongyu/mingdao/Open",
        "parms": {}
    }, {
        "api": "pay/GetList",
        "parms": {}
    }, {
        "api": "eventlist/hdGetList",
        "parms": {}
    }, {
        "api": "user/Ping",
        "parms": {}
    }, {
        "api": "Test",
        "parms": {}
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "chat/GetList",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["jiuba", "jiaotang", "shouchong", "dixiaqianzhuanghd", "taskhd", "xstaskhd", "gonghuihd", "jjchd", "hbzbhd", "clslhd", "lingzhulaixihd", "dxlthd", "wzcjhd", "slzdhd", "qjzzdhd", "kuangdonghd", "qiandaohd", "kaifukuanghuanhd", "jijinhd", "zhuishalinghd", "yibaichouhd", "huobanzhaomuhd", "qirileichonghd", "jierihd", "kbzzhd", "wzryhd", "yuedujijin", "patahd", "mingdao", "heishihd", "jitianhaoli", "huodonghd", "renown", "heishiMrjx"]
    }, {
        "api": "user/Ping",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["yibaichouhd"]
    }, {
        "api": "user/ChangeName",
        "parms": {
            "name": "{{randName}}"
        }
    }, {
        "api": "jiuba/Open",
        "parms": {}
    }, {
        "api": "jiuba/Lottery",
        "parms": {
            "type": 30
        }
    }, {
        "api": "hongdian/Get",
        "parms": ["jiuba", "taskhd", "huodonghd"]
    }, {
        "api": "hongdian/Get",
        "parms": ["zhuishalinghd"]
    }, {
        "api": "hero/ChangePos",
        "parms": {
            "state": "set",
            "id": "65534e066fe10dfa109e1249",
            "pos": "2"
        }
    }, {
        "api": "user/Ping",
        "parms": {}
    }, {
        "api": "kuangdong/Open",
        "parms": {}
    }, {
        "api": "tanxian/Open",
        "parms": {
            "cache": true
        }
    }, {
        "api": "gonglukuangbiao/Open",
        "parms": {}
    }, {
        "api": "task/Open",
        "parms": {
            "type": [2]
        }
    }, {
        "api": "tanxian/Fight",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["taskhd", "huodonghd", "jijinhd", "huobanzhaomuhd"]
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["jijinhd"]
    }, {
        "api": "task/Open",
        "parms": {
            "type": [2]
        }
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "SyncBtn",
        "parms": ["shouchong"]
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "task/Open",
        "parms": {
            "type": [1, 2, 3, 4, 5]
        }
    }, {
        "api": "hongdian/Get",
        "parms": ["yibaichouhd"]
    }, {
        "api": "task/Finsh",
        "parms": {
            "taskid": 2000
        }
    }, {
        "api": "hongdian/Get",
        "parms": ["taskhd", "huodonghd"]
    }, {
        "api": "equip/OneKeyWear",
        "parms": {
            "heroId": "65534de06fe10dfa109e1218"
        }
    }, {
        "api": "kuangdong/Open",
        "parms": {}
    }, {
        "api": "tanxian/Open",
        "parms": {
            "cache": true
        }
    }, {
        "api": "gonglukuangbiao/Open",
        "parms": {}
    }, {
        "api": "task/Open",
        "parms": {
            "type": [2]
        }
    }, {
        "api": "tanxian/Fight",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["taskhd", "huodonghd", "jijinhd", "huobanzhaomuhd"]
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["jijinhd"]
    }, {
        "api": "user/Ping",
        "parms": {}
    }, {
        "api": "task/Open",
        "parms": {
            "type": [2]
        }
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "SyncBtn",
        "parms": ["shouchong"]
    }, {
        "api": "event/shouchong/Open",
        "parms": {}
    }, {
        "api": "kuangdong/Open",
        "parms": {}
    }, {
        "api": "item/Use",
        "parms": {
            "itemId": "3007",
            "useNum": 1
        }
    }, {
        "api": "hongdian/Get",
        "parms": ["yibaichouhd"]
    }, {
        "api": "user/Ping",
        "parms": {}
    }, {
        "api": "hongdian/Get",
        "parms": ["yibaichouhd"]
    }
]

function fmtParms(param:any, data:any){
    let str = JSON.stringify(param);
    str = str.replace("{{randBindUid}}",`yaliceshi${random(1000000000,99999999999)}`)
    str = str.replace("{{randName}}",`压力测试${random(1000000000,99999999999)}`)
    return JSON.parse(str);
}


async function start(userId) {
    /**
     请求步骤
     */
    let client: any = await connect()
    if (!client) return
    
    let res = {};

    for(let i=0;i<steps.length;i++){
        let parms = fmtParms(steps[i].parms,{
            userId: userId,
            stepi:i,
        });

        let startTime = Date.now();
        // console.log('请求接口开始',userId,steps[i].api,parms)
        let response = await client?.callApi( steps[i].api, parms );
        if((Date.now()-startTime)>300&&steps[i].api!='user/Login') console.log('请求接口结束',userId,steps[i].api, response.isSucc ,'耗时', + (Date.now()-startTime) + 'ms')

        if(response.isSucc){
            res[i] = response.res;
            if(steps[i]['key']){
                res[steps[i]['key']] = response.res;
            }
        }
        
        await sleep(30)
    }
}


async function connect() {
    let url = requestUrl

    let client = new WsClient(serviceProto, {
        server: url,
        timeout:0,
    });

    let result = await client.connect();
    if (!result.isSucc) return console.log('connect server fail: ', result.errMsg);
    else console.log(`connect server succ at ${url}`);

    client.flows.preSendDataFlow.push(v => {
        if (v.data instanceof Uint8Array) {
            v.data = encryptUint8Array(v.data);
        }
        return v;
    });

    client.flows.postDisconnectFlow.push(v => {
        if (!v.isManual) {
            console.log('网络错误，连接已断开')
        }
        return v;
    })
    return client
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

function random(min = 500, max = 1500) {
    return Math.round(Math.random() * (max - min) + min)
}

~async function loop(){
    await main(userNum)
}();