import { Application, BackendSession, HandlerService, pinus, } from "pinus";
import { resResult } from "../../../pubUtils/util";
import { STATUS, getRedisKeyByRankType, ROLE_SELECT, RANK_TYPE, HERO_SELECT, GUILD_SELECT, RANK_FIRST_REWARD_STATUS, ITEM_CHANGE_REASON } from "../../../consts";
import { RoleModel } from "../../../db/Role";
import { UserGuildModel } from "../../../db/UserGuild";
import { GuildModel } from "../../../db/Guild";
import { Rank, getGeneralRank, getRankFirstReward, getRankInHandler } from "../../../services/rankService";
import { nowSeconds } from "../../../pubUtils/timeUtil";
import { gameData } from "../../../pubUtils/data";
import { addItems } from "../../../services/role/rewardService";
import { HeroModel, HeroUpdate } from "../../../db/Hero";
import { RewardInter } from "../../../pubUtils/interface";
import { GuildRankInfo, RoleAndGuildRankInfo, RoleRankInfo } from "../../../domain/rank";
import { RankFirstType } from "../../../db/RankFirst";

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

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

    async getGeneralRank(msg: {}, session: BackendSession) {
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let serverId = session.get('serverId');

        let role = await RoleModel.findByRoleId(roleId, 'rankReceived');
        if (!role) return resResult(STATUS.WRONG_PARMS);

        let ranks = await getGeneralRank(role, serverId);

        return resResult(STATUS.SUCCESS, { ranks });
    }


    async getRankReward(msg: {}, session: BackendSession) {
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let serverId = session.get('serverId');

        let role = await RoleModel.findByRoleId(roleId, 'rankReceived');
        if (!role) return resResult(STATUS.WRONG_PARMS);

        let ranks = await getRankFirstReward(role, serverId);

        return resResult(STATUS.SUCCESS, { ranks });
    }

    async getRank(msg: { type: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let serverId = session.get('serverId');
        let guildCode = session.get('guildCode');

        let { type } = msg;
        let redisKey = getRedisKeyByRankType(type);
        if (!redisKey) return resResult(STATUS.WRONG_PARMS);
        let result = await getRankInHandler(redisKey, type, { serverId }, session);
        return resResult(STATUS.SUCCESS, { type, ...result });
    }

    // 查看活跃排行榜
    async getGuildRank(msg: { type: number }, session: BackendSession) {

        let roleId = session.get('roleId');
        let serverId = session.get('serverId')

        let { type } = msg;

        let redisKey = getRedisKeyByRankType(type);
        if (!redisKey) return resResult(STATUS.WRONG_PARMS);

        let r = new Rank(redisKey, { serverId });
        const myUserGuild = await UserGuildModel.getMyGuild(roleId, 'auth guildCode');
        let { ranks, myRank } = await r.getRankListWithMyRank({ guildCode: myUserGuild?.guildCode || '' });
        if (!myRank) {
            let guild = await GuildModel.findByCode(myUserGuild.guildCode, serverId, GUILD_SELECT.RANK);
            if (type == RANK_TYPE.GUILD_LV) {
                myRank = await r.generMyRankWithGuild(guild.code, guild.lv, guild.lvUpdateTime, guild);
            } else if (type == RANK_TYPE.GUILD_ACTIVE) {
                myRank = await r.generMyRankWithGuild(guild.code, guild.activeWeekly, guild.activeUpdateTime, guild);
            }
        }

        return resResult(STATUS.SUCCESS, { type, ranks, myRank });
    }

    // 查看单个武将排行榜
    async getHeroRank(msg: { type: number, hid: number }, session: BackendSession) {

        let serverId = session.get('serverId')

        let { type, hid } = msg;
        let redisKey = getRedisKeyByRankType(type);
        if (!redisKey) return resResult(STATUS.WRONG_PARMS);

        let r = new Rank(redisKey, { serverId, hid });
        let ranks = await r.getRankByRange();

        return resResult(STATUS.SUCCESS, {
            type, hid, ranks
        });
    }

    async receiveReward(msg: { type: number, id: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let serverId = session.get('serverId');
        let roleName = session.get('roleName');
        let sid = session.get('sid');

        let { type, id } = msg;

        let ids: number[] = [];
        if (id == 0) {
            gameData.generalRankReward.forEach((dic, id) => {
                if (dic.rankId == type) {
                    ids.push(id);
                }
            });
        } else {
            ids.push(id);
        }
        let rewards: RewardInter[] = [];
        let canReceiveId: number[] = [];
        let role = await RoleModel.findByRoleId(roleId, 'rankReceived');

        for (let id of ids) {
            let dicReward = gameData.generalRankReward.get(id);
            if (!dicReward || dicReward.rankId != type) continue;

            let rankFirst: RankFirstType = pinus.app.get('rankFirstRewards').get(serverId)?.get(id);
            // console.log('*******', pinus.app.get('rankFirstRewards'), rankFirst);
            if (!rankFirst) continue;
            if (role.rankReceived.includes(id)) continue;

            let reward = dicReward.reward;
            rewards = rewards.concat(reward);
            canReceiveId.push(id);
        }

        role = await RoleModel.receiveRankReward(roleId, canReceiveId);
        if (canReceiveId.length <= 0) return resResult(STATUS.REWARD_CONDITION_NOT_REACH);

        let rewardStatus = canReceiveId.map(id => {
            return { id, type, status: RANK_FIRST_REWARD_STATUS.RECEIVED }
        })

        let goods = await addItems(roleId, roleName, sid, rewards, ITEM_CHANGE_REASON.RANK_REWARD);

        return resResult(STATUS.SUCCESS, {
            rewards: rewardStatus,
            goods
        })
    }
}