import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult, splitString } from '../../../pubUtils/util';
import { ITEM_CHANGE_REASON, STATUS, } from '../../../consts';
import { SelfServiceShopData } from '../../../domain/activityField/selfServiceShopField';
import { handleCost } from '../../../services/role/rewardService';
import { ActivitySelfServiceShopModel, ActivitySelfServiceShopModelType } from '../../../db/ActivitySelfServiceShop';
import { ActivitySelfServiceModel } from '../../../db/ActivitySelfService';
import { ActivitySelfServiceGoodsModel } from '../../../db/ActivitySelfServiceGoods';
import { ActivityModel, ActivityModelType } from '../../../db/Activity';
import { addSelfServiceShopGiftReward, getSelfServiceShopActivityData, getPlayerActivityData } from '../../../services/activity/selfServiceShopActivityService';
import { addReward, stringToConsumeParam, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { random } from 'underscore';
import { RoleModel } from '../../../db/Role';
import { getActivityById } from '../../../services/activity/activityService';
import { getRoleCreateTime, getServerCreateTime } from '../../../services/redisService';

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

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

    /************************自助商店、糜家商队****************************/

    /**
    * @description 获取自助商店数据
    * @param {{ }} msg
    * @param {BackendSession} session
    * @memberof SelfServiceShopHandler
    */
    async getSelfServiceShopActivity(msg: {}, session: BackendSession) {
        const { } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');

        let playerData = await getSelfServiceShopActivityData(serverId, roleId)
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);
        let playerGoods = await ActivitySelfServiceGoodsModel.findData(playerData.activityId, roleId, playerData.roundIndex, true);
        return resResult(STATUS.SUCCESS, { playerData, playerGoods: playerGoods ? playerGoods : [] });
    }

    /**
        * @description 购买礼包
        * @param {{ activityId: number, roundIndex: number, index: number, cellIndex: number}} msg
        * @param {BackendSession} session
        * @memberof SelfServiceShopHandler
        */
    async buyGift(msg: { activityId: number, roundIndex: number, index: number }, session: BackendSession) {
        const { activityId, roundIndex, index } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

        let activityData = await getActivityById(activityId);
        let createTime = await getRoleCreateTime(roleId);
        let serverTime = await getServerCreateTime(serverId);
        let playerData = new SelfServiceShopData(activityData, createTime, serverTime);
        let item = playerData.getItem(index);

        if (item.countMax > 0) {//限制购买次数
            let playerRecords: ActivitySelfServiceShopModelType[] = await ActivitySelfServiceShopModel.findDataByIndex(serverId, activityId, roleId, playerData.roundIndex, index);
            if (playerRecords.length >= item.countMax) {
                return resResult(STATUS.ACTIVITY_MAX_COUNT);
            }
        }

        let price = item.price;
        if (price > 0) {//RMB购买
            return resResult(STATUS.ACTIVITY_NEED_PAY);
        }
        //检查资源
        let consume = stringToConsumeParam(item.consume)
        let consumeResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.SELF_SERVICE_SHOP_BUY_GIFT);
        if (!consumeResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        let result = await addSelfServiceShopGiftReward(roleId, roleName, sid, serverId, activityId, roundIndex, index, item);
        return resResult(STATUS.SUCCESS, Object.assign(result, {}));
    }

    /**
       * @description 操作礼包
       * @param {{ data:Array<{activityId: number, roundIndex: number, index: number, cellIndex: number, rewardIndex: number}>}} msg
       * @param {BackendSession} session
       * @memberof SelfServiceShopHandler
       */
    async saveGood(msg: { data: Array<{ activityId: number, roundIndex: number, index: number, cellIndex: number, rewardIndex: number }> }, session: BackendSession) {
        const { data } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

        for (let obj of data) {
            await ActivitySelfServiceGoodsModel.addGoods(obj.activityId, roleId, obj.roundIndex, obj.index, obj.cellIndex, obj.rewardIndex);
        }

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

    /**
        * @description 购买代币资源
        * @param {{ activityId: number, roundIndex: number}} msg
        * @param {BackendSession} session
        * @memberof SelfServiceShopHandler
        */
    async buyRecources(msg: { activityId: number, roundIndex: number }, session: BackendSession) {
        const { activityId, roundIndex } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        

        let activityData: ActivityModelType = await getActivityById(activityId);
        let createTime = await getRoleCreateTime(roleId);
        let serverTime = await getServerCreateTime(serverId);
        let playerData = new SelfServiceShopData(activityData, createTime, serverTime);
        let unitPrice = playerData.unitPrice;//购买价格
        let unitCountMax = playerData.unitCountMax;//最大购买次数
        let unitReward = playerData.unitReward;//购买获得资源

        let playerSelfServerData = await ActivitySelfServiceModel.findData(serverId, activityId, roleId, roundIndex);

        let buyCount = (playerSelfServerData && playerSelfServerData.unitBuyCount) ? playerSelfServerData.unitBuyCount : 0;
        if (buyCount >= unitCountMax) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT);
        }

        //检查资源
        let consume = stringToConsumeParam(unitPrice)
        let consumeResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.SELF_SERVICE_SHOP_BUY_RESOURCE);
        if (!consumeResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        await ActivitySelfServiceModel.addBuyRecord(serverId, activityId, roleId, roundIndex, 1);
        let rewardArray = stringToRewardParam(unitReward)
        let result = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.SELF_SERVICE_SHOP_BUY_RESOURCE);

        return resResult(STATUS.SUCCESS, Object.assign(result, { unitBuyCount: buyCount + 1 }));
    }

    /**
       * @description 获取关卡id
       * @param {{ activityId: number}} msg
       * @param {BackendSession} session
       * @memberof SelfServiceShopHandler
       */
    async getWarId(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 getPlayerActivityData(activityId, serverId, roleId)
        if (!playerData) return resResult(STATUS.ACTIVITY_MISSING);

        if (playerData.challengeCount >= playerData.count) {
            return resResult(STATUS.ACTIVITY_MAX_COUNT);
        }

        let warIdArray = splitString(playerData.warid, '&')
        let index = random(warIdArray.length - 1);
        let warId = warIdArray[index];

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