import { Application, BackendSession } from 'pinus';
import { DailyRecordModel } from '../../../db/DailyRecord';
import { STATUS } from '../../../consts/statusCode';
import { resResult } from '../../../pubUtils/util';
import { RoleModel } from '../../../db/Role';
import { getDailyNum, getDailyBattleList, getDailyBuyCountCost } from '../../../services/dailyBattleService';
import { handleCost } from '../../../services/rewardService';
import { getGoldObject } from '../../../pubUtils/itemUtils';
import { gameData } from '../../../pubUtils/data';

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

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

    // 获取关卡列表
    async getData(msg: { }, session: BackendSession) {
        let roleId = session.get('roleId');

        let role = await RoleModel.findByRoleId(roleId); 
        let result = await getDailyBattleList(role);

        return resResult(STATUS.SUCCESS, { list: result });
    }

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

        const curDaily = gameData.daily.find(cur => cur.dailyType == type);
        if(!curDaily) return resResult(STATUS.DAILY_TYPE_NOT_FOUND);
        let { timesPerDay, timesCanBuy } = curDaily;
        let { buyCount = 0 } = await DailyRecordModel.refreshRecord(roleId, type);
        let { vLv } = await RoleModel.findByRoleId(roleId);
        if(vLv > 0) {
            timesCanBuy += 0; // 暂留，用于处理vip等级增加最大购买次数
        }
        if(buyCount + count > timesCanBuy ) {
            return resResult(STATUS.DAILY_REFRESH_TIMES_LACK)
        }
        let buyCost = 0;
        for(let i = 1; i <= count; i++) {
            let num = buyCount + i;
            buyCost += getDailyBuyCountCost(num);
        }
        let {gold} = await RoleModel.findByRoleId(roleId);
        if(buyCost > gold) {
            return resResult(STATUS.DAILY_REFRESH_GOLD_LACK);
        }

        await handleCost(roleId, sid, [getGoldObject(buyCost)]);
        let newDailyRecord = await DailyRecordModel.increseBuyCount(roleId, type, count);

        let checkDailyResult = await getDailyNum(newDailyRecord, timesPerDay, timesCanBuy);
        return resResult(STATUS.SUCCESS, { type, ...checkDailyResult, buyCost});
    }
}