import { Application, BackendSession, HandlerService, } from 'pinus';
import { resResult, } from '../../../pubUtils/util';
import { STATUS, ITEM_CHANGE_REASON, POP_UP_SHOP_CONDITION_TYPE, ACTIVITY_TYPE, DEBUG_MAGIC_WORD, PUSH_ROUTE, } from '../../../consts';
import { checkPopUpCondition, getPopUpShopData, getPopUpShopDataShow } from '../../../services/activity/popUpShopService';
import { ActivityPopUpShopModel } from '../../../db/ActivityPopUpShop';
import { addReward, stringToConsumeParam, stringToRewardParam } from '../../../services/activity/giftPackageService';
import { RewardParam } from '../../../domain/activityField/rewardField';
import { handleCost } from '../../../services/role/rewardService';
import { setInterval } from 'timers';
import { sendMessageToUserWithSuc } from '../../../services/pushService';

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

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

    /************************弹出式商店****************************/

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

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

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

    async checkPopUpCondition(msg: { conditionType: number }, session: BackendSession) {
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        let { conditionType } = msg;
        if(
            conditionType != POP_UP_SHOP_CONDITION_TYPE.GACHA_RES_NOT_ENOUGH && 
            conditionType != POP_UP_SHOP_CONDITION_TYPE.TERAPH_RES_NOT_ENOUGH
        ) {
            return resResult(STATUS.WRONG_PARMS);
        }

        await checkPopUpCondition(serverId, roleId, conditionType, {});

        return resResult(STATUS.SUCCESS);
    }


    /**
        * @description 购买礼包
        * @param {{ activityId: number,  id: number, beginTimeStamp: number}} msg
        * @param {BackendSession} session
        * @memberof PopUpShopHandler
        */
    async buyGift(msg: { activityId: number, id: number, code: string }, session: BackendSession) {
        const { activityId, code, id } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        
        let playerData = await getPopUpShopData(activityId, serverId, roleId);
        if (!playerData) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }
        if (playerData.type !== ACTIVITY_TYPE.POP_UP_SHOP) {
            return resResult(STATUS.ACTIVITY_TYPE_ERROR);
        }

        let record = await ActivityPopUpShopModel.findByCode(serverId, activityId, roleId, code);
        if(!record) return resResult(STATUS.ACTIVITY_TASK_NOT_COMPLETE);
        let pkg = playerData.findPackageById(record.id);
        let item = pkg?.findItemById(id);
        if(!item) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }
        if(item.productID) {
            return resResult(STATUS.ACTIVITY_POP_UP_MUST_BUY);
        }

        let consume = stringToConsumeParam(item.consume);
        let consumeResult = await handleCost(roleId, sid, consume, ITEM_CHANGE_REASON.POP_UP_BUY_GIFT);
        if(!consumeResult) return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);
        
        record = await ActivityPopUpShopModel.addRecordById(serverId, activityId, roleId, code, id);
        let showItem = playerData.updateRecordById(record, id);

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

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

    // 客户端展示弹出礼包的通知
    async showGift(msg: { code: string }, session: BackendSession) {
        const { code } = msg;

        let rec = await ActivityPopUpShopModel.show(code);
        if (!rec) return resResult(STATUS.ACTIVITY_MISSING);
        return resResult(STATUS.SUCCESS);
    }

    async debugPushPopUpShop(msg: { conditionType: number, magicWord: string, param: number, needDelete: boolean }, session: BackendSession) {
        const roleId = session.get('roleId');
        let serverId = session.get('serverId');
        const { magicWord, conditionType, param } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        // let activities = await getActivitiesByType(serverId, ACTIVITY_TYPE.POP_UP_SHOP);
        // for(let { activityId } of activities) {
        //     let playerData = await getPopUpShopData(activityId, serverId, roleId);
        //     for(let pkg of playerData.packages) {
        //         if(pkg.conditionType == conditionType) {
        //             await ActivityPopUpShopModel.deleteMany({ roleId, activityId, id: pkg.id });
        //         }
        //     }
        // }


        let arr = await checkPopUpCondition(serverId, roleId, conditionType, { 
            oldLv: param? param - 1: 0,
            newLv: param||100,
            quality: param||3,
            warId: param||128,
            seasonWinNum: param||10,
            equipStar: param||10
         });

        return resResult(STATUS.SUCCESS, { activities:arr });
    }

    private interval: NodeJS.Timer;
    private pushId = 0;

    async debugPushPopUpInterval(msg: { magicWord: string }, session: BackendSession) {
        const roleId = session.get('roleId');
        let sid = session.get('sid');
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        
        if(this.interval) {
            clearInterval(this.interval);
        }
        let fun = async () => {
            await sendMessageToUserWithSuc(roleId, PUSH_ROUTE.ACTIVITY_UPDATE, { 
                activities: [{
                    activityId: 25, 
                    activityType: 24, 
                    param: { popUpShopItems: [
                        {"code":"eefXmwD2","packageId":5,"endTime":Date.now() + 60000,"id":1,"name":"超值第一章通关礼包","price":6,"productID":"com.bantu.sgzzyz.yb34-20","consume":"&","reward":"2&11002&20|2&22001&2|2&31001&10000","rebate":1000,"buyCnt":1,"hasBoughtCnt":0},
                        {"code":"eefXmwD2","packageId":5,"endTime":Date.now() + 60000,"id":2,"name":"超值第一章通关礼包","price":30,"productID":"com.bantu.sgzzyz.yb34-21","consume":"&","reward":"2&11002&40|2&22001&10|2&31001&20000","rebate":850,"buyCnt":1,"hasBoughtCnt":0},
                        {"code":"eefXmwD2","packageId":5,"endTime":Date.now() + 60000,"id":3,"name":"超值第一章通关礼包","price":68,"productID":"com.bantu.sgzzyz.yb34-22","consume":"&","reward":"2&11003&20|2&22001&25|2&31001&40000","rebate":950,"buyCnt":1,"hasBoughtCnt":0}
                    ]},
                }],
                pushId: ++this.pushId 
            }, sid);
        };
        await fun();
        this.interval = setInterval(fun, 60000)

        return resResult(STATUS.SUCCESS);
    }

    async debugStopPupUpInterval(msg: { magicWord: string }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        
        if(this.interval) {
            clearInterval(this.interval);
        }
        this.pushId = 0;

        return resResult(STATUS.SUCCESS);
    }
}
