import { Application, BackendSession } from 'pinus';
import { UserGuildModel } from '../../../db/UserGuild';
import { GuildModel } from '../../../db/Guild';
import { WishPoolReportModel } from '../../../db/WishPoolReport';
import { resResult, genCode } from '../../../pubUtils/util';
import { ITEM_CHANGE_REASON, PUSH_ROUTE, STATUS } from '../../../consts';
import { gameData, getGoodById, getWishPoolReward } from '../../../pubUtils/data';
import { addItems, checkGoods, checkHeroEquips, checkHeroes, getHonourObject, handleCost } from '../../../services/role/rewardService';
import { ITID, CONSUME_TYPE } from '../../../consts/constModules/itemConst';
import { GUILD_POINT_WAYS, GUILD_STRUCTURE, WISH_POOL_TYPE } from '../../../consts/constModules/guildConst';
import { getWishPool, getUserGuildWithRefActive, addActive, canWishToday } from '../../../services/guildService';
import { findIndex, findWhere } from 'underscore';
import { RoleModel } from '../../../db/Role';
import { getRoleOnlineInfo } from '../../../services/redisService';
import { ARMY } from '../../../pubUtils/dicParam';
import { guildInter } from '../../../pubUtils/interface';
import { getSeconds, getZeroPoint, nowSeconds, isToday } from '../../../pubUtils/timeUtil';
import { sendMessageToUserWithSuc } from '../../../services/pushService';
import { isGoodsHidden } from '../../../services/dataService';
export default function(app: Application) {
    return new WishPoolHandler(app);
}

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

    async getWishPool(msg: guildInter & {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        let userGuild = await getUserGuildWithRefActive(roleId);
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS);
        let res = await getWishPool(userGuild);
        return resResult(STATUS.SUCCESS, res);
    }
    
    //  许愿
    async wishGoods(msg: guildInter & {goodId: number, type: number}, session: BackendSession) {
        const { goodId, type, myUserGuild } = msg;
        const roleId: string = session.get('roleId');
        const serverId: number = parseInt(session.get('serverId'));

        if(isGoodsHidden(goodId)) return resResult(STATUS.ITEM_IS_HIDDEN);
        let dicGoods = getGoodById(goodId)
        if (!dicGoods) return resResult(STATUS.DIC_DATA_NOT_FOUND);
        let dicItid = ITID.get(dicGoods.itid);
        if (dicItid.type != CONSUME_TYPE.SOUL || type != WISH_POOL_TYPE.SOUL) 
            return resResult(STATUS.GUILD_WISH_POOL_CAN_NOT_WISH);

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

        // 退出A军团 和 新入B军团 在同一天, 且在A军团已经许过愿，那么此时不允许许愿
        if (!await canWishToday(roleId)) {
            return resResult(STATUS.HAS_REACH_WISH_COUNT_LIMIT);
        }

        const { guildCode: code, wishGoods, receivedWishPool } = userGuild;

        let { lv } = await GuildModel.findGuild(code, serverId, 'lv');
        let len = wishGoods.filter(cur => cur.type == type).length;
        
        if(receivedWishPool.indexOf(type) != -1) {
            return resResult(STATUS.HAS_REACH_WISH_COUNT_LIMIT);
        }
        if (len >= ARMY.ARMY_WISH_TIMES)  //今日已经许愿过
            return resResult(STATUS.HAS_REACH_WISH_COUNT_LIMIT);

        let dicStructure = gameData.centerBase.get(lv);
        let count = 0;
        if (type == WISH_POOL_TYPE.SOUL) {
            let wishGoodsHero = dicStructure.wishgoodsHero.find(cur => cur.quality == dicGoods.quality);
            if (!wishGoodsHero) return resResult(STATUS.NOT_WISH_THE_QUALITY_GOODS);
            count = wishGoodsHero.count;
        }

        const id = genCode(6);
        let { wishGoods: resWishGoods } = await UserGuildModel.pushAndUpdate(roleId, {}, { wishGoods: { type, goodId, count, receiveCnt: 0, drawCnt: 0, id, donateNames:[]} }, 'wishGoods');
        return resResult(STATUS.SUCCESS, { wishGoods: resWishGoods, receivedWishPool });
    }

    //  捐赠
    async donateGoods(msg: guildInter & {wishRoleId: string, id: string}, session: BackendSession) {
        let { wishRoleId, id, myUserGuild } = msg;
        const dntRoleId: string = session.get('roleId');
        const dntRoleName: string = session.get('roleName');
        const serverId: number = session.get('serverId');
        const sid: string = session.get('sid');
        if (wishRoleId == dntRoleId)
            return resResult(STATUS.WRONG_PARMS);
        let role = await RoleModel.findByRoleId(wishRoleId);
        if (!role)
            return resResult(STATUS.WRONG_PARMS);//没有玩家
        let wishUserGuild = await getUserGuildWithRefActive(wishRoleId, ' wishDntCnt wishGoods guildCode');
        if (!wishUserGuild) 
            return resResult(STATUS.WRONG_PARMS);
        const { guildCode: code, wishGoods } = wishUserGuild;
        let dntRoleGuild = await getUserGuildWithRefActive(dntRoleId);
        if (!dntRoleGuild) 
            return resResult(STATUS.WRONG_PARMS);
        if (dntRoleGuild.guildCode != code) 
            return resResult(STATUS.WRONG_PARMS);
        if (dntRoleGuild.wishDntCnt >= ARMY.ARMY_WISH_HELP) 
            return resResult(STATUS.HAS_REACH_WISH_DONATE_COUNT_LIMIT);
        let wishGood = findWhere(wishGoods, { id });
        if (!wishGood) 
            return resResult(STATUS.WRONG_PARMS);//没有该许愿
        if (wishGood.receiveCnt >= wishGood.count)
            return resResult(STATUS.HAS_RECEIVE_WISH_GOOD);//已经收到

        if(isGoodsHidden(wishGood.goodId)) return resResult(STATUS.ITEM_IS_HIDDEN);

        let dicWishReward = getWishPoolReward(wishGood.goodId);
        if(!dicWishReward) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let costResult = await handleCost(dntRoleId, sid, [{ id: wishGood.goodId, count: 1 }], ITEM_CHANGE_REASON.WISH_POOL_DONATE);
        if(!costResult) return resResult(STATUS.GUILD_DONATE_CAN_NOT_SEND);

        let { wishDntCnt } = await UserGuildModel.donateGoods(dntRoleId, 1, 'wishDntCnt');
        let { wishGoods: resWishGoods } = await UserGuildModel.donateUpdate(wishRoleId, dntRoleName, id, 'wishGoods');

        let hisOnlineInfo = await getRoleOnlineInfo(wishRoleId);
        if(hisOnlineInfo.isOnline && hisOnlineInfo.sid) {
            sendMessageToUserWithSuc(wishRoleId, PUSH_ROUTE.WISH_GOODS_RECEIVE, { wishGoods: resWishGoods }, hisOnlineInfo.sid);
        }
        await WishPoolReportModel.addReport(code, wishRoleId, role.roleName , dntRoleId, dntRoleName, wishGood.goodId, 1);
        let goods = await addItems(dntRoleId, dntRoleName, sid, [getHonourObject(dicWishReward.honourReward)], ITEM_CHANGE_REASON.WISH_POOL_DONATE);
        await addActive(dntRoleId, serverId, GUILD_POINT_WAYS.WISH_POOL);

        return resResult(STATUS.SUCCESS, { wishDntCnt, goods, updateWishGoods: resWishGoods.map(({type, goodId, count, receiveCnt, drawCnt, id})=>{
                return { type, goodId, count, receiveCnt, drawCnt, id, roleId: wishRoleId };
            })
        });
    }

    async receiveGoods(msg: guildInter & { id: string }, session: BackendSession) {
        let { id, myUserGuild } = msg;
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const sid: string = session.get('sid');
        let userGuild = await getUserGuildWithRefActive(roleId);
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS);
        const { wishGoods, receivedWishPool } = userGuild;
            let index = findIndex(wishGoods, { id }); 
        if (index == -1) 
            return resResult(STATUS.WRONG_PARMS);
        let { drawCnt, goodId } = wishGoods[index];
        if (drawCnt <= 0)
            return resResult(STATUS.WRONG_PARMS);
        wishGoods[index].drawCnt = 0;
        if(receivedWishPool.indexOf(wishGoods[index].type) == -1) receivedWishPool.push(wishGoods[index].type);

        let result = await UserGuildModel.updateInfo(roleId, { wishGoods, receivedWishPool }, {});
        if (!result) 
            resResult(STATUS.INTERNAL_ERR);
        let goods = await addItems(roleId, roleName, sid,  [{ id : goodId, count: drawCnt }], ITEM_CHANGE_REASON.WISH_POOL_RECEIVE);
        return resResult(STATUS.SUCCESS, { goods, wishGoods, receivedWishPool });
    }

    async getReports(msg: guildInter & {}, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const { myUserGuild } = msg;
        let userGuild = await getUserGuildWithRefActive(roleId);
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS);
        const { guildCode: code } = userGuild;
        const reports = await WishPoolReportModel.getReportsByTime(code, 1);//获得今天的捐赠日报
        return resResult(STATUS.SUCCESS, { reports });
    }
} 