import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ITEM_CHANGE_REASON, STATUS, } from '../../../consts';
import { getPlayerTreasureHuntData, getPlayerTreasureHuntShopData, getPlayerTreasureHuntTaskData, getPlayerTreasureHuntTreasureShopData, getPlayerTreasureHuntChallengeData, getPlayerTreasureHuntFirstPageData } from '../../../services/activity/treasureHuntService';
import { ActivityTreasureHuntShopModel } from '../../../db/ActivityTreasureHuntShop';
import { ActivityTreasureHuntTaskModel } from '../../../db/ActivityTreasureHuntTask';
import { handleCost } from '../../../services/role/rewardService';
import { addReward, stringToConsumeParam, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { ActivityTreasureHuntTreasureShopModel } from '../../../db/ActivityTreasureHuntTreasureShop';
import { ActivityTreasureHuntFirstPageModel } from '../../../db/ActivityTreasureHuntFirstPage';
import { CheckMeterial } from '../../../services/role/checkMaterial';
import { ActivityTreasureHuntChallengeModel } from '../../../db/ActivityTreasureHuntChallenge';


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

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

    /************************寻宝骑兵活动****************************/

    /**
     * 每日物资：商店
       寻宝备战：完成任务获得奖励，(奖品达到一定数量后开启 “寻宝大冒险”)
       寻宝大冒险：完成战棋关卡获得奖励
       天子宝库：物品兑换奖励
    * @description 获取寻宝骑兵活动的数据
    * @param {BackendSession} session
    * @memberof TreasureHuntHandler
    */
    async getTreasureHuntActivity(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        let playerData = await getPlayerTreasureHuntData(activityId, serverId, roleId);
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);

        return resResult(STATUS.SUCCESS, playerData);
    }

    /**
* @description 寻宝骑兵获取首页的奖励
* @param {BackendSession} session
* @memberof TreasureHuntHandler
*/
    async getFirstPageReward(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');

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

        if (playerData.firstPage.isReceive) {
            return resResult(STATUS.ACTIVITY_REWARDED);
        }

        //添加领取记录
        await ActivityTreasureHuntFirstPageModel.receiveReward(serverId, activityId, roleId, playerData.roundIndex);

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

        playerData.firstPage.isReceive = true;
        return resResult(STATUS.SUCCESS, Object.assign(result, {
            param: { activityId },
            item: playerData.firstPage,
        }));
    }

    /**
  * @description 寻宝骑兵购买每日商店中的商品
  * @param {BackendSession} session
  * @memberof TreasureHuntHandler
  */
    async buyGoods(msg: { activityId: number, cellIndex: number, count: number }, session: BackendSession) {
        const { activityId, cellIndex, count = 1 } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        
        let playerData = await getPlayerTreasureHuntShopData(activityId, serverId, roleId,);
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let item = playerData.shop.getItem(cellIndex);
        if (!item) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (item.price > 0) {
            return resResult(STATUS.ACTIVITY_NEED_PAY, {});
        }
        if (item.buyCount + count > item.countMax) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT, {});
        }

        let consumeStr = item.getConsume(count);
        let consume = stringToConsumeParam(...consumeStr);
        let resourceResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.TREASURE_HUNT_SHOP_BUY);
        if (!resourceResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        //添加购买记录
        await ActivityTreasureHuntShopModel.buyShopRecord(activityId, roleId, playerData.roundIndex, playerData.todayIndex, cellIndex, count);

        let rewardParamArr: Array<RewardParam> = stringToRewardParam(item.reward).map(cur => ({...cur, count: cur.count * count }));
        let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.TREASURE_HUNT_SHOP_BUY)

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

    /**
 * @description 寻宝骑兵获取寻宝备战的任务奖励
 * @param {BackendSession} session
 * @memberof TreasureHuntHandler
 */
    async getTaskReward(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 getPlayerTreasureHuntTaskData(activityId, serverId, roleId);
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let item = playerData.tasks.getItem(cellIndex);
        if (!item) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (item.condition > item.totalCount) {
            return resResult(STATUS.ACTIVITY_TASK_UNCOMPLETED, {});
        }
        if (item.isReceive) {
            return resResult(STATUS.ACTIVITY_REWARDED, {});
        }

        //添加购买记录
        await ActivityTreasureHuntTaskModel.receiveReward(serverId, activityId, roleId, playerData.roundIndex, cellIndex, 1);

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

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

    /**
    * @description 寻宝骑兵寻宝大冒险挑战
    * @param {BackendSession} session
    * @memberof TreasureHuntHandler
    */
    async challenge(msg: { activityId: number }, session: BackendSession) {
        const { activityId } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');

        let playerData = await getPlayerTreasureHuntChallengeData(activityId, serverId, roleId,);
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let challengeData = playerData.challenge;
        //消耗资源
        let consumeStr = challengeData.consume;
        let consume = stringToConsumeParam(consumeStr)

        let check = new CheckMeterial(roleId);
        let isEnough = await check.decrease(consume);
        if (!isEnough) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        let warId = playerData.challenge.resultWarId;
        if(!warId) {
            warId = playerData.challenge.randomGK();
            await ActivityTreasureHuntChallengeModel.setWarId(serverId, activityId, roleId, playerData.roundIndex, warId);
        }

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

    /**
    * @description 寻宝骑兵购买天子宝库商店中的商品
    * @param {BackendSession} session
    * @memberof TreasureHuntHandler
    */
    async buyTreasureShopGoods(msg: { activityId: number, cellIndex: number, count: number }, session: BackendSession) {
        const { activityId, cellIndex, count = 1 } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');

        let playerData = await getPlayerTreasureHuntTreasureShopData(activityId, serverId, roleId,);
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let item = playerData.treasureShop.getItem(cellIndex);
        if (!item) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (item.buyCount + count > item.countMax) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT, {});
        }

        let consumeStrs = new Array<string>(count).fill(item.consume);
        let consume = stringToConsumeParam(...consumeStrs);
        let resourceResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.TREASURE_HUNT_SP_SHOP_BUY);
        if (!resourceResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        //添加购买记录
        await ActivityTreasureHuntTreasureShopModel.addRecord(activityId, roleId, playerData.roundIndex, cellIndex, count);

        let rewardParamArr: Array<RewardParam> = stringToRewardParam(item.reward).map(cur => ({...cur, count: cur.count * count}));
        let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.TREASURE_HUNT_SP_SHOP_BUY)

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