import { Application, BackendSession } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { STATUS, } from '../../../consts';
import { getPlayerTreasureHuntData, getTreasureHuntData, getPlayerTreasureHuntShopData, getPlayerTreasureHuntTaskData, getPlayerTreasureHuntTreasureShopData, getPlayerTreasureHuntChallengeData, getPlayerTreasureHuntFirstPageData } from '../../../services/activity/treasureHuntService';
import { ActivityTreasureHuntShopModel } from '../../../db/ActivityTreasureHuntShop';
import { ActivityTreasureHuntTaskModel } from '../../../db/ActivityTreasureHuntTask';
import { handleCost } from '../../../services/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';


export default function (app: Application) {
    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 { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex, activityData } = await getTreasureHuntData(serverId, roleId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        let playerData = await getPlayerTreasureHuntData(activityId, serverId, roleId, huntRoundIndex, huntBeginTime, huntEndTime);
        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');
        const funcs: number[] = session.get('funcs');

        let { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex, activityData } = await getTreasureHuntData(serverId, roleId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (activityId !== huntActivityId) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }

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

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

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

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

        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 }, 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');
        const funcs: number[] = session.get('funcs');

        let { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex, activityData } = await getTreasureHuntData(serverId, roleId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (activityId !== huntActivityId) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }

        let playerData = await getPlayerTreasureHuntShopData(activityId, serverId, roleId, huntRoundIndex, huntBeginTime, huntEndTime,);
        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 >= item.countMax) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT, {});
        }

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

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

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

        item.buyCount += 1;
        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');
        const funcs: number[] = session.get('funcs');

        let { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex, activityData } = await getTreasureHuntData(serverId, roleId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (activityId !== huntActivityId) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }

        let playerData = await getPlayerTreasureHuntTaskData(activityId, serverId, roleId, huntRoundIndex, huntBeginTime, huntEndTime,);
        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, huntRoundIndex, cellIndex, 1);

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

        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');
        const funcs: number[] = session.get('funcs');

        let { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex, activityData } = await getTreasureHuntData(serverId, roleId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (activityId !== huntActivityId) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }

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

        let warId = playerData.challenge.randomGK();

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

    /**
    * @description 寻宝骑兵购买天子宝库商店中的商品
    * @param {BackendSession} session
    * @memberof TreasureHuntHandler
    */
    async buyTreasureShopGoods(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');
        const funcs: number[] = session.get('funcs');

        let { huntActivityId, huntBeginTime, huntEndTime, huntRoundIndex, activityData } = await getTreasureHuntData(serverId, roleId);
        if (!activityData) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }
        if (activityId !== huntActivityId) {
            return resResult(STATUS.ACTIVITY_MISSING, {});
        }

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

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

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

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

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