import {ApiCall} from "tsrpc";
import {ReqOpen, ResOpen} from "../../shared/protocols/qjzzd/PtlOpen";
import {PublicShared} from "../../shared/public/public";
import {Rank} from "../../public/rank/rank";
import {QjzzdFun} from "../../public/qjzzd";

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    // 获取配置参数
    let data = await G.mongodb.collection('scheduler').findOne({type: 'qjzzd'});
    // 获取本人数据
    let myData = await G.mongodb.cPlayerInfo('qjzzd').findOne({uid: call.uid, type: 'qjzzd'});
    // 获取当前maxDps和排名
    let maxDps = await Rank.list.qjzzd.getRankScore(call.uid)
    let rank = await Rank.list.qjzzd.getRankSortByOne(call.uid)
    // 战斗次数等数据重置判断
    let _zeroTime = PublicShared.getToDayZeroTime(G.time)
    if (!data) {
        data = (await G.mongodb.collection('scheduler').findOneAndUpdate({type: 'qjzzd'}, {
            $set: {
                lastRunTime: G.time,
                boss: await QjzzdFun.getBoosId(0)
            }
        }, {upsert: true, returnDocument: 'after'})).value;
    }
    if (!myData || myData.refreshTime < data.lastRunTime || !myData?.refreFightTime || myData?.refreFightTime < _zeroTime) {
        let _setData = {}
        // 每日挑战次数更新
        if (!myData?.refreFightTime || myData?.refreFightTime < _zeroTime) {
            // 每日挑战
            _setData = {
                refreFightTime: G.time,
                useFightNum: 0
            }
        }
        // 周期挑战次数更新
        if (!myData || myData.refreshTime < data.lastRunTime) {
            Object.assign(_setData, {refreshTime: data.lastRunTime, useFightNum: 0})
        }

        // 更新数据库
        G.mongodb.cPlayerInfo('qjzzd').updateOne(
            {uid: call.uid, type: 'qjzzd'},
            {$set: _setData},
            {upsert: true}
        );

        // 获取当前maxDps和排名
        let maxDps = await Rank.list.qjzzd.getRankScore(call.uid)
        let rank = await Rank.list.qjzzd.getRankSortByOne(call.uid)

        call.succ({
            boss: data.boss,
            maxDps,
            rank,
            useFightNum: 0,
            refreshTime: data.lastRunTime,
        });
    } else {
        call.succ({
            useFightNum: myData.useFightNum,
            refreshTime: myData.refreshTime,
            maxDps,
            rank,
            boss: data.boss
        });
    }
}