import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ITEM_CHANGE_REASON, STATUS } from '../../../consts';
import { getPlayerRefreshTaskData } from '../../../services/activity/refreshTaskService';
import { RefreshTaskItem } from '../../../domain/activityField/refreshTaskField';
import { addReward, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { ActivityRefreshTaskModel } from '../../../db/ActivityRefreshTask';
import { ActivityRefreshTaskPointModel } from '../../../db/ActivityRefreshTaskPoint';


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

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

    /************************通用的刷新任务（分页，可刷新，限制领取次数）****************************/

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

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

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

        return resResult(STATUS.SUCCESS, playerData);
    }

    /**
        * @description 获取奖励
        * @param {{ activityId: number, roundIndex: number, pageIndex: number,id: number, type: number}} msg
        * @param {BackendSession} session
        * @memberof RefreshTaskHandler
        */
    async getReward(msg: { activityId: number, roundIndex: number, pageIndex: number, id: number, type: number }, session: BackendSession) {
        const { activityId, roundIndex, pageIndex, id, 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 getPlayerRefreshTaskData(activityId, serverId, roleId)
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        if (playerData.roundIndex != roundIndex) {
            return resResult(STATUS.ACTIVITY_EXPIRE);
        }
        let dailyItemData: RefreshTaskItem = playerData.findItem(pageIndex, id, type);
        if (!dailyItemData) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }
        if (dailyItemData.totalCount < dailyItemData.condition) {//未完成任务
            return resResult(STATUS.ACTIVITY_TASK_UNCOMPLETED);
        }
        if (dailyItemData.receiveRewardCount) {//已经领取过
            return resResult(STATUS.ACTIVITY_REWARDED);
        }

        await ActivityRefreshTaskModel.addReceiveRecord(serverId, activityId, roleId, roundIndex, pageIndex, id, dailyItemData.getRefTime(), 1);

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

        //获得点数
        await ActivityRefreshTaskPointModel.addPoint(serverId, activityId, roleId, dailyItemData.point);

        dailyItemData.receiveRewardCount += 1;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, roundIndex, pageIndex, id, type },
            item: dailyItemData,
            totalPoint: playerData.totalPoint + dailyItemData.point,
        }));
    }

    /**
        * @description 兑换点数
        * @param {{ activityId: number, roundIndex: number}} msg
        * @param {BackendSession} session
        * @memberof RefreshTaskHandler
        */
    async exchangePoint(msg: { activityId: number, roundIndex: number }, session: BackendSession) {
        const { activityId, roundIndex } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

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

        if ((playerData.totalPoint - playerData.exchangePoint) < playerData.consumePoint) {//点数不够
            return resResult(STATUS.ACTIVITY_NO_POINT);
        }

        await ActivityRefreshTaskPointModel.addReceiveRecord(serverId, activityId, roleId, playerData.consumePoint);

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

        playerData.exchangePoint += playerData.consumePoint;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, roundIndex },
            item: { exchangePoint: playerData.exchangePoint },
        }));
    }

}
