import { Application, BackendSession, HandlerService } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { LAND_TYPE, STATUS, CURRENCY_TYPE, CURRENCY_BY_TYPE, BANK_TYPE, ACTIVITY_RESOURCES_TYPE, ITEM_CHANGE_REASON } from '../../../consts';
import { ActivityMonopolyModel, ActivityMonopolyModelType } from '../../../db/ActivityMonopoly';
import { ActivityMonopolyLandModel, ActivityMonopolyLandModelType } from '../../../db/ActivityMonopolyLand';
import { getPlayerMonopolyData, nextPosition } from '../../../services/activity/monopolyService';
import { random } from 'underscore';
import { handleCost } from '../../../services/role/rewardService';
import { addReward, stringToConsumeParam, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { getPlayerRefreshShopDataByRoundIndex } from '../../../services/activity/refreshShopService';
import { ActivityRefreshShopModel } from '../../../db/ActivityRefreshShop';

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

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


    /**
    * @description 获取大富翁活动数据
    * @param {{activityId: number }} msg
    * @param {BackendSession} session
    * @memberof ActivityMonopolyHandler
    */
    async getMonopolyActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid: string = session.get('sid');
        

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

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

        return resResult(STATUS.SUCCESS, playerData);
    }


    /**
    * @description 移动
    * @param {{activityId: number }} msg
    * @param {BackendSession} session
    * @memberof ActivityMonopolyHandler
    */
    async move(msg: { activityId: number, step: number }, session: BackendSession) {
        const { activityId, step } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid: string = session.get('sid');
        
        const roleName = session.get('roleName');

        let moveStep = 0;
        if (step >= 1 && step <= 6) {//指定，天机骰子
            //检查资源
            let consumeResult = await handleCost(roleId, sid, [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.SPECIAL_DICE), count: 1 }], ITEM_CHANGE_REASON.MONOPOLY_MOVE);
            if (!consumeResult) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);
            moveStep = step;
        } else {//普通骰子
            //检查资源
            let consumeResult = await handleCost(roleId, sid, [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.NORMAL_DICE), count: 1 }], ITEM_CHANGE_REASON.MONOPOLY_MOVE);
            if (!consumeResult) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);
            moveStep = random(5) + 1;
        }
        let playerData = await getPlayerMonopolyData(activityId, serverId, roleId)

        let oldPosition = playerData.curPosition;
        let newPosition = nextPosition(oldPosition, moveStep, playerData.list.length);
        await ActivityMonopolyModel.updatePosition(serverId, activityId, roleId, newPosition, 1)

        let landData = playerData.findMonopolyItem(newPosition);
        let landReward = null;//土地奖励
        let bankReward = null;//银行奖励
        if (landData && landData.landType == LAND_TYPE.BANK_NORMAL) {
            //土地奖励
            if (landData.rewards.length > landData.stopCount) {
                let reward = landData.rewards[landData.level - 1];
                let rewardArray = stringToRewardParam(reward)
                landReward = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.MONOPOLY_MOVE);
            }

            //土地升级
            if (landData.rewards.length > landData.level) {
                let newLevel = landData.level + 1;
                await ActivityMonopolyLandModel.updateLevel(serverId, activityId, roleId, newPosition, newLevel)
                landData.level = newLevel;
            }

            //取钱
            if (landData.record.length > 0) {
                let records = landData.record.filter(obj => { return obj.type == BANK_TYPE.OUT });
                if (records.length < landData.takeOutMax) {
                    let resource = landData.record[0].resource;
                    let rewardArray = stringToRewardParam(resource)
                    bankReward = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.MONOPOLY_MOVE);
                    let recordResult = await ActivityMonopolyLandModel.addRecord(serverId, activityId, roleId, newPosition, BANK_TYPE.OUT, resource);
                    landData.record = recordResult.record;
                }
            }
        } else if (landData && ((landData.landType == LAND_TYPE.BANK_COIN) || (landData.landType == LAND_TYPE.BANK_GOLD))) {
            //取钱
            if (landData.record.length > 0) {
                let records = landData.record.filter(obj => { return obj.type == BANK_TYPE.OUT });
                if (records.length < landData.takeOutMax) {
                    let resource = landData.record[0].resource;
                    let rewardArray = stringToRewardParam(resource)
                    bankReward = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.MONOPOLY_MOVE);
                    let recordResult = await ActivityMonopolyLandModel.addRecord(serverId, activityId, roleId, newPosition, BANK_TYPE.OUT, resource);
                    landData.record = recordResult.record;
                }
            }
        }
        await ActivityMonopolyLandModel.updateStopCount(serverId, activityId, roleId, newPosition);
        landData.stopCount += 1;
        return resResult(STATUS.SUCCESS, { landReward, bankReward, landData, moveStep, newPosition, roundIndex: playerData.roundIndex + 1, });
    }

    /**
   * @description 存钱
   * @param {{activityId: number ,addCount: number}} msg
   * @param {BackendSession} session
   * @memberof ActivityMonopolyHandler
   */
    async bank(msg: { activityId: number, addCount: number }, session: BackendSession) {
        const { activityId, addCount } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid: string = session.get('sid');
        
            let playerData = await getPlayerMonopolyData(activityId, serverId, roleId)
            let curPosition = playerData.curPosition;
            if (curPosition == 0) {
                return resResult(STATUS.MONOPOLY_LAND_TYPE_ERROR);
            }
            let landData = playerData.findMonopolyItem(curPosition);
            if (landData.landType != LAND_TYPE.BANK_NORMAL
                && landData.landType != LAND_TYPE.BANK_COIN
                && landData.landType != LAND_TYPE.BANK_GOLD) {
                return resResult(STATUS.MONOPOLY_LAND_TYPE_ERROR);
            }
            if (landData.record.length != 0) {
                return resResult(STATUS.MONOPOLY_BANK);
            }
            if (addCount > landData.saveMax) {
                return resResult(STATUS.MONOPOLY_BANK_SAVE_MAX);
            }

            let resrouseStr = '';
            if (landData.landType == LAND_TYPE.BANK_COIN
                || landData.landType == LAND_TYPE.BANK_NORMAL) {
                resrouseStr = `${ACTIVITY_RESOURCES_TYPE.GOODS}&${CURRENCY_BY_TYPE.get(CURRENCY_TYPE.COIN)}&${addCount}`
                //检查资源
                let consumeResult = await handleCost(roleId, sid, [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.COIN), count: addCount }], ITEM_CHANGE_REASON.MONOPOLY_BANK);
                if (!consumeResult) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);
            } else if (landData.landType == LAND_TYPE.BANK_GOLD) {
                resrouseStr = `${ACTIVITY_RESOURCES_TYPE.GOODS}&${CURRENCY_BY_TYPE.get(CURRENCY_TYPE.GOLD)}&${addCount}`
                //检查资源
                let consumeResult = await handleCost(roleId, sid, [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.GOLD), count: addCount }], ITEM_CHANGE_REASON.MONOPOLY_BANK);
                if (!consumeResult) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);
            }

            let recordResult = await ActivityMonopolyLandModel.addRecord(serverId, activityId, roleId, curPosition, BANK_TYPE.IN, resrouseStr);
            landData.record = recordResult.record;
            return resResult(STATUS.SUCCESS, { landData });

    }


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

        let playerMonopolyData: ActivityMonopolyModelType = await ActivityMonopolyModel.findData(serverId, activityId, roleId);
        let playerLandData: ActivityMonopolyLandModelType = await ActivityMonopolyLandModel.findDataByPosition(serverId, activityId, roleId, playerMonopolyData.curPosition);
        let playerShopData = await getPlayerRefreshShopDataByRoundIndex(shopActivityId, serverId, roleId, playerLandData.stopCount);
        if (!playerShopData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }
        return resResult(STATUS.SUCCESS, { playerShopData });
    }


    /**
        * @description 购买非RMB商品
        * @param {{ monopolyActivityId:number, shopActivityId: number, roundIndex: number, id: number, pageIndex: number}} msg
        * @param {BackendSession} session
        * @memberof RefreshShopHandler
        */
    async buyGood(msg: { monopolyActivityId, shopActivityId: number, roundIndex: number, id: number, pageIndex: number }, session: BackendSession) {
        const { monopolyActivityId, shopActivityId, roundIndex, id, pageIndex } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        
        let playerMonopolyData: ActivityMonopolyModelType = await ActivityMonopolyModel.findData(serverId, monopolyActivityId, roleId);
        let playerData = await getPlayerMonopolyData(monopolyActivityId, serverId, roleId)
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let landItem = playerData.findMonopolyItem(playerMonopolyData.curPosition)
        if (landItem.stopCount > landItem.shoppingCountMax) {
            return resResult(STATUS.SHOP_CLOSED);
        }
        let playerShopData = await getPlayerRefreshShopDataByRoundIndex(shopActivityId, serverId, roleId, landItem.stopCount);
        if (!playerShopData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }

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

        let item = playerShopData.findItem(id, pageIndex);
        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.MONOPOLY_BUY_GOODS);
        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.MONOPOLY_BUY_GOODS);

        await ActivityRefreshShopModel.addRecord(shopActivityId, roleId, roundIndex, pageIndex, id, 1);

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