import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ITEM_CHANGE_REASON, STATUS } from '../../../consts';
import { getPlayerRechargeMoneyData, getPlayerRechargeMoneyDataShow } from '../../../services/activity/rechargeMoneyService';
import { RechargeMoneyPool } from '../../../domain/activityField/rechargeMoneyField';
import { addReward, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { ActivityRechargeMoneyModel } from '../../../db/ActivityRechargeMoney';
import { addItems } from '../../../services/role/rewardService';


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

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

    /************************每日累计充值****************************/

    /**
    * @description 获取活动数据
    * @param {BackendSession} session
    * @memberof RechargeMoneyHandler
    */
    async getRechargeMoneyActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

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

        return resResult(STATUS.SUCCESS, {playerData});
    }

    /**
   * @description 获取奖励
   * @param {BackendSession} session
   * @memberof RechargeMoneyHandler
   */
    async pull(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

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

        if (playerData.ticketCnt <= 0) {
            return resResult(STATUS.ACTIVITY_RECHARGE_TICKET_NOT_ENOUGH);
        }

        let item = playerData.pull();
        if (!item) {
            return resResult(STATUS.ACTIVITY_RECHARGE_TICKET_NOT_ENOUGH);
        }

        let notGetRecord = playerData.recordArr[0];
        // console.log('notGetRecord', JSON.stringify(notGetRecord));
        await ActivityRechargeMoneyModel.addRecord(notGetRecord._id, item.id, `${item.gid}&${item.count}`);
        let goods = await addItems(roleId, roleName, sid, [{ id: item.gid, count: item.count }], ITEM_CHANGE_REASON.RECHARGE_REWARD)

        return resResult(STATUS.SUCCESS, {
            param: { activityId },
            item: item,
            ticketCnt: playerData.ticketCnt,
        });
    }
}
