import { Application, BackendSession } from 'pinus';
import { resResult, splitString } from '../../../pubUtils/util';
import { ACTIVITY_RESOURCES_TYPE, CURRENCY_BY_TYPE, CURRENCY, STATUS, CURRENCY_TYPE, } from '../../../consts';
import { getPlayerPopUpShopData } from '../../../services/activity/popUpShopService';
import { ActivityModel, ActivityModelType } from '../../../db/Activity';
import { ActivityPopUpShopModel, ActivityPopUpShopModelType } from '../../../db/ActivityPopUpShop';
import { PopUpShopData } from '../../../domain/activityField/popUpShopField';
import { addReward, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { handleCost } from '../../../services/rewardService';
import moment = require('moment');

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

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

    /************************弹出式商店****************************/

    /**
    * @description 获取弹出式商店数据
    * @param {{ }} msg
    * @param {{ activityId: number}} msg
    * @param {BackendSession} session
    * @memberof PopUpShopHandler
    */
    async getPopUpShopActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

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

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

    /**
        * @description 购买礼包
        * @param {{ activityId: number,  id: number, beginTimeStamp: number}} msg
        * @param {BackendSession} session
        * @memberof PopUpShopHandler
        */
    async buyGift(msg: { activityId: number, id: number, beginTimeStamp: number }, session: BackendSession) {
        const { activityId, id, beginTimeStamp } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        const funcs: number[] = session.get('funcs');
        let beginTime = moment(beginTimeStamp).toDate();

        let activityData: ActivityModelType = await ActivityModel.findActivity(activityId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }

        let allTaskData: any[] = JSON.parse(activityData.data);
        let taskIndex = allTaskData.findIndex(obj => { return obj && obj.id == id });
        if (taskIndex == -1) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }

        let playerData = new PopUpShopData(allTaskData[taskIndex], activityId);

        if (playerData.price) {
            return resResult(STATUS.ACTIVITY_NEED_PAY);
        }

        if (playerData.consume) {
            return resResult(STATUS.ACTIVITY_NEED_PAY);
        }

        let playerRecords: ActivityPopUpShopModelType = await ActivityPopUpShopModel.findDataByBeginTime(serverId, activityId, roleId, id, playerData.taskType, beginTime);
        if (!playerRecords) {
            return resResult(STATUS.ACTIVITY_POP_UP_SHOP_EXPIRE);
        }
        if (playerRecords.buyCount >= playerData.count) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT);
        }

        if (playerData.condition > playerRecords.totalCount) {
            return resResult(STATUS.ACTIVITY_TASK_UNCOMPLETED);
        }

        //元宝消费
        let arr = splitString(playerData.consume, '&')
        if (arr[0] != ACTIVITY_RESOURCES_TYPE.GOODS || arr[1] != CURRENCY_BY_TYPE.get(CURRENCY_TYPE.GOLD)) {
            return resResult(STATUS.ACTIVITY_GOLD_RESOURCE);
        }
        let price = arr[2];//数量
        let resourceResult = await handleCost(roleId, sid, [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.GOLD), count: price }]);
        if (!resourceResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

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

        await ActivityPopUpShopModel.addRecord(serverId, activityId, roleId, id, playerData.taskType, 1, beginTime);

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

}
