import { Application, BackendSession, HandlerService } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ACTIVITY_RESOURCES_TYPE, CURRENCY_BY_TYPE, CURRENCY_TYPE, DAILY_COIN_BOX_STATUS, ITEM_CHANGE_REASON, STATUS } from '../../../consts';
import { getGoldObject, handleCost } from '../../../services/role/rewardService';
import { getPlayerDailyCoinData, mergeData } from '../../../services/activity/dailyCoinService';
import { ConsumeExchangeFormulaItem, CoinRewardFormulaItem } from '../../../domain/activityField/dailyCoinField';
import { ActivityDailyCoinModel } from '../../../db/ActivityDailyCoin';
import { addReward, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { ItemInter } from '../../../pubUtils/interface';
import { RoleModel } from '../../../db/Role';
import moment = require('moment');


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

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


    /************************每日兑换铜币****************************/

    /**
        * @description 获取每日铜币活动数据
        * @param {{ activityId: number}} msg
        * @param {BackendSession} session
        * @memberof DailyCoinHandler
        */
    async getDailyCoinActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

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

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

        return resResult(STATUS.SUCCESS, playerData);
    }

    /**
        * @description 兑换
        * @param {{ activityId: number, count:number}} msg
        * @param {BackendSession} session
        * @memberof DailyCoinHandler
        */
    async exchangeCoin(msg: { activityId: number, count: number }, session: BackendSession) {
        const { activityId, count } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');

        let playerData = await getPlayerDailyCoinData(activityId, serverId, roleId)
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let curIndex = playerData.exchangeCount;
        if (curIndex + count > playerData.countMax) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT);
        }
        let allConsume: Array<ItemInter> = []
        let allReward: Array<RewardParam> = [];
        let role = await RoleModel.findByRoleId(roleId)
        let rateArray = [];//暴击记录
        for (let i = 1; i <= count; i++) {
            let index = curIndex + i;
            if (index > playerData.freeCount) {//消耗资源
                let consumeItem: ConsumeExchangeFormulaItem = playerData.findConsumeExchangeFormulaItem(index);
                let times = index;
                let consumeCount = eval(consumeItem.consumeFormula)
                let consume = getGoldObject(consumeCount)
                allConsume = allConsume.concat(consume)
            }
            let rate = playerData.getRate()//翻几倍
            rateArray.push(rate);
            let lv = role.lv;//玩家等级
            let rewardItem: CoinRewardFormulaItem = playerData.findCoinRewardFormulaItem(lv);
            if (!rewardItem) {
                return resResult(STATUS.ACTIVITY_DATA_ERROR);
            }
            let coinRewardCount = eval(rewardItem.rewardFormula);
            // console.log('******** coinReward', lv, rewardItem.rewardFormula, coinRewardCount)

            let baseRewardParamArr: Array<RewardParam> = [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.COIN), count: coinRewardCount, type: ACTIVITY_RESOURCES_TYPE.GOODS }];
            // console.log('第几次抽奖:', index, ' 基础奖励翻倍:', rate, JSON.stringify(baseRewardParamArr),)
            for (let reward of baseRewardParamArr) {
                reward.count = reward.count * rate;
            }
            allReward = allReward.concat(baseRewardParamArr);
        }

        let newConsume = mergeData(allConsume);
        let newReward = mergeData(allReward);
        // console.log('所有消耗', JSON.stringify(newConsume))
        // console.log('所有奖励', JSON.stringify(newReward))

        //检查资源
        let consumeResult = await handleCost(roleId, sid, newConsume, ITEM_CHANGE_REASON.DAILY_COIN_EXCHANGE);
        if (!consumeResult) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);

        let addCoin = 0
        let coinId = CURRENCY_BY_TYPE.get(CURRENCY_TYPE.COIN);
        for (let obj of newReward) {
            if (obj.id === coinId) {
                addCoin += obj.count;
            }
        }

        let consumeGold = 0;
        let goldId = CURRENCY_BY_TYPE.get(CURRENCY_TYPE.GOLD);
        for (let obj of newConsume) {
            if (obj.id === goldId) {
                consumeGold += obj.count;
            }
        }

        //免费期间
        let time = moment(new Date()).valueOf();
        let result = await addReward(roleId, roleName, sid, serverId, newReward, ITEM_CHANGE_REASON.DAILY_COIN_EXCHANGE);

        let extraReward = playerData.addExchangeCount(count);
        await ActivityDailyCoinModel.addExchangeRecord(serverId, activityId, roleId, playerData.roundIndex, count, addCoin, `${count}&${consumeGold}&${addCoin}&${time}`, playerData.hasNotReceivedBox());

        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId, count, extraReward },
            item: { exchangeCount: playerData.exchangeCount, recordMsg: `${count}&${consumeGold}&${addCoin}&${time}`, rateArray },
        }));
    }


    /**
        * @description 领取宝箱
        * @param {{ activityId: number, cellIndex:number}} msg
        * @param {BackendSession} session
        * @memberof DailyCoinHandler
        */
     async receiveExtraReward(msg: { activityId: number, cellIndex: number }, session: BackendSession) {
        const { activityId, 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 getPlayerDailyCoinData(activityId, serverId, roleId)
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let box = await playerData.findBoxByCellIndex(cellIndex);
        if(!box) return resResult(STATUS.DAILY_COIN_BOX_NOT_FOUND);
        if(box.status != DAILY_COIN_BOX_STATUS.CAN_OPEN) return resResult(STATUS.DAILY_COIN_BOX_CANNOT_RECEIVE);
       
        let rewardArray = stringToRewardParam(box.reward)
        let result = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.ACT_DAILY_COIN_RECEIVE_BOX);

        let item = playerData.receiveBox(cellIndex);
        await ActivityDailyCoinModel.receiveBox(serverId, activityId, roleId, playerData.roundIndex, cellIndex, playerData.hasNotReceivedBox());

        return resResult(STATUS.SUCCESS, Object.assign(result, {
            item,
            param: { activityId },
        }));
    }

}
