import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { STATUS, ACTIVITY_RESOURCES_TYPE, ITEM_CHANGE_REASON } from '../../../consts';
import { handleCost } from '../../../services/role/rewardService';
import { ActivityGrowthModel } from '../../../db/ActivityGrowth';
import { ActivityDailyGiftsModel } from '../../../db/ActivityDailyGifts';
import { addReward, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { ActivityDailyChallengesModel } from '../../../db/ActivityDailyChallenges';
import { ActivityGrowthPointModel } from '../../../db/ActivityGrowthPoint';
import { getPlayerSevenDaysData, getPlayerSevenDaysGrowthData, getPlayerSevenDaysDailyChallengesData, getPlayerSevenDaysDailyGiftsData } from '../../../services/activity/sevenDaysService';
import { SevenDaysGrowthItem, SevenDaysPointRewardItem, SevenDaysDailyItem, SevenDaysDailyGiftItem } from '../../../domain/activityField/sevenDaysField';


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

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


    /**
       * @description 获取七天乐活动总的数据
       * @param {{ activityId: number}} msg
       * @param {BackendSession} session
       * @memberof SevenDaysHandler
       */
    async getSevenDaysActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

        let playerData = await getPlayerSevenDaysData(activityId, serverId, roleId)

        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);

        return resResult(STATUS.SUCCESS, playerData);
    }

    /************************成长任务****************************/

    /**
        * @description 获取成长任务每天完成的单个奖励
        * @param {{ activityId: number, dayIndex: number, cellIndex: number, type: number}} msg
        * @param {BackendSession} session
        * @memberof SevenDaysHandler
        */
    async getGrowthCellReward(msg: { activityId: number, dayIndex: number, cellIndex: number, type: number }, session: BackendSession) {
        const { activityId, dayIndex, cellIndex, type } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

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

        let growthItemData: SevenDaysGrowthItem = playerData.growth.findGrowthItem(dayIndex, cellIndex, type);
        if (!growthItemData) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }
        if (!growthItemData.isComplete()) {//未完成任务
            return resResult(STATUS.ACTIVITY_TASK_UNCOMPLETED);
        }
        if (!growthItemData.canReceive()) {//已经领取过
            return resResult(STATUS.ACTIVITY_REWARDED);
        }

        await ActivityGrowthModel.addCellRecord(serverId, activityId, roleId, dayIndex, cellIndex, 1);
        let rewardParamArr: Array<RewardParam> = stringToRewardParam(growthItemData.reward);
        let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.GROWTH_REWARD)

        growthItemData.receiveRewardCount = 1;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, dayIndex, cellIndex, type },
            item: growthItemData,
        }));
    }

    /**
        * @description 成长任务每天奖章兑换奖励
        * @param {{ activityId: number, id: number}} msg
        * @param {BackendSession} session
        * @memberof SevenDaysHandler
        */
    async getGrowthDayReward(msg: { activityId: number, id: number }, session: BackendSession) {
        const { activityId, id } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

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

        let pointItemData: SevenDaysPointRewardItem = playerData.growth.findPointItem(id);
        if (!pointItemData) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }
        if (playerData.growth.getTotalPoint() < pointItemData.progress) {
            return resResult(STATUS.ACTIVITY_NO_POINT);
        }
        if (pointItemData.getPointReward) {//已经领取过
            return resResult(STATUS.ACTIVITY_REWARDED);
        }

        await ActivityGrowthPointModel.addRecord(serverId, activityId, roleId, id);

        let rewardParamArr: Array<RewardParam> = stringToRewardParam(pointItemData.reward);
        let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.GROWTH_DAY_EXCHANGE)


        pointItemData.getPointReward = true;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, id },
            item: pointItemData,
        }));
    }

    /************************今日挑战****************************/

    /**
        * @description 获取今日挑战的单个奖励
        * @param {{ activityId: number, dayIndex: number, cellIndex: number, type: number}} msg
        * @param {BackendSession} session
        * @memberof SevenDaysHandler
        */
    async getDailyChallengeReward(msg: { activityId: number, dayIndex: number, cellIndex: number, type: number }, session: BackendSession) {
        const { activityId, dayIndex, cellIndex, type } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

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

        let dailyItemData: SevenDaysDailyItem = playerData.dailyChallenge.findDailyChallengesItem(dayIndex, cellIndex, type);
        if (!dailyItemData) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }
        if (!dailyItemData.isComplete()) {//未完成任务
            return resResult(STATUS.ACTIVITY_TASK_UNCOMPLETED);
        }
        if (!dailyItemData.canReceive()) {//已经领取过
            return resResult(STATUS.ACTIVITY_REWARDED);
        }

        await ActivityDailyChallengesModel.addCellRecord(serverId, activityId, roleId, dayIndex, cellIndex, 1);

        let rewardParamArr: Array<RewardParam> = stringToRewardParam(dailyItemData.reward);
        let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.DAILY_CHALLENGE_REWARD)

        dailyItemData.receiveRewardCount = 1;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, dayIndex, cellIndex, type },
            item: dailyItemData,
        }));
    }


    /************************每日特惠礼包****************************/

    /**
        * @description 购买每日特惠礼包
        * @param {{ activityId: number, dayIndex: number, cellIndex: number}} msg
        * @param {BackendSession} session
        * @memberof SevenDaysHandler
        */
    async buyDailyGiftsCell(msg: { activityId: number, dayIndex: number, cellIndex: number }, session: BackendSession) {
        const { activityId, dayIndex, cellIndex } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

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

        let dailyItemData: SevenDaysDailyGiftItem = playerData.dailyGift.findDailyGiftsItem(dayIndex, cellIndex);
        if (!dailyItemData) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }
        if (!dailyItemData.canBuy()) {//最大次数
            return resResult(STATUS.ACTIVITY_MAX_COUNT);
        }
        if (dayIndex > playerData.today()) {//还未开启
            return resResult(STATUS.ACTIVITY_UNOPENED);
        }

        //货币是否足够
        let consumeData = dailyItemData.consumeRes();
        let consumeType = consumeData.type;//购买类型

        if (consumeType == ACTIVITY_RESOURCES_TYPE.GOODS) {//物品表，元宝、金币、体力
            let result = await handleCost(roleId, sid, [{ id: consumeData.id, count: consumeData.count }], ITEM_CHANGE_REASON.BUY_DAILY_GIFTS);
            if (!result) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);
        } else if (consumeType == ACTIVITY_RESOURCES_TYPE.RMB) {//RMB购买
            return resResult(STATUS.ACTIVITY_NEED_PAY);
        }

        await ActivityDailyGiftsModel.buyRecord(serverId, activityId, roleId, dayIndex, cellIndex, 1);

        let rewardParamArr: Array<RewardParam> = stringToRewardParam(dailyItemData.reward);
        let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.BUY_DAILY_GIFTS)

        dailyItemData.buyCount += 1;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, dayIndex, cellIndex },
            item: dailyItemData,
        }));
    }

}
