import {ctor} from '../global';
import {initMongoDB} from '../setMongodb';

async function start() {
    //连接mongodb
    await initMongoDB();

    // 查找所有穿戴shiwu的hero
    let heros = await G.mongodb.collection("hero").find({
        shiwu: {$exists: true}
    }).toArray();

    for (let i = 0; i < heros.length; i++) {
        let hero = heros[i];
        if (R.values(hero.shiwu).filter(i => !i._id).length == 0) {
            continue
        }

        let shiwuChange = {}
        if (hero.shiwu?.['1']?._id) {
            shiwuChange['1'] = hero.shiwu['1']
        }
        if (hero.shiwu?.['2']?._id) {
            shiwuChange['2'] = hero.shiwu['2']
        }
        console.log("修复英雄数据：", hero._id, shiwuChange);
        let res = await G.mongodb.collection("hero").findOneAndUpdate(
            {_id: hero._id}, {$set: {shiwu: shiwuChange}}, {returnDocument: 'after'}
        );
        console.log("修复更新结果", res.value._id, res.value);
    }

    // 查找所有赶海数据
    let datas = await G.mongodb.collection("ganhai").find(
        {ship: {$ne: null}}
    ).toArray();

    for (let i = 0; i < datas.length; i++) {
        let up = false;
        let data = datas[i];
        if (!data.ship) continue;
        for (let pos in data.ship.player.roles) {
            if (!data.ship.player.roles[pos].shiwu) {
                continue
            }
            for (let idx in data.ship.player.roles[pos].shiwu) {
                if (!data.ship.player.roles[pos].shiwu[idx]._id) {
                    up = true;
                    delete data.ship.player.roles[pos].shiwu[idx];
                }
            }
        }

        if (!up) continue;
        let res = (await G.mongodb.collection("ganhai").findOneAndUpdate({_id: data._id}, {
            $set: {ship: data.ship}
        }, {returnDocument: "after"})).value;

        console.log("修复赶海数据结果", res.ship);
    }

    console.log("开始修复公路狂飙数据...");
    // 删除所有人的公路狂飙的对手
    await G.mongodb.collection("wanted").updateMany({}, {$unset: {enemys: true}})
}

//定义全局变量
ctor();
//启动服务
start().then(() => {
    process.exit()
});


