import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ACTIVITY_TYPE, ITEM_CHANGE_REASON, STATUS } from '../../../consts';
import { newPlayerLimitPackageActivity, getPlayerLimitPackageData } from '../../../services/activity/limitPackageService';
import { addReward, stringToConsumeParam, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { ActivityShopModel } from '../../../db/ActivityShop';
import moment = require('moment');
import { RoleModel } from '../../../db/Role';
import { handleCost } from '../../../services/role/rewardService';

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

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

    /************************新手限定礼包****************************/

    /**
    * @description 获取新手限定活动数据 开服1-7天可以购买，第8天0-5点只能看，不能买
    * @param {{ activityId:number}} msg
    * @param {BackendSession} session
    * @memberof LimitPackageHandler
    */
    async getNewPlayerLimitPackageActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');


        let { createTime } = await RoleModel.findByRoleId(roleId);
        let createDate = moment(createTime * 1000).toDate();
        let endTime = moment(createDate).startOf('d').add(7, 'd').add(5, 'h').toDate();
        if (new Date() > endTime) {
            return resResult(STATUS.ACTIVITY_NEW_PLAYER_GIFT_END);
        }
        let playerData = await newPlayerLimitPackageActivity(serverId, roleId);
        if (!playerData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }
        return resResult(STATUS.SUCCESS, { playerData });
    }

    /************************每日每周限购礼包****************************/

    /**
    * @description 获取每日/每周限购礼包数据
    * @param {{ activityId:number, type:number }} msg
    * @param {BackendSession} session
    * @memberof LimitPackageHandler
    */
    async getLimitPackageActivity(msg: { activityId: number, type: number }, session: BackendSession) {
        const { activityId, type } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

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


    /**
        * @description 购买礼包
        * @param {{ activityId: number, roundIndex: number, id: number}} msg
        * @param {BackendSession} session
        * @memberof LimitPackageHandler
        */
    async buyGood(msg: { activityId: number, roundIndex: number, id: number }, session: BackendSession) {
        const { activityId, roundIndex, 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 getPlayerLimitPackageData(activityId, serverId, roleId);
        if (!playerData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }

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

        switch (playerData.type) {
            case ACTIVITY_TYPE.NEW_PLAYER_LIMIT_PACKAGE:
                {
                    let { createTime } = await RoleModel.findByRoleId(roleId);
                    let createDate = moment(createTime * 1000).toDate();
                    let endTime = moment(createDate).startOf('d').add(7, 'd').toDate();
                    if (new Date() > endTime) {
                        return resResult(STATUS.ACTIVITY_NEW_PLAYER_LIMIT_PACKAGE_END);
                    }
                    break;
                }
            default:
                break;
        }

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

        //检查资源
        let consume = stringToConsumeParam(item.consume)
        let consumeResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.BUY_LIMIT_PACKAGE);
        if (!consumeResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        let rewardArray = stringToRewardParam(item.reward)
        let result = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.BUY_LIMIT_PACKAGE);

        await ActivityShopModel.addRecord(activityId, roleId, roundIndex, id, 1);

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

}
