import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { ReqRefreshShip, ResRefreshShip } from "../../shared/protocols/ganhai/PtlRefreshShip";
import { randomMyShips } from './ApiOpen';

export default async function (call: ApiCall<ReqRefreshShip, ResRefreshShip>) {
    let dbData = await G.mongodb.collection('ganhai').findOne({ uid: call.uid });
    if (dbData.ship != null) return call.error('', { code: -1 });
    let reNum = dbData.useRefreshNum

    let _refresh: boolean = false
    let _yijianzuigao: boolean = false


    if (call.req?.yjzg) {
        _yijianzuigao = true
        let need = G.gc.ganhai.oneClickNeed;
        await PlayerFun.checkNeedIsMeet(call, need);
        await PlayerFun.cutNeed(call, need);
    } else {
        reNum += 1;
        if (reNum > G.gc.ganhai.refreshNum) {
            let _maxNum = G.gc.ganhai.refreshMaxNeed;
            let need = G.gc.ganhai.refreshNeed.map(_need => {
                return {
                    ..._need,
                    n: ((reNum - 1) * 20) > _maxNum ? _maxNum : (reNum - 1) * 20
                };
            });
            await PlayerFun.checkNeedIsMeet(call, need);
            await PlayerFun.cutNeed(call, need);
        }
        _refresh = reNum % G.gc.ganhai.num == 0
    }

    let shipIndex = randomMyShips(_refresh,_yijianzuigao);

    G.mongodb.collection('ganhai').updateOne({ uid: call.uid }, { $set: { myShips: shipIndex, useRefreshNum: reNum } });

    call.succ({
        change: {
            myShips: shipIndex,
            useRefreshNum: reNum
        }
    });
}