import { Application, BackendSession } from 'pinus';
import { GOLD_COST_RATIO, DUNGEON_CONST } from '../../../consts';
import { STATUS } from '../../../consts/statusCode';
import { resResult, calculateNum, shouldRefresh } from '../../../pubUtils/util';
import { RoleModel } from '../../../db/Role';
import { handleCost } from '../../../services/rewardService';
import { getGoldObject } from '../../../pubUtils/itemUtils';
import { getDungeonData } from '../../../services/dungeonService';

export default function(app: Application) {
    return new DungeonBattleHandler(app);
}

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

    // 获取关卡列表
    async getData(msg: { }, session: BackendSession) {
        let roleId = session.get('roleId');
        let role = await RoleModel.findByRoleId(roleId);
        let res = await getDungeonData(role);
        return resResult(STATUS.SUCCESS, res);
    }

    // 购买每日次数
    async buyNum(msg: { count: number }, session: BackendSession) {
        let { count } = msg;
        if( !count || count < 0) return resResult(STATUS.WRONG_PARMS);
        const roleId = session.get('roleId');
        const sid = session.get('sid');

        let { dungeonCnt = 0, dungeonBuyCnt = 0, dungeonRefTime } = await RoleModel.findByRoleId(roleId);
        let curTime = new Date();
        let needRefresh = shouldRefresh(dungeonRefTime, curTime);
        if(needRefresh) {
            dungeonCnt = 0; dungeonBuyCnt = 0;
        }

        let timesCanBuy = DUNGEON_CONST.MAX_BUY_CNT;
        let { vLv } = await RoleModel.findByRoleId(roleId);
        if(vLv > 0) {
            timesCanBuy += 0; // 暂留，用于处理vip等级增加最大购买次数
        }
        if(dungeonBuyCnt + count > timesCanBuy ) {
            return resResult(STATUS.DUNGEON_REFRESH_TIMES_LACK)
        }
        let buyCost = 0;
        for(let i = 1; i <= count; i++) {
            let num = dungeonBuyCnt + i;
            buyCost += calculateNum(GOLD_COST_RATIO.DUNGRON_BUY_NUM, {num}, 50);
        }
        let {gold} = await RoleModel.findByRoleId(roleId);
        if(buyCost > gold) {
            return resResult(STATUS.DAILY_REFRESH_GOLD_LACK);
        }
        await handleCost(roleId, sid, [getGoldObject(buyCost)]);
        await RoleModel.buyCnt(roleId, needRefresh, count, curTime);

        let nextCostGold = calculateNum(GOLD_COST_RATIO.DUNGRON_BUY_NUM, {num: dungeonBuyCnt + count + 1 }, 50);
        return resResult(STATUS.SUCCESS, { 
            costGold: buyCost,
            nextCostGold,
            battleCount: DUNGEON_CONST.MAX_CNT + dungeonBuyCnt + count - dungeonCnt, 
            buyCount: DUNGEON_CONST.MAX_BUY_CNT - dungeonBuyCnt - count
        });
    }
}