import { Application, BackendSession, HandlerService, } from 'pinus';
import { UserGuildModel } from '../../../db/UserGuild';
import { resResult } from '../../../pubUtils/util';
import { DATA_NAME, ITEM_CHANGE_REASON, STATUS, TASK_TYPE } from '../../../consts';
import { DonationModel } from '../../../db/Donation';
import { getZeroPoint, nowSeconds } from '../../../pubUtils/timeUtil';
import { getArmyDonateBaseByLv, getArmyDonateBoxBaseById } from '../../../pubUtils/data';
import { GuildModel } from '../../../db/Guild';
import { handleCost, addItems } from '../../../services/role/rewardService';
import { CHAT_SERVER, GUILD_POINT_WAYS } from '../../../consts';
import { addFund, donate, getDonation, getGuildFundByRefTime } from '../../../services/donateService';
import { getUserGuildWithRefActive } from '../../../services/guildService';
import { ARMY } from '../../../pubUtils/dicParam';
import { addActive } from '../../../services/guildService'
import { checkTask, checkTaskInDonate } from '../../../services/task/taskService';
import { guildInter } from '../../../pubUtils/interface';
import { lockData } from '../../../services/redLockService';
import { getVipDonateConsume } from '../../../services/activity/monthlyTicketService';

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

export class DonationHandler {
    constructor(private app: Application) {

    }
    /**
     * 捐献所的等级，捐献的次数，战报，捐献达到的基金，领取宝箱记录
     * @param msg 
     * @param session 
     */
    async getDonation(msg: guildInter & {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const serverId: number = parseInt(session.get('serverId'));

        let userGuild = await getUserGuildWithRefActive(roleId);
        if (!userGuild) return resResult(STATUS.WRONG_PARMS);

        let guild = await GuildModel.findGuild(userGuild.guildCode, serverId, 'structure lv');
        if(!guild) {
            return resResult(STATUS.WRONG_PARMS);
        }
        const { guildCode: code, donateCnt, receiveBoxs } = userGuild;
        let { donateFund, reports, donationLv } = await getDonation(code, guild);
        return resResult(STATUS.SUCCESS, { receiveBoxs, donateFund, reports, donateCnt: donateCnt || 0, donationLv });
    }
    /**
     * 捐献
     * @param msg 
     * @param session 
     */
    async donate(msg: guildInter & { id: number }, session: BackendSession) {
        const { id } = msg;
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const serverId: number = parseInt(session.get('serverId'));
        const sid: string = session.get('sid');
        const guildCode: string = session.get('guildCode');
        let res: any = await lockData(serverId, DATA_NAME.DONATE, guildCode);// 锁定资金的增加
        try {
            if (!!res.err) {
                return resResult(STATUS.REDLOCK_ERR);
            }

            let userGuild = await getUserGuildWithRefActive(roleId);
            if (!userGuild) {
                res.releaseCallback();
                return resResult(STATUS.WRONG_PARMS);
            }
            const { guildCode: code, donateCnt: resdonateCnt } = userGuild;

            let guild = await GuildModel.findGuild(code, serverId, 'structure lv');
            if(!guild) {
                res.releaseCallback();
                return resResult(STATUS.WRONG_PARMS);
            }

            if (resdonateCnt >= ARMY.ARMY_DONATE_TIMES) {
                res.releaseCallback();
                return resResult(STATUS.GUILD_DONATE_TIMES_NOT_ENOUGH);
            }
            let { donationLv } = await getGuildFundByRefTime(code, getZeroPoint());
            let { donateReward } = getArmyDonateBaseByLv(donationLv);
            let { rewardGood, rewardFund, cosume } = donateReward.get(id);
            let consumeResult = getVipDonateConsume(cosume, session.get('vipStartTime'));
            let result = await handleCost(roleId, sid, consumeResult, ITEM_CHANGE_REASON.DONATE);
            if (!result) {
                res.releaseCallback();
                return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);
            }
            let { donateCnt } = await UserGuildModel.donateFund(roleId, 1);

            let { donateFund, reports } = await donate(code, rewardFund, id, roleName, donationLv);
            let goods = [];
            if (!!rewardGood)
                goods = await addItems(roleId, roleName, sid, [rewardGood], ITEM_CHANGE_REASON.DONATE);
            //增加基金
            await addFund(code, serverId, rewardFund);

            await checkTaskInDonate(serverId, roleId, sid, cosume);
            await addActive(roleId, serverId, GUILD_POINT_WAYS.DONATE, id);
            res.releaseCallback();
            return resResult(STATUS.SUCCESS, { donateFund, reports, donateCnt, simpleGoods: goods });
        } catch (e) {
            res.releaseCallback();
            throw e;
        }
    }
    /**
     * 领取宝箱
     * @param msg 
     * @param session 
     */
    async receiveBox(msg: guildInter & { id: number }, session: BackendSession) {
        const { id, myUserGuild } = msg;
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const sid: string = session.get('sid');
        const serverId: number = parseInt(session.get('serverId'));
        let userGuild = await getUserGuildWithRefActive(roleId);
        if (!userGuild)
            return resResult(STATUS.WRONG_PARMS);
        const { guildCode: code, receiveBoxs: resReceiveBoxs } = userGuild;

        let guild = await GuildModel.findGuild(code, serverId, 'structure lv');
        if(!guild) {
            return resResult(STATUS.WRONG_PARMS);
        }

        if (resReceiveBoxs.indexOf(id) != -1)
            return resResult(STATUS.GUILD_DONATE_BOXS_IS_GOT);
        let { boxRewards, fund, level } = getArmyDonateBoxBaseById(id);
        let { donateFund, donationLv } = await getDonation(code, guild);
        if( donationLv < level) return resResult(STATUS.GUILD_DONATE_LV_NOT_ENOUGH)
        if (donateFund < fund)
            return resResult(STATUS.GUILD_DONATE_BOXS_NOT_GOT);
        resReceiveBoxs.push(id);
        let { receiveBoxs } = await UserGuildModel.updateInfo(roleId, { receiveBoxs: resReceiveBoxs }, {}, 'receiveBoxs');
        let goods = await addItems(roleId, roleName, sid, boxRewards, ITEM_CHANGE_REASON.DONATE_BOX);
        return resResult(STATUS.SUCCESS, { receiveBoxs, goods });
    }
}