import {MongoClient} from "mongodb";
import {readFileSync,rename} from "fs";
import {resolve} from "path";
let XLSX = require("xlsx");


// 日志版本
let version = '11.07.6'

// 本地地址
let serverSid = 3
let mongodbName = 'heijiao'
let mongodbUrl = `mongodb://root:lyMaple525458@10.0.1.20:27017/heijiao?authSource=admin`
// 日测服地址
// let serverSid = 1
// 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`

let dbClient
let outputLog = []
let outputLog1 = []


async function main() {
    await initDB()
    /**
     * 获取所有请求API
     */
    let allApiConfig = await readApiJson()
    let allApiNameConfig = await readApiNameJson()

    // 查询当前压测一轮用户数量
    // let userNum = await dbClient.collection('stressTestLog').countDocuments({version: version, num: 1})
    // console.log(1111,a)

    /**
     * 记录每个步骤消耗的时间，计算最小值，最大值，平均值
     */
    await start(allApiConfig,allApiNameConfig)

    await toExcel()


    console.log(outputLog)
    console.log(`---------------统计完成----------------`)

}

async function toExcel(){
    const jsonWorkSheet = await XLSX.utils.json_to_sheet(outputLog);
    const jsonWorkSheet1 = await XLSX.utils.json_to_sheet(outputLog1);
    const workBook = {
        SheetNames: ['outputLog','outputLog1'],
        Sheets: {
            ['outputLog']: jsonWorkSheet,
            ['outputLog1']: jsonWorkSheet1,
        }
    };
    await XLSX.writeFileXLSX(workBook, `outputLog.${version}.xlsx`);
    rename(`./outputLog.${version}.xlsx`, `/g123/outputLog.${version}.xlsx`, err => { })
}

async function start(allApi,allName) {
    // for (let itemIdx in allApi) {
    //
    //     let items = allApi[itemIdx]
    //     let logs = await dbClient.collection('stressTestLog').find({version: version, num: items[0].num}).toArray()
    //     if (!logs.length) continue
    //
    //     let times = logs.map(i => i.time)
    //     let jtime = 0
    //     for(let i = 0;i<times.length;i++) {
    //         jtime = times[i]+jtime;
    //     }
    //     let meanTime = Math.round(jtime/times.length);
    //
    //     logs = logs.sort((a, b) => a.time - b.time)
    //
    //
    //     // console.log(logs)
    //     outputLog.push({
    //         txt: logs[0].txt,
    //         num: logs[0].num,
    //         minTime: logs[0].time,
    //         maxTime: logs[logs.length - 1].time,
    //         meanTime: meanTime
    //     })
    //     console.log(`----------正在统计${logs[0].txt}-----------`)
    // }

    for (let itemIdx in allName) {

        let item = allName[itemIdx]
        let logs = await dbClient.collection('apiTestLog').find({version: version, name: item}).toArray()
        if (!logs.length) continue

        // console.log(1111111111111)

        let times = logs.map(i => i.ms)
        let jtime = 0
        for(let i = 0;i<times.length;i++) {
            jtime = times[i]+jtime;
        }
        let meanTime = Math.round(jtime/times.length);

        logs = logs.sort((a, b) => a.ms - b.ms)

        // console.log(logs)
        outputLog1.push({
            path: logs[0].name,
            num: logs[0].num,
            minTime: logs[0].ms,
            maxTime: logs[logs.length - 1].ms,
            meanTime: meanTime,
            count: logs.length
        })
        console.log(`----------正在统计${logs[0].txt}-----------`)
    }

}

async function readApiJson() {
    return await JSON.parse(readFileSync(resolve(__dirname, './allApi.json'), 'utf-8'))
}

async function readApiNameJson() {
    return await JSON.parse(readFileSync(resolve(__dirname, './allPath.json'), 'utf-8'))
}

async function initDB() {
    console.log('connect mongodb ......');
    let client = await MongoClient.connect(mongodbUrl);
    dbClient = client.db(mongodbName || '');
    console.log('connect mongodb succ');
}

main()