import { Application, BackendSession, HandlerService, pinus, } from 'pinus';
import { isNumber } from 'underscore';
import { ITEM_CHANGE_REASON, STATUS } from '../../../consts';
import { ActivityGuildPayRecordModel } from '../../../db/ActivityGuildPayRecord';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { resResult } from '../../../pubUtils/util';
import { addReward, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { getGuildPayDataShow, getGuildPayData } from '../../../services/activity/guildPayService';


export default function (app: Application) {
    return new GuildPayHandler(app);
}

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


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

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

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

    /**
    * @description (一键)领取奖励
    * @param {{ }} msg
    * @param {BackendSession} session
    * @memberof GuildPayHandler
    */
     async receiveItems(msg: { activityId: number, cellIndex: number }, session: BackendSession) {
        const { activityId, cellIndex } = msg;
        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const sid = session.get('sid');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');

        if(!isNumber(cellIndex)) return resResult(STATUS.WRONG_PARMS);

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

        let items = playerData.receiveItems(cellIndex);
        if(!items) return resResult(STATUS.ACTIVITY_ITEM_CANNOT_RECEIVE);


        let records: number[] = [], rewards: RewardParam[] = [];
        for(let item of items) {
            records.push(item.cellIndex);
            rewards.push(...stringToRewardParam(item.reward));
        }
        await ActivityGuildPayRecordModel.receiveItems(serverId, activityId, playerData.roundIndex, roleId, records);
        let result = await addReward(roleId, roleName, sid, serverId, rewards, ITEM_CHANGE_REASON.ACT_GUILD_PAY_REWARD);

        return resResult(STATUS.SUCCESS, { items, ...result });
    }
}
