import {ApiCall} from "tsrpc";
import {PlayerFun} from '../../public/player';
import {ShopFun} from '../../public/shop';
import {ReqRefresh, ResRefresh} from "../../shared/protocols/shop/PtlRefresh";

export default async function (call: ApiCall<ReqRefresh, ResRefresh>) {
    let shopId = call.req.shopId;
    let shopConf = G.gc.shop[shopId];

    let uid = shopId != "2" ? call.uid : call.conn.gud.ghId

    let shopData = await ShopFun.getShopData(uid, shopId, call.conn.gud.lv);

    if (!shopData) return call.error(globalThis.lng.shop_1);

    let change: typeof ShopFun.changeType = {};

    if (shopConf.freeRefreshNum > 0 && shopData.useFreeRefreshNum < shopConf.freeRefreshNum) {
        change.useFreeRefreshNum = shopData.useFreeRefreshNum + 1;
        if (shopConf.freeRefreshInterval > 0 && change.useFreeRefreshNum >= shopConf.freeRefreshNum) {
            change.lastFreeRefreshTime = G.time;
        }
    } else if (shopConf.freeRefreshInterval > 0 && G.time - shopData.lastFreeRefreshTime >= shopConf.freeRefreshInterval) {
        change.useFreeRefreshNum = 1;
        if (change.useFreeRefreshNum >= shopConf.freeRefreshNum) {
            change.lastFreeRefreshTime = G.time;
        }
    } else {
        if (shopConf.recoilRefreshNum == 0 && shopConf.vip.length < 1) return call.error(globalThis.lng.shop_6);
        let refreshNum = shopConf.recoilRefreshNum;
        if (shopConf.vip.length > 0) {
            if (shopConf.vip[call.conn.gud.vip] != undefined) refreshNum += shopConf.vip[call.conn.gud.vip];
            else refreshNum += shopConf.vip.last();
        }
        if (shopConf.recoilRefreshNum > 0 && shopData.useRecoilRefreshNum >= shopConf.recoilRefreshNum) return call.error(globalThis.lng.shop_7);
        if (shopConf.recoilRefreshNeed.length > 0) {
            let meet = await PlayerFun.checkNeedByArgs(call, ...shopConf.recoilRefreshNeed);
            await PlayerFun.cutNeed(call, [meet.atn]);
        }

        change.useRecoilRefreshNum = shopData.useRecoilRefreshNum + 1;
    }

    change.buyNum = {};
    change.shopItems = ShopFun.getShopItems(shopId, call.conn.gud.lv);

    await ShopFun.changeShopData(uid, shopId, change);

    let {buyNum, shopItems, ...ops} = change;
    call.succ({buyNum: buyNum, shopItems: shopItems, ...ops});
}