import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ITEM_CHANGE_REASON, STATUS } from '../../../consts';
import { getPlayerRefreshShopData } from '../../../services/activity/refreshShopService';
import { addReward, stringToConsumeParam, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { ActivityRefreshShopModel } from '../../../db/ActivityRefreshShop';
import { handleCost } from '../../../services/role/rewardService';

export default function (app: Application) {
    new HandlerService(app, {});
    return new RefreshShopHandler(app);
}

export class RefreshShopHandler {
    constructor(private app: Application) {
    }

    /************************通用的刷新商店（分页，可刷新，限制购买次数，支持rmb与资源兑换）****************************/

    /**
    * @description 获取商店数据
    * @param {{ activityId:number}} msg
    * @param {BackendSession} session
    * @memberof RefreshShopHandler
    */
    async getRefreshShopActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

        let playerData = await getPlayerRefreshShopData(activityId, serverId, roleId);
        if (!playerData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }
        return resResult(STATUS.SUCCESS, { playerData });
    }


    /**
        * @description 购买
        * @param {{ activityId: number, roundIndex: number, id: number, pageIndex: number}} msg
        * @param {BackendSession} session
        * @memberof RefreshShopHandler
        */
    async buyGood(msg: { activityId: number, roundIndex: number, id: number, pageIndex: number, count: number }, session: BackendSession) {
        const { activityId, roundIndex, id, pageIndex, count = 1 } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

        let playerData = await getPlayerRefreshShopData(activityId, serverId, roleId);
        if (!playerData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }

        if (playerData.roundIndex != roundIndex) {
            return resResult(STATUS.ACTIVITY_EXPIRE);
        }

        let item = playerData.findItem(id, pageIndex);
        if (!item) {
            return resResult(STATUS.ACTIVITY_ID_ERROR);
        }
        if (item.countMax > 0 && item.buyCount + count > item.countMax) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT);
        }
        if (item.price > 0) {
            return resResult(STATUS.ACTIVITY_NEED_PAY);
        }

        //检查资源
        let consumeArr = new Array<string>(count).fill(item.consume);
        let consume = stringToConsumeParam(...consumeArr);
        let consumeResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.BUY_REFRESH_SHOP);
        if (!consumeResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        let rewardArray = stringToRewardParam(item.reward).map(cur => ({...cur, count: cur.count * count }));
        let result = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.BUY_REFRESH_SHOP);

        await ActivityRefreshShopModel.addRecord(activityId, roleId, roundIndex, pageIndex, id, count);

        item.buyCount += count;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, roundIndex, id },
            item: item
        }));
    }

}
