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, STATUS } from '../../../consts';
import { getArmyWishPoolBaseByLv, getGoodById, getWishPoolReward } from '../../../pubUtils/data';
import { addItems, checkGoods, checkHeroes } from '../../../services/rewardService';
import { IT_TYPE } from '../../../consts/constModules/itemConst';
import { GUILD_STRUCTURE } from '../../../consts/constModules/guildConst';
import { refreshUserGuild, getWishPool, getUserGuildWithRefActive } 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 } from '../../../pubUtils/timeUtil';
import { getHonourObject } from '../../../pubUtils/itemUtils';
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');
        const { myUserGuild } = msg;
        let userGuild = await refreshUserGuild(myUserGuild, 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'));
        let count;
        let goodInfo = getGoodById(goodId)
        if (!goodInfo) 
            return resResult(STATUS.WRONG_PARMS);
        if (!(goodInfo.itid == IT_TYPE.HERO_PIECE && type == 2 ) && !(goodInfo.itid == IT_TYPE.EQUIP_PIECE && type == 1 )) 
            return resResult(STATUS.WRONG_PARMS);
        let userGuild = await refreshUserGuild(myUserGuild, roleId);
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS);
        let result = await checkGoods(roleId, [goodId]);
        if (!result) {
            if (goodInfo.itid == IT_TYPE.HERO_PIECE ) {
                result = await checkHeroes(roleId, [goodInfo.hid]);
                if (!result)
                    return resResult(STATUS.GUILD_WISH_POOL_NOT_OWN_HERO);
            } else if (goodInfo.itid == IT_TYPE.EQUIP_PIECE ) {
                result = await checkGoods(roleId, [goodInfo.equipId]);
                if (!result)
                    return resResult(STATUS.GUILD_WISH_POOL_NOT_OWN_EQUIP);
            }
        }
        const { guildCode: code, wishGoods, receivedWishPool, createdAt } = userGuild;

        let { structure } = await GuildModel.findGuild(code, serverId, 'structure');
        let { lv } = findWhere(structure, {id: GUILD_STRUCTURE.WISH_POOL});
        let { wishGoodsEquips, wishGoodsHeros } = getArmyWishPoolBaseByLv(lv);
        let len = 0;
        wishGoods.map(({type: resType})=>{
            if (resType == type)
                len++;
        });
        
        if(receivedWishPool.indexOf(type) != -1 && getSeconds(createdAt) > getZeroPoint()) {
            return resResult(STATUS.HAS_REACH_WISH_COUNT_LIMIT);
        }
        if (len >= ARMY.ARMY_WISH_TIMES)  //今日已经许愿过
            return resResult(STATUS.HAS_REACH_WISH_COUNT_LIMIT);
        if (type == 1) {
            let wishGoodsEquip = findWhere(wishGoodsEquips, { quality: goodInfo.quality});
            if (!wishGoodsEquip)
                return resResult(STATUS.NOT_WISH_THE_QUALITY_GOODS);
            count = wishGoodsEquip.count;
        } else {
            let wishGoodsHero = findWhere(wishGoodsHeros, { quality: goodInfo.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 });
    }

    //  捐赠
    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 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 refreshUserGuild(myUserGuild, 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);//已经收到

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

        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) {
            // await addItems(wishRoleId, role.roleName, hisOnlineInfo.sid ,  [{ id : wishGood.goodId, count: 1 }], ITEM_CHANGE_REASON.WISH_POOL_DONATE);
            this.app.channelService.pushMessageByUids('onWishGoodsRecive', resResult(STATUS.SUCCESS, { wishGoods: resWishGoods }), [{uid:wishRoleId, sid: 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);
        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 refreshUserGuild(myUserGuild, 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 });
    }

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