import { Application, BackendSession, pinus } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { STATUS } from '../../../consts/statusCode';
import { getRoleOnlineInfo, updateUserInfo } from '../../../services/redisService';
import { addItems, createHeroes } from '../../../services/rewardService';
import { RewardInter } from '../../../pubUtils/interface';
import { getExpByLv, getLvByExp } from '../../../pubUtils/data';
import { RoleModel, RoleType } from '../../../db/Role';
import { BLOCK_TYPE, GUILD_AUTH, GUILD_DISMISS_WAY, GUILD_JOB, GUILD_MASTER_CHANGE_WAY, GUILD_STATUS, GUILD_STRUCTURE, ITEM_CHANGE_REASON, MAIL_TYPE, REDIS_KEY, TA_EVENT } from '../../../consts';
import { GuildFormParam } from '../../../domain/backEndField/params';
import { GuildModel, GuildUpdateParam } from '../../../db/Guild';
import { getGuildChannelSid } from '../../../services/chatService';
import { pushGuildNoticeUpdateMsg } from '../../../services/sysChatService'
import { Rank } from '../../../services/rankService';
import { UserGuildModel } from '../../../db/UserGuild';
import { UserGuildApplyModel } from '../../../db/UserGuildApply';
import { reportTAEvent } from '../../../services/sdkService';
import { sendMailByContent } from '../../../services/mailService';
import { GuildLeader } from '../../../domain/rank';

let timer: NodeJS.Timer;
export default function (app: Application) {
    return new GmRoleHandler(app);
}

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

    async addItems(msg: { roleId: string, roleName: string, serverId: number, values: { reward: RewardInter[], heroes: number[], lv: number, expInc: number }}, session: BackendSession) {
        let { roleId, roleName, serverId, values } = msg;

        let { reward, heroes, lv, expInc = 0 } = values;
        if (reward == undefined && heroes == undefined && lv == undefined) {
            return resResult(STATUS.WRONG_PARMS);
        }
        let connect = await getRoleOnlineInfo(roleId);
        let sid = connect.isOnline?connect.sid: null;

        if(reward &&reward.length > 0) {
            await addItems(roleId, roleName, sid, values.reward, ITEM_CHANGE_REASON.DEBUG);
        }
        if(heroes && heroes.length > 0) {
            await createHeroes(roleId, roleName, sid, serverId, heroes.map(hid => { return { hid, count: 1 }}))
        }
        if(lv && lv > 0) {
            let exp = getExpByLv(lv - 1)?.sum||0;
            exp += expInc;
            let newLv = getLvByExp(exp);
            let role = await RoleModel.updateRoleInfo(roleId, { lv: newLv, exp })
            let r = new Rank(REDIS_KEY.USER_LV, { serverId: serverId });
            await r.setRankWithRoleInfo(roleId, newLv, Date.now(), role);
            let uids = [{ uid: roleId, sid }];
            pinus.app.get('channelService').pushMessageByUids('onPlayerExpChange', resResult(STATUS.SUCCESS, { 
                isLvUp: false, lv: newLv, exp
            }), uids);
        }
        return resResult(STATUS.SUCCESS);
    }

    async handleBlock(msg: { roleId: string, blockType: BLOCK_TYPE, blockReason: string }, session: BackendSession) {
        let { roleId, blockType, blockReason } = msg;
        if(roleId == undefined || blockType == undefined || blockReason == undefined) return resResult(STATUS.WRONG_PARMS);
        let role = await RoleModel.updateRoleInfo(roleId, { blockType, blockReason });
        if(!role) return resResult(STATUS.ROLE_NOT_FOUND);
        let { isOnline, sid } = await getRoleOnlineInfo(roleId);
        if(isOnline) {
            await this.app.rpc.connector.connectorRemote.setOtherUseBlockTypeSession.toServer(sid,[{ roleId, blockType }]);
            if(blockType == BLOCK_TYPE.BLOCK) { // 踢走
                await this.app.rpc.connector.connectorRemote.remoteLogin.toServer(sid, roleId, STATUS.BLOCKED);
            }
        }
        return resResult(STATUS.SUCCESS);
    }

    async updateGuild(msg: GuildFormParam, session: BackendSession ) {
        const uid = session.get('uid');
        let params = new GuildFormParam(msg);
        if(!params.checkParams()) return resResult(STATUS.WRONG_PARMS);

        let guild = await GuildModel.findByCode(params.code, null, '+members');
        let structure = guild.structure||[];

        let updateParams: GuildUpdateParam = { code: params.code };
        if(params.name && guild.name != params.name) updateParams.name = params.name;
        if(params.fund != undefined && guild.fund != params.fund) updateParams.fund = params.fund;
        if(params.notice && guild.notice != params.notice) updateParams.notice = params.notice;
        if(params.lv && guild.lv != params.lv) updateParams.lv = params.lv;
        for(let id = GUILD_STRUCTURE.START; id < GUILD_STRUCTURE.END; id ++) {
            let curStructure = structure.find(cur => cur.id == id);
            let lv = params.lv;
            switch(id) {
                case GUILD_STRUCTURE.ARMY_CENTER: 
                    lv = params.lv; break;
                case GUILD_STRUCTURE.EQUIP_PRODUCE:
                    lv = params.equipProduce; break;
                case GUILD_STRUCTURE.BOSS:
                    lv = params.boss; break;
                case GUILD_STRUCTURE.TRAIN:
                    lv = params.train; break;
                case GUILD_STRUCTURE.DONATE:
                    lv = params.donate; break;
                case GUILD_STRUCTURE.WISH_POOL:
                    lv = params.wishPool; break;
                case GUILD_STRUCTURE.STORE:
                    lv = params.store; break;
            }
            if(curStructure) {
                curStructure.lv = lv;
            } else {
                structure.push({ id, lv });
            }
        }
        updateParams.structure = structure;
        let chatSid = await getGuildChannelSid(params.code);
        console.log('*****', params.code, updateParams)
        this.app.rpc.chat.guildRemote.updateInfo.toServer(chatSid, params.code, updateParams);
        // 设置玩家名
        if(updateParams.name != undefined || updateParams.lv != undefined) {
            let arr = [];
            if(updateParams.name != undefined) {
                arr.push({ field: 'name', value: updateParams.name });
                for(let roleId of guild.members) {
                    await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'guildName', value: updateParams.name }]);
                }
            }
            if(updateParams.lv != undefined) arr.push({ field: 'lv', value: updateParams.lv });
            await updateUserInfo(REDIS_KEY.GUILD_INFO, params.code, arr);
        }
        if (updateParams.lv != undefined) {
            let r = new Rank(REDIS_KEY.GUILD_LV_RANK, { serverId: guild.serverId });
            await r.setRankWithGuildInfo2(guild.code, updateParams.lv, guild.activeWeekly, guild.lvUpdateTime, guild);
        }

        guild = await GuildModel.updateInfo(params.code, updateParams);
        return resResult(STATUS.SUCCESS);
    }
    async dismissGuild(msg: { code: string }, session: BackendSession) {

        const { code } = msg;

        let guild = await GuildModel.findByCode(code, null, '+serverId');
        if(!guild) return resResult(STATUS.GUILD_NOT_FOUND);
        if(guild.status == GUILD_STATUS.DISMISSED) return resResult(STATUS.GUILD_DELETE_ERROR);

        let serverId = guild.serverId;
        guild = await GuildModel.dismiss(code, serverId);
        if (!guild) return resResult(STATUS.GUILD_DELETE_ERROR);

        await UserGuildModel.dismiss(code);
        const { members } = guild;
        await RoleModel.dissmissGuild(members);
        await UserGuildApplyModel.deleteApplyByGuild(code);

        await this.app.rpc.connector.connectorRemote.setOtherUserGuildSession.broadcast(members.map(roleId => { return { roleId, userGuild: null } })); // 更新session

        // 删除channel

        let chatSid = await getGuildChannelSid(code);
        this.app.rpc.chat.guildRemote.dismiss.toServer(chatSid, code);

        let r = new Rank(REDIS_KEY.GUILD_ACTIVE_RANK, { serverId });
        await r.removeFromRank({ guildCode: code });
        let r2 = new Rank(REDIS_KEY.GUILD_LV_RANK, { serverId });
        await r2.removeFromRank({ guildCode: code });
        let leader = <RoleType>guild.leader;
        reportTAEvent(leader.roleId, TA_EVENT.GUILD_DISMISS, { name: guild.name, way: GUILD_DISMISS_WAY.BACKEND });

        return resResult(STATUS.SUCCESS, { code, status: guild.status });
    }

    async setGuildLeader(msg: { code: string, roleId: string }, session: BackendSession) {

        const { code, roleId } = msg;
        let guild = await GuildModel.findByCode(code, null, '+serverId');
        if(!guild) return resResult(STATUS.GUILD_NOT_FOUND);
        if(guild.status == GUILD_STATUS.DISMISSED) return resResult(STATUS.GUILD_DELETE_ERROR);

        let role = await RoleModel.findByRoleId(roleId);
        if(!role) return resResult(STATUS.ROLE_NOT_FOUND);

        let userGuild = await UserGuildModel.getMyGuild(roleId);
        if(!userGuild || userGuild.guildCode != code) return resResult(STATUS.GUILD_KICK_ERROR);
        if(userGuild.auth == GUILD_AUTH.LEADER) return resResult(STATUS.GUILD_USER_IS_LEADER);

        let leader = <RoleType>guild.leader;
        // 交换
        let oldLeaderUserGuild = await UserGuildModel.updateInfo(leader.roleId, { auth: GUILD_AUTH.MEMBER, job: GUILD_JOB.SHIBING }, {}, 'auth'); // 团长撤
        await this.app.rpc.connector.connectorRemote.setOtherUserGuildSession.broadcast([{ roleId: leader.roleId, userGuild: oldLeaderUserGuild }]); // 更新session

        let newLeaderUserGuild = await UserGuildModel.updateInfo(roleId, { auth: GUILD_AUTH.LEADER, job: GUILD_JOB.DAJIANGJUN }, {}, 'auth'); // 最高功勋人升
        await this.app.rpc.connector.connectorRemote.setOtherUserGuildSession.broadcast([{ roleId: roleId, userGuild: newLeaderUserGuild }]); // 更新session

        let managerCntInc = userGuild.auth == GUILD_AUTH.MANAGER ? -1 : 0; // 管理人数

        guild = await GuildModel.updateInfo(code, { leader: role._id }, { managerCnt: managerCntInc }, 'managerCnt name'); // 如果有转让团长设置leader

        // 添加动态
        let chatSid = await getGuildChannelSid(code);

        this.app.rpc.chat.guildRemote.changeLeader.toServer(chatSid, code, guild.managerCnt, role, leader.roleId);
        await sendMailByContent(MAIL_TYPE.GUILD_BE_IMPEACH, leader.roleId, { params: [guild.name] });
        await sendMailByContent(MAIL_TYPE.GUILD_BE_SET_LEADER, roleId, { params: [guild.name] });

        await updateUserInfo(REDIS_KEY.GUILD_INFO, code, [{ field: 'leader', value: new GuildLeader(role) }]);
        reportTAEvent(roleId, TA_EVENT.GUILD_MASTER_CHANGE, { way: GUILD_MASTER_CHANGE_WAY.BACKEND, change_id_after: roleId })

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