import {ApiCall} from "tsrpc";
import {PlayerFun} from '../../public/player';
import {ShopFun} from '../../public/shop';
import {ReqBuy, ResBuy} from "../../shared/protocols/shop/PtlBuy";
import {HongDianChange} from "../hongdian/fun";

export default async function (call: ApiCall<ReqBuy, ResBuy>) {
    let index = call.req.buyIndex;
    let shopId = call.req.shopId;
    let buyNum = call.req.buyNum || 1;

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

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

    let shopItem = shopData.shopItems[index];

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

    if (!shopItem) return call.error(globalThis.lng.shop_2);

    if (shopItem.needVip > call.conn.gud.vip) return call.error(globalThis.lng.shop_3);

    if (buyNum < 0) return call.error(globalThis.lng.shop_4);

    shopData.buyNum[index] = shopData.buyNum[index] || 0;

    let vipAdd = 0;
    if (shopItem.vipAddbuyNum.length > 0) {
        if (shopItem.vipAddbuyNum[call.conn.gud.vip] != undefined) vipAdd += shopItem.vipAddbuyNum[call.conn.gud.vip];
        else vipAdd += shopItem.vipAddbuyNum.last();
    }

    if (shopItem.buyNum > 0 && shopData.buyNum[index] + buyNum > shopItem.buyNum + vipAdd) return call.error(globalThis.lng.shop_4);

    let need = shopItem.buyNeed.map(v => {
        v.n *= buyNum;
        return v;
    });

    await PlayerFun.checkNeedIsMeet(call, need);

    shopData.buyNum[index] += buyNum;
    shopItem.n *= buyNum;

    await PlayerFun.cutNeed(call, need);
    if (shopItem.a == 'shiwu') {
        await PlayerFun.addShiwu(call, [{...shopItem, t: shopItem.t.toString()}]);
    } else {
        await PlayerFun.sendPrize(call, [shopItem]);
    }
    if (shopId == '2') {
        await ShopFun.changeGHShopData(uid, shopId, {buyNum: shopData.buyNum});
    } else {
        await ShopFun.changeShopData(uid, shopId, {buyNum: shopData.buyNum});
    }

    HongDianChange.sendChangeKey(uid, ['gonghuihd', 'taskhd', 'huodonghd', 'patahd']);
    // shopId=2，rid=公会id，作用未知，单独给“2”发送个人红点。
    if (shopId == "2") HongDianChange.sendChangeKey(call.uid, ['gonghuihd', 'taskhd', 'huodonghd', 'patahd']);
    call.succ({prize: [shopItem], buyNum: shopData.buyNum});
}