import { ApiCall } from "tsrpc";
import { ReqOpen, ResOpen } from "../../shared/protocols/slzd/PtlOpen";
import { PublicShared } from '../../shared/public/public';
import { SlzdShared } from '../../shared/public/slzd';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    // 查询特产库
    let stashObj:k_v<number> = await SlzdShared.getStash()
    let dbData = await G.mongodb.collection('slzdUser').findOne({ uid: call.uid });
    let data = dbData?.data;

    if (!data || PublicShared.getToDayZeroTime() > data.refreshTime) {
        let GHdata = await call.conn.gonghui;
        if (!data) {
            var hz = await G.mongodb.collection('slzdUser').findOne({ uid: GHdata.data.createPlayer.uid });
        }

        data = {
            aim: hz?.data?.aim || '',
            winNum: 0,
            winRec: [],
            fightNum: G.gc.slzd.ctorFightNum,
            buyFightNum: 0,
            replyCd: G.time,
            refreshTime: G.time,
            useRefreshNum: 0,
            enemy: data?.enemy || {}
        };


        G.mongodb.collection('slzdUser').updateOne(
            { uid: call.uid },
            {
                $set: {
                    ghid: call.conn.gud.ghId,
                    data: data,
                    info: await call.conn.getDefaultFightData(),
                    val: dbData?.val || {},
                    recordFightNum: 0
                }
            },
            { upsert: true }
        );
    } else if (data.fightNum < G.gc.slzd.maxFightNum && G.time - data.replyCd > G.gc.slzd.replyCd) {
        let addNum = Math.floor((G.time - data.replyCd) / G.gc.slzd.replyCd);
        let maxAddNum = G.gc.slzd.maxFightNum - data.fightNum;
        data.fightNum += addNum > maxAddNum ? maxAddNum : addNum;
        data.replyCd = G.time;
        G.mongodb.collection('slzdUser').updateOne({ uid: call.uid }, { $set: { 'data.fightNum': data.fightNum, 'data.replyCd': data.replyCd } });
    }

    let { refreshTime, ...ops } = data;
    call.succ({
        ...ops,
        stashObj,
        soltLog: (await G.mongodb.collection('slzdGh').findOne({ ghid: call.conn.gud.ghId }))?.soltLog || []
    });
}