import { Application, BackendSession, ChannelService, HandlerService, } from 'pinus';
import { resResult, getRandEelm, shouldRefresh, sortArrRandom } from '../../../pubUtils/util';
import { STATUS, GUILD_OPERATE, GUILD_AUTH, GUILD_JOB, GUILD_APPLY_TYPE, GUILD_STRUCTURE, GUILD_REC_TYPE, GUILD_STRUCTURE_NAME, MAIL_TYPE, REDIS_KEY, GUILD_SELECT, USER_GUILD_SELECT, TASK_TYPE, DEBUG_MAGIC_WORD, CHANNEL_PREFIX, MSG_TYPE, MSG_SOURCE, ITEM_CHANGE_REASON, TA_EVENT, GUILD_DISMISS_WAY, GUILD_MASTER_CHANGE_WAY, GUILD_QUIT_WAY, PUSH_ROUTE } from '../../../consts';
import { UserGuildModel, UserGuildType } from '../../../db/UserGuild';
import { checkAuth, joinGuild, getUserGuildWithRefActive, addActive, settleGuildWeekly, getMyGuildInfo, setUserGuildSession, getInvitationList, addGuildRecord, pushChangeGuildLeader, pushGuildMemberQuit, pushGuildDismiss, pushGuildInfoUpdate, getTodayGuildActive } from '../../../services/guildService';
import { GuildModel, GuildType, GuildUpdateParam } from '../../../db/Guild';
import { RoleModel, RoleType } from '../../../db/Role';
import { ARMY } from '../../../pubUtils/dicParam';
import { handleCost, addItems, getGoldObject } from '../../../services/role/rewardService';
import { nowSeconds, getTimeFun, getSeconds, getZeroPointD, DAY_TO_MS, HOUR_TO_MS } from '../../../pubUtils/timeUtil';
import { GuildListInfo, GuildMemberParam } from '../../../domain/battleField/guild';
import { GuildLeader } from '../../../domain/rank';
import { UserGuildApplyModel } from '../../../db/UserGuildApply';
import { hasStructureConsume, getStructureConsume, gameData } from '../../../pubUtils/data';
import { GuildRecModel } from '../../../db/GuildRec';
import { sendMailByContent, SendMailFun, sendMailToGuildByContent } from '../../../services/mailService';
import { updateUserInfo, isRoleOnline, getRoleOnlineInfo } from '../../../services/redisService';

import { openGuildRefine } from '../../../services/guildRefineService';
import { unlockTrain } from '../../../services/guildTrainService';
import { removeBossRank } from '../../../services/guildBossService';
import { removeTrainRank } from '../../../services/guildTrainService';
import { pushGuildNoticeUpdateMsg, pushGuildUpStructureMsg, addRoleToGuildChannel, getGuildChannelSid, createGroupMsg, pushGroupMsgToRoom } from '../../../services/chatService';
import { Rank } from '../../../services/rankService';
import { checkTask } from '../../../services/task/taskService';
import { guildInter } from '../../../pubUtils/interface';
import * as dicParam from '../../../pubUtils/dicParam';
import { reportTAEvent } from '../../../services/sdkService';
import { changeGuildActivity, guildDismisActivity, guildPayQuitGuild } from '../../../services/activity/guildPayService';
import { sendMessageToUserWithSuc } from '../../../services/pushService';
import { GuildActiveModel } from '../../../db/GuildActive';
import { leaveRaceActivityToRemote, leaveRaceWhenDismissToRemote, leaveRaceWhenQuitGuildToRemote } from '../../../services/guildActivity/guildActivityService';
import { getGVGInfoInGuild } from '../../../services/gvg/gvgService';
import { guildAbdicateToLeague, guildDismissToLeague, memberQuitGuildToLeague } from '../../../services/gvg/gvgTeamService';
import { leaveCity } from '../../../services/gvg/gvgBattleService';


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

export class GuildHandler {
    channelService: ChannelService;
    constructor(private app: Application) {
        this.channelService = app.get('channelService');
    }

    // 创建军团
    async createGuild(msg: guildInter & { guildCode: string } & { name: string, icon: number, notice: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const sid = session.get('sid');
        const serverId = session.get('serverId');
        const { name, icon, notice, guildCode } = msg;

        // 检查名字是否重
        const checkNameResult = await GuildModel.checkName(name, serverId);
        if (checkNameResult) return resResult(STATUS.GUILD_NAME_DUP);

        // 检查元宝是否够
        const role = await RoleModel.findByRoleId(roleId);
        if (ARMY.ARMY_CREAT_COST > role.gold) {
            return resResult(STATUS.DAILY_REFRESH_GOLD_LACK);
        }

        // 检查是否充值过
        if(ARMY.ARMY_CREAT_CONDITION > role.totalPay) {
            return resResult(STATUS.GUILD_PAY_CONDITION);
        }

        await handleCost(roleId, sid, [getGoldObject(ARMY.ARMY_CREAT_COST)], ITEM_CHANGE_REASON.CREATE_GUILD);

        // 创建公会
        const guild = await GuildModel.createGuild({ guildCode, name, icon, notice }, role, serverId);
        if (!guild) return resResult(STATUS.GUILD_CREATE_ERROR);
        guild.leader = <RoleType>guild.leader;
        //创建科技树
        await openGuildRefine(guild.code);
        await unlockTrain(guild.code, 1);
        const userGuild = await UserGuildModel.createUserGuild(guild.code, role, true);
        if (!userGuild) return resResult(STATUS.GUILD_CREATE_ERROR);

        await RoleModel.joinGuild(roleId, guild.code, guild.name, true);
        await UserGuildApplyModel.deleteApply(roleId); // 删除玩家所有对其他公会的申请

        // 加入排行
        let r = new Rank(REDIS_KEY.GUILD_ACTIVE_RANK, { serverId });
        await r.setRankWithGuildInfo(guild.code, 0, Date.now(), guild);
        let r2 = new Rank(REDIS_KEY.GUILD_LV_RANK, { serverId });
        await r2.setRankWithGuildInfo2(guild.code, guild.lv, guild.activeWeekly, Date.now(), guild);
        await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'guildName', value: name }]);

        let rank = await r.getMyRank({ guildCode: guild.code });

        // 加入channel
        setUserGuildSession(session, userGuild);
        addRoleToGuildChannel(roleId, sid, guild.code);

        // 添加动态
        await addGuildRecord(roleId, guild.code, GUILD_REC_TYPE.JOIN_GUILD, [roleName]);

        // 返回
        const result = { ...guild, rank, myInfo: { ...userGuild, isOnline: true } };
        await checkTask(serverId, roleId, sid, TASK_TYPE.GUILD_JOIN);
        return resResult(STATUS.SUCCESS, result);
    }

    // 获取军团列表
    async getGuildList(msg: guildInter & { page: number, showPeopleMax: boolean, name: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        // const sid = session.get('sid');
        const serverId = session.get('serverId');
        const { page = 1, showPeopleMax, name } = msg;

        const guildList = await GuildModel.getGuildList(page, showPeopleMax, name, serverId);
        const applyList = await UserGuildApplyModel.findApplyByRole(roleId);

        const { quitGuildTime: quitTime = 0 } = await RoleModel.findByRoleId(roleId);

        const list = new Array<GuildListInfo>();
        for (let guild of guildList) {
            let info = new GuildListInfo(guild);

            let hasApply = applyList.find(cur => cur.guildCode == guild.code);
            info.setApply(!!hasApply);
            list.push(info);
        }
        return resResult(STATUS.SUCCESS, { quitTime, list });
    }

    // 团长修改军团名等信息
    async setGuildInfo(msg: guildInter & { code: string, name: string, notice: string, introduce: string, ceLimit: number, isAuto: boolean, icon: number }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const { code, name, notice, introduce, ceLimit, isAuto, icon } = msg;
        if (!code) return resResult(STATUS.WRONG_PARMS);

        // 检查名字是否重
        if(name != undefined) {
            const checkNameResult = await GuildModel.checkName(name, serverId);
            if (checkNameResult) return resResult(STATUS.GUILD_NAME_DUP);
        }

        const select = ['code', 'name', 'notice', 'introduce', 'ceLimit', 'isAuto', 'icon', '+members'];
        let updateInfo: GuildUpdateParam = {};
        if(name != undefined) updateInfo.name = name;
        if(notice != undefined) updateInfo.notice = notice;
        if(introduce != undefined) updateInfo.introduce = introduce;
        if(ceLimit != undefined) updateInfo.ceLimit = ceLimit;
        if(isAuto != undefined) updateInfo.isAuto = isAuto;
        if(icon != undefined) updateInfo.icon = icon;
        const guild = await GuildModel.updateInfo(code, updateInfo, {}, select.join(' '));
        await pushGuildInfoUpdate(code, { name, notice, introduce, ceLimit, isAuto });

        if(name != undefined) {
            await updateUserInfo(REDIS_KEY.GUILD_INFO, code, [{ field: 'name', value: name }]);
            for(let roleId of guild.members) {
                await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'guildName', value: name }]);
            }
        }
        if (notice != undefined) {
            pushGuildNoticeUpdateMsg(roleId, roleName, guild);
        }
        // 返回
        return resResult(STATUS.SUCCESS, { ...guild });
    }

    // 游客查看军团详细信息
    async getGuildInfo(msg: guildInter & { code: string }, session: BackendSession) {

        const serverId = session.get('serverId');
        const { code } = msg;

        const select = ['code', 'name', 'notice', 'ceLimit', 'isAuto', 'icon', 'lv', 'memberCnt', 'guildCe'];
        const guild = await GuildModel.findByCode(code, null, select.join(' '));
        let leader = <RoleType>guild.leader;
        delete guild.leader;
        // 返回
        return resResult(STATUS.SUCCESS, { ...guild, leader: leader.roleName });

    }

    // 团长授权头衔
    async setAuth(msg: guildInter & { roleId: string, auth: number }, session: BackendSession) {

        const roleId = session.get('roleId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const ip = session.get('ip');
        const { roleId: memberRoleId, auth, myUserGuild, hisUserGuild } = msg;

        const { guildCode: code } = myUserGuild;

        if (auth == hisUserGuild.auth) {
            return resResult(STATUS.GUILD_AUTH_NOT_CHANGE);
        }

        // 管理员最大数 等策划表
        let guild = await GuildModel.findByCode(code, serverId, 'managerCnt lv leagueCode');
        if (!guild) {
            return resResult(STATUS.GUILD_NOT_FOUND);
        }

        let managerCntInc = 0;
        if (auth == GUILD_AUTH.LEADER) { // 转让团长
            if (hisUserGuild.auth == GUILD_AUTH.MANAGER) {
                managerCntInc = -1;
            }
        } else {
            managerCntInc = auth == GUILD_AUTH.MANAGER ? 1 : -1;
        }

        let maxManagerCnt = gameData.centerBase.get(guild.lv);
        if (!maxManagerCnt) return STATUS.DIC_DATA_NOT_FOUND;

        if (guild.managerCnt + managerCntInc > maxManagerCnt.managerNum) {
            return resResult(STATUS.GUILD_MANAGER_REACH_MAX);
        }

        const userGuild = await UserGuildModel.updateInfo(memberRoleId, { auth, job: auth == GUILD_AUTH.LEADER ? GUILD_JOB.DAJIANGJUN : hisUserGuild.job }, {}, 'auth'); // 设置权限
        if (!userGuild) {
            return resResult(STATUS.GUILD_MEMBER_NOT_FOUND);
        }
        await this.app.rpc.connector.connectorRemote.setOtherUserGuildSession.broadcast([{ roleId: memberRoleId, userGuild }]);

        const role = await RoleModel.findByRoleId(memberRoleId);
        let updateObject = {};
        if (auth == GUILD_AUTH.LEADER) { // 转让团长
            updateObject['leader'] = role._id;
            let myUserGuild = await UserGuildModel.updateInfo(roleId, { auth: GUILD_AUTH.MEMBER, job: GUILD_JOB.SHIBING }, {}); // 自己降权限
            setUserGuildSession(session, myUserGuild);
            await updateUserInfo(REDIS_KEY.GUILD_INFO, code, [{ field: 'leader', value: new GuildLeader(role) }]);
            await RoleModel.updateRoleInfo(memberRoleId, { isGuildLeader: true });
            await RoleModel.updateRoleInfo(roleId, { isGuildLeader: false });
            await guildAbdicateToLeague(guild, roleId, role);
        }

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

        // 添加动态
        if (auth == GUILD_AUTH.MANAGER) {
            await pushGuildInfoUpdate(code, { managerCnt: guild.managerCnt });
            await addGuildRecord(roleId, code, GUILD_REC_TYPE.SET_MANAGER, [role.roleName]);
            await sendMailByContent(MAIL_TYPE.GUILD_BE_SET_MANAGER, memberRoleId, { sendName: roleName, params: [guild.name] });
        } else if (auth == GUILD_AUTH.LEADER) {
            await pushChangeGuildLeader(code, guild.managerCnt, role, roleId);
            await addGuildRecord(roleId, code, GUILD_REC_TYPE.SET_LEADER, [roleName, role.roleName]);
            await sendMailByContent(MAIL_TYPE.GUILD_BE_SET_LEADER, memberRoleId, { sendName: roleName, params: [guild.name] });

            reportTAEvent(roleId, TA_EVENT.GUILD_MASTER_CHANGE, { way: GUILD_MASTER_CHANGE_WAY, change_id_after: memberRoleId }, ip);
        } else {
            await pushGuildInfoUpdate(code, { managerCnt: guild.managerCnt });
            await sendMailByContent(MAIL_TYPE.GUILD_BE_SET_MEMBER, memberRoleId, { sendName: roleName, params: [guild.name] });
        }


        // 返回
        return resResult(STATUS.SUCCESS, {
            roleId: memberRoleId, auth: userGuild.auth, managerCnt: guild.managerCnt
        });

    }

    // 团员获取自己军团详细信息
    async getMyGuildInfo(msg: guildInter & {}, session: BackendSession) {
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        let userGuild = await getUserGuildWithRefActive(roleId);
        if (!userGuild) {
            return resResult(STATUS.SUCCESS, { hasGuild: false })
        };

        let guild = await GuildModel.findByCode(userGuild.guildCode, serverId, '+serverId');
        if (!guild) {
            return resResult(STATUS.GUILD_NOT_FOUND);
        }

        let result = await getMyGuildInfo(roleId, sid, userGuild, guild, serverId, session);
        let gvg = await getGVGInfoInGuild(roleId, guild);
        return resResult(STATUS.SUCCESS, { ...result, gvg });
    }

    // 玩家申请公会
    async applyGuild(msg: guildInter & { code: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const { code } = msg;

        const guild = await GuildModel.findByCode(code, serverId);
        if (!guild) return resResult(STATUS.GUILD_NOT_FOUND);

        const { isMemberMax, isAuto, ceLimit, lv } = guild;
        if (isMemberMax) {
            return resResult(STATUS.GUILD_MEMBER_MAX);
        }

        const role = await RoleModel.findByRoleId(roleId, null, true);
        if (ceLimit > role.ce) {
            return resResult(STATUS.GUILD_NOT_REACH_CONDI);
        }

        if(nowSeconds() - role.quitGuildTime < dicParam.ARMY.ARMY_JOIN_COOLDOWNTIME * 60) {
            return resResult(STATUS.GUILD_QUIT_TIME);
        }

        let hasGuild = false;
        if (isAuto) { // 自动加入
            const joinResult = await joinGuild(code, guild.name, lv, roleId, serverId, session);
            if (joinResult.status == -1) {
                return joinResult.resResult;
            }

            // 添加动态
            await addGuildRecord(roleId, code, GUILD_REC_TYPE.JOIN_GUILD, [roleName]);
            // 更新人数增加
            await pushGuildInfoUpdate(code, { memberCnt: joinResult.memberCnt, guildCe: joinResult.guildCe });

            hasGuild = true;
        } else { // 不自动加入，插入申请表
            await UserGuildApplyModel.createUserGuildApply(role, guild, GUILD_APPLY_TYPE.APPLY);
        }

        // 返回
        return resResult(STATUS.SUCCESS, { code, hasGuild });
    }

    // 玩家申请公会
    async getApplyList(msg: guildInter & { code: string, lastApplyCode: string }, session: BackendSession) {

        const { code, lastApplyCode } = msg;

        const result = await UserGuildApplyModel.findApplyByGuild(code, lastApplyCode);
        const list = [];
        for (let cur of result) {
            let role = <RoleType>cur.role;
            delete cur.role;
            let isOnline = await isRoleOnline(role.roleId);
            list.push({ applyCode: cur.applyCode, ...role, isOnline, createTime: getSeconds(cur.createdAt) });
        }

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

    // 团长同意/拒绝公会申请
    async receiveApply(msg: guildInter & { code: string, applyCodeList: [string], isReceived: boolean }, session: BackendSession) {

        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const { code, applyCodeList, isReceived } = msg;

        const applyList = await UserGuildApplyModel.getListByApplyCode(applyCodeList);

        const guild = await GuildModel.findByCode(code, serverId);
        let roleIds = new Array<string>();
        if (isReceived) { // 同意申请，加入

            for (let { roleId } of applyList) {
                const joinResult = await joinGuild(code, guild.name, guild.lv, roleId, serverId, session);
                if (joinResult.status == -1) continue;
                // 更新人数增加
                await pushGuildInfoUpdate(code, { memberCnt: joinResult.memberCnt, guildCe: joinResult.guildCe });
                // 添加动态
                await addGuildRecord(roleId, code, GUILD_REC_TYPE.JOIN_GUILD, [joinResult.roleName]);
                roleIds.push(roleId);
            }
        } else { // 拒绝申请，删除申请
            for (let { roleId } of applyList) {
                await sendMailByContent(MAIL_TYPE.GUILD_APPLY_REFUSE, roleId, { sendName: roleName, params: [guild.name] });
                roleIds.push(roleId);
            }

            await UserGuildApplyModel.deleteByApplyCode(applyCodeList);
        }

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

    // 团长查看（刷新）可邀请人列表
    async getInviteMemberList(msg: guildInter & {}, session: BackendSession) {

        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const { myUserGuild: myGuild } = msg;
        let guild = await GuildModel.findByCode(myGuild.guildCode, serverId, GUILD_SELECT.INVITED_MEMBER);
        let invitedMembers = guild.invitedMembers;
        if (shouldRefresh(guild.inviteTime, new Date())) {
            invitedMembers = [];
        }

        // 离线时间，三天内在线且尚未加入军团。按以下规则排序  离线时间 玩家等级 玩家战力

        const day = <number>getTimeFun().getBeforeDay(3);

        const { quitGuildTime: quitTime = 0 } = await RoleModel.findByRoleId(roleId);
        let allList = await RoleModel.getInviteList(day, serverId);
        allList = allList.filter(cur => !invitedMembers.includes(cur.roleId))
        let list = getRandEelm(allList, 10);
        if (!list.length) list = allList;
        list = sortArrRandom(list);

        let result = [];
        for (let cur of list) {
            let isOnline = await isRoleOnline(cur.roleId);
            result.push({ ...cur, isOnline })
        }

        return resResult(STATUS.SUCCESS, { quitTime, list: result });

    }

    // 团长（一键）邀请人
    async inviteMember(msg: guildInter & { code: string, roleIds: string[] }, session: BackendSession) {

        const serverId = session.get('serverId');
        const { code, roleIds } = msg;

        const guild = await GuildModel.findByCode(code, serverId, GUILD_SELECT.INVITED_MEMBER);
        if (guild.isMemberMax) return resResult(STATUS.GUILD_MEMBER_MAX);

        const roleList = await RoleModel.findByRoleIds(roleIds);
        let result = new Array<string>();
        
        for (let role of roleList) {
            if (!role.hasGuild || role.serverId == serverId) {
                let apply = await UserGuildApplyModel.createUserGuildApply(role, guild, GUILD_APPLY_TYPE.INVITE);
                result.push(role.roleId);
                let hisInfo = await getRoleOnlineInfo(role.roleId);
                if (hisInfo.isOnline) {
                    let guild = <GuildType>apply.guild;
                    let leader = <RoleType>guild.leader;
                    let invitation = { applyCode: apply.applyCode, ...guild, leader: leader.roleName };
                    sendMessageToUserWithSuc(role.roleId, PUSH_ROUTE.GUILD_INVITE, { invitation }, hisInfo.sid);
                }
            }
        }
        if(result.length <= 0) {
            return resResult(STATUS.GUILD_CANNOT_INVITE)
        }

        await GuildModel.recordInvitedMember(code, serverId, roleIds, shouldRefresh(guild.inviteTime, new Date()));

        return resResult(STATUS.SUCCESS, { roleIds: result });

    }

    // 成员收到邀请列表
    async getInvitationList(msg: guildInter & { lastApplyCode: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const { lastApplyCode } = msg;
        let list = await getInvitationList(roleId, lastApplyCode);

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

    }


    // 成员同意/拒绝邀请
    async receiveInvitation(msg: guildInter & { applyCode: string, isReceived: boolean }, session: BackendSession) {

        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const { applyCode, isReceived } = msg;

        const invite = await UserGuildApplyModel.findByCode(applyCode);
        if (!invite) return resResult(STATUS.GUILD_INVITE_NOT_FOUND);

        let code: string;
        if (isReceived) { // 同意申请，加入
            const { guildCode } = invite;
            const guild = await GuildModel.findByCode(guildCode, serverId);
            if (!guild) {
                await UserGuildApplyModel.deleteByApplyCode([applyCode]); // 删除这条邀请
                return resResult(STATUS.GUILD_DELETE_ERROR);
            }

            const joinResult = await joinGuild(guildCode, guild.name, guild.lv, roleId, serverId, session);
            if (joinResult.status == -1) {
                return joinResult.resResult;
            }

            // 更新人数增加
            await pushGuildInfoUpdate(code, { memberCnt: joinResult.memberCnt, guildCe: joinResult.guildCe });
            // 添加动态
            await addGuildRecord(roleId, code, GUILD_REC_TYPE.JOIN_GUILD, [joinResult.roleName]);

            code = guild.code;
        }
        await UserGuildApplyModel.deleteByApplyCode([applyCode]); // 删除这条邀请

        return resResult(STATUS.SUCCESS, { applyCode, code, isReceived, hasGuild: isReceived });
    }

    // 获取军团成员
    async getGuildMember(msg: { code: string, sort: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const guildAuth: number = session.get('guildAuth');
        // const serverId = session.get('serverId');
        const { code, sort } = msg;

        let select = ['role', 'job'];
        const checkDetailResult = await checkAuth(GUILD_OPERATE.GET_MEMBER_LIST_DETAIL, code, guildAuth);
        if (checkDetailResult) {
            select.push('auth', 'activeWeekly activeUpdateTime');
        }
        let list = await UserGuildModel.getListByGuild(code, select.join(' '), { auth: 1 });
        let result: GuildMemberParam[] = [];
        for (let cur of list) {
            let role = <RoleType>cur.role;
            if(role) {
                let param = new GuildMemberParam(cur, role);
                let isOnline = await isRoleOnline(role.roleId);
                param.setOnline(!!isOnline);
                result.push(param);
            }
        }

        if (result && result.length > 0) {
            let leader = result.shift(); // 团长在最上面
            result.sort((a, b) => {
                if (sort == 'active') {
                    if (b.activeWeekly == a.activeWeekly) {
                        return a.activeUpdateTime - b.activeUpdateTime
                    } else {
                        return b.activeWeekly - a.activeWeekly
                    }
                } else if (sort == 'loginTime') {
                    return b.quitTime - a.quitTime;
                } else {
                    return b.ce - a.ce;
                }
            });
            result.unshift(leader);
        } else {
            // 此处应有异常
        }
        return resResult(STATUS.SUCCESS, { list: result });
    }

    // 团长解散军团
    async dismiss(msg: guildInter & { code: string }, session: BackendSession) {

        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleId = session.get('roleId');
        const ip = session.get('ip');
        const { code } = msg;

        let guild = await GuildModel.findByCode(code, serverId, 'leagueCode');
        if(guild.leagueCode) return resResult(STATUS.GVG_GUILD_HAS_LEAGUE); 

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

        await sendMailToGuildByContent(MAIL_TYPE.GUILD_DISSMISS, code, {}, guild);
        await UserGuildModel.dismiss(code);
        const { members } = guild;
        await RoleModel.dissmissGuild(members);
        await UserGuildApplyModel.deleteApplyByGuild(code);
        await guildDismissToLeague(guild);

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

        // 删除channel
        await guildDismisActivity(code, serverId);
        await pushGuildDismiss(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 });
        reportTAEvent(roleId, TA_EVENT.GUILD_DISMISS, { name: guild.name, way: GUILD_DISMISS_WAY.GAME }, ip);
        for(let roleId of members) {
            reportTAEvent(roleId, TA_EVENT.GUILD_QUIT, { name: guild.name, way: GUILD_QUIT_WAY.DISMISS }, ip);
            updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'guildName', value: '' }]);
        }
        leaveRaceWhenDismissToRemote(serverId, code);

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

    // 成员退出军团
    async quit(msg: guildInter & { code: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        const sid = session.get('sid');
        const ip = session.get('ip');
        const { code } = msg;

        const userGuild = await UserGuildModel.quit(code, roleId);
        if (!userGuild) return resResult(STATUS.GUILD_QUIT_ERROR);

        const role = await RoleModel.quitGuild(roleId, nowSeconds());
        if (!role) return resResult(STATUS.GUILD_QUIT_ERROR);

        const guild = await GuildModel.quit(code, roleId, serverId, role.ce, userGuild.auth == GUILD_AUTH.MANAGER);
        if (!guild) return resResult(STATUS.GUILD_QUIT_ERROR);
        await updateUserInfo(REDIS_KEY.GUILD_INFO, guild.code, [{ field: 'guildCe', value: guild.guildCe }])
        await updateUserInfo(REDIS_KEY.USER_INFO, roleId, [{ field: 'guildName', value: '' }]);
        await memberQuitGuildToLeague(guild, role);

        //删除排名信息
        await removeBossRank(code, roleId);
        await removeTrainRank(code, roleId, guild.trainId);
        // 添加动态
        await addGuildRecord(roleId, code, GUILD_REC_TYPE.QUIT_GUILD, [roleName]);
        await pushGuildMemberQuit(roleId, code, guild, sid);

        setUserGuildSession(session, null);
        reportTAEvent(roleId, TA_EVENT.GUILD_QUIT, { name: guild.name, way: GUILD_QUIT_WAY.QUIT }, ip);
        changeGuildActivity('', serverId, roleId, sid);
        leaveRaceWhenQuitGuildToRemote(serverId, guildCode, roleId);
        guildPayQuitGuild(serverId, code, roleId);
        leaveCity(true, roleId, serverId, guildCode);

        return resResult(STATUS.SUCCESS, { hasGuild: role.hasGuild });
    }

    // 团长踢退出军团
    async kick(msg: guildInter & { code: string, roleId: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const { code, roleId: memberRoleId } = msg;

        const userGuild = await UserGuildModel.quit(code, memberRoleId);
        if (!userGuild) return resResult(STATUS.GUILD_KICK_ERROR);

        const role = await RoleModel.quitGuild(memberRoleId, nowSeconds());
        if (!role) return resResult(STATUS.GUILD_KICK_ERROR);

        const guild = await GuildModel.quit(code, memberRoleId, serverId, role.ce, userGuild.auth == GUILD_AUTH.MANAGER);
        if (!guild) return resResult(STATUS.GUILD_KICK_ERROR);
        await updateUserInfo(REDIS_KEY.GUILD_INFO, guild.code, [{ field: 'guildCe', value: guild.guildCe }])
        await updateUserInfo(REDIS_KEY.USER_INFO, memberRoleId, [{ field: 'guildName', value: '' }]);
        await memberQuitGuildToLeague(guild, role);

        //删除排名信息
        await removeBossRank(code, memberRoleId);
        await removeTrainRank(code, roleId, guild.trainId);
        const { isOnline, sid } = await getRoleOnlineInfo(memberRoleId);
        await pushGuildMemberQuit(roleId, code, guild, sid);

        // 添加动态
        await addGuildRecord(roleId, code, GUILD_REC_TYPE.QUIT_GUILD, [role.roleName]);
        if(isOnline) {
            await this.app.rpc.connector.connectorRemote.setOtherUserGuildSession.toServer(sid,[{ roleId: memberRoleId, userGuild }]);
            changeGuildActivity('', serverId, memberRoleId, sid);
        }

        await sendMailByContent(MAIL_TYPE.GUILD_BE_KICK, memberRoleId, { sendName: roleName, params: [guild.name] });
        reportTAEvent(memberRoleId, TA_EVENT.GUILD_QUIT, { name: guild.name, way: GUILD_QUIT_WAY.KICK });
        leaveRaceWhenQuitGuildToRemote(serverId, code, memberRoleId);
        guildPayQuitGuild(serverId, code, memberRoleId);
        leaveCity(true, memberRoleId, serverId, code);

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

    // 团员弹劾团长
    async impeach(msg: guildInter & { code: string, roleId: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const sid = session.get('sid');
        const serverId = session.get('serverId');
        const ip = session.get('ip');
        const { code, roleId: leaderRoleId } = msg;

        // 离线72小时
        const { roleName: oldRoleName, quitTime } = await RoleModel.findByRoleId(leaderRoleId);
        if (quitTime > <number>getTimeFun().getBeforeDay(3)) {
            return resResult(STATUS.GUILD_LEADER_LOGIN);
        }
        // 上周周功勋最高的人
        const topUserGuilds = await UserGuildModel.findTopActive(code, 'auth role roleId');
        if (topUserGuilds.length <= 0) {
            return resResult(STATUS.GUILD_MEMBER_NOT_FOUND);
        }
        let topUserGuild: UserGuildType;
        for (let userGuild of topUserGuilds) {
            let role = await RoleModel.findByRoleId(userGuild.roleId, 'quitTime');
            if (role && role.quitTime > <number>getTimeFun().getBeforeDay(3)) {
                topUserGuild = userGuild; break;
            }
        }
        if (!topUserGuild) {
            return resResult(STATUS.GUILD_MEMBER_NOT_FOUND);
        }

        // 检查元宝是否够
        const role = await RoleModel.findByRoleId(roleId);
        if (ARMY.ARMY_IMPEACH_COST > role.gold) {
            return resResult(STATUS.DAILY_REFRESH_GOLD_LACK);
        }
        await handleCost(roleId, sid, [getGoldObject(ARMY.ARMY_IMPEACH_COST)], ITEM_CHANGE_REASON.GUILD_IMPEACH);

        const topUser = <RoleType>topUserGuild.role;
        // 交换

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

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

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

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

        // 添加动态
        await addGuildRecord(roleId, code, GUILD_REC_TYPE.IMPEACH, [oldRoleName, topUser.roleName]);
        await pushChangeGuildLeader(code, guild.managerCnt, topUser, leaderRoleId);
        await sendMailByContent(MAIL_TYPE.GUILD_BE_IMPEACH, leaderRoleId, { sendName: roleName, params: [guild.name] });
        await sendMailByContent(MAIL_TYPE.GUILD_BE_SET_LEADER, topUser.roleId, { sendName: roleName, params: [guild.name] });

        await updateUserInfo(REDIS_KEY.GUILD_INFO, code, [{ field: 'leader', value: new GuildLeader(topUser) }]);
        await RoleModel.updateRoleInfo(leaderRoleId, { isGuildLeader: false });
        let newLeader = await RoleModel.updateRoleInfo(topUser.roleId, { isGuildLeader: true });
        await guildAbdicateToLeague(guild, leaderRoleId, newLeader);
        reportTAEvent(roleId, TA_EVENT.GUILD_MASTER_CHANGE, { way: GUILD_MASTER_CHANGE_WAY.IMPEACH, change_id_after: topUser.roleId }, ip)

        let isOnline = await isRoleOnline(topUser.roleId);
        const leader = { ...topUser, ce: topUser.ce, isOnline }
        return resResult(STATUS.SUCCESS, {
            code, managerCnt: guild.managerCnt, leader
        });
    }

    // 升级建筑物等级
    async upStructure(msg: guildInter & { code: string, id: number }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const { code, id } = msg;

        const guild = await GuildModel.findByCode(code, serverId, 'lv structure activeWeekly lvUpdateTime');
        if (!guild) {
            return resResult(STATUS.GUILD_NOT_FOUND);
        }

        const { lv, structure } = guild;
        const curStructure = structure.find(cur => cur.id == id);
        if (!curStructure) {
            return resResult(STATUS.GUILD_STRUCTURE_NOT_FOUND);
        }
        if (id != GUILD_STRUCTURE.ARMY_CENTER && curStructure.lv >= lv) { // 中军大帐以外建筑物
            if (curStructure.lv >= lv) {
                return resResult(STATUS.GUILD_STRUCTURE_LV_MAX);
            }
        }
        if (!hasStructureConsume(id, curStructure.lv + 1)) {
            return resResult(STATUS.GUILD_STRUCTURE_LV_MAX);
        }
        const cost = getStructureConsume(id, curStructure.lv);

        const result = await GuildModel.upStructure(code, id, cost, 'code fund structure lv activeWeekly lvUpdateTime name');
        if (!result) {
            return resResult(STATUS.GUILD_FUND_NOT_ENOUGH);
        }
        if (id == GUILD_STRUCTURE.ARMY_CENTER) {
            let r = new Rank(REDIS_KEY.GUILD_LV_RANK, { serverId });
            await r.setRankWithGuildInfo2(code, result.lv, result.activeWeekly, result.lvUpdateTime, result);
        }

        const resultStructure = result.structure.find(cur => cur.id == id);

        // 修改信息
        await pushGuildInfoUpdate(code, { ...result });
        await updateUserInfo(REDIS_KEY.GUILD_INFO, code, [{ field: 'lv', value: result.lv }]);

        // 添加动态
        const structureName = GUILD_STRUCTURE_NAME.get(id);
        await addGuildRecord(roleId, code, GUILD_REC_TYPE.STRUCTURE_UP, [structureName, resultStructure.lv.toString()]);

        // 军团频道聊天消息
        pushGuildUpStructureMsg(roleId, roleName, result, resultStructure);

        return resResult(STATUS.SUCCESS, result);
    }


    // 获取动态
    async getRec(msg: guildInter & { code: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const { code } = msg;

        // console.log(startTime)
        const list = await GuildRecModel.getGuildRec(code, <number>getTimeFun().getBeforeDayWithHour(3));

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

    // 团长发送消息给军团内所有成员的邮箱
    async sendMail(msg: guildInter & { code: string, info: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const { code, info, myUserGuild } = msg;

        const guild = await GuildModel.findByCode(code, serverId, 'members');
        if (!guild) return resResult(STATUS.GUILD_NOT_FOUND);

        const { members } = guild;
        const jobName = myUserGuild.auth == 1? '大将军': '管理';
        //下发邮件
        await sendMailToGuildByContent(MAIL_TYPE.GUILD_MAIL, code, { sendName: `${jobName}：${roleName}`, params: [info] }, guild);

        return resResult(STATUS.SUCCESS, { isSuccess: true });
    }

    // 团长发送世界频道
    async recruit(msg: guildInter & { code: string, info: string }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        
        const { code, info } = msg;
        const guild = await GuildModel.findByCode(code, serverId);
        if (!guild) return resResult(STATUS.GUILD_NOT_FOUND);


        // 发送世界频道消息
        let channelId = `${serverId}`;
        const msgData = await createGroupMsg(roleId, roleName, CHANNEL_PREFIX.WORLD, channelId, MSG_TYPE.RICH_TEXT, MSG_SOURCE.GUILD_RECURIT, JSON.stringify({ guildCode: guild.code, guildName: guild.name, info }), '', '');
        if (!msgData) return resResult(STATUS.WRONG_PARMS);
        await pushGroupMsgToRoom(msgData);

        return resResult(STATUS.SUCCESS, { isSuccess: true });
    }

    // 领取活跃奖励
    async receiveActiveBox(msg: guildInter & { code: string, id: number }, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const sid = session.get('sid');
        const serverId = session.get('serverId');
        
        const { code, id } = msg;

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

        let activeDayReward = gameData.guildActiveDayReward.get(id);
        if (!activeDayReward) return resResult(STATUS.GUILD_ACTIVE_BOX_NOT_FOUND);

        const guildActive = await getTodayGuildActive(code);
        if (guildActive < activeDayReward.activeDayPoint) {
            return resResult(STATUS.GUILD_ACTIVE_POINT_NOT_REACH);
        }

        if (userGuild.receivedActive.includes(id)) {
            return resResult(STATUS.GUILD_ACTIVE_BOX_HAS_RECEIVED);
        }
        userGuild.receivedActive.push(id);

        let goods = await addItems(roleId, roleName, sid, activeDayReward.reward, ITEM_CHANGE_REASON.GUILD_ACTIVE_REWARD);
        userGuild = await UserGuildModel.updateInfo(roleId, { receivedActive: userGuild.receivedActive }, {}, 'receivedActive');

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.GUILD_RECEIVE_BOX);
        return resResult(STATUS.SUCCESS, { goods, receivedActive: userGuild.receivedActive });
    }

    // 查看活跃排行榜
    async getActiveRank(msg: guildInter & {}, session: BackendSession) {
        let serverId = session.get('serverId')
        const { myUserGuild } = msg;

        let r = new Rank(REDIS_KEY.GUILD_ACTIVE_RANK, { serverId });
        let { ranks, myRank } = await r.getRankListWithMyRank({ guildCode: myUserGuild.guildCode });
        if (!myRank) {
            let guild = await GuildModel.findByCode(myUserGuild.guildCode, serverId, 'code icon name lv leader activeWeekly');
            myRank = await r.generMyRankWithGuild(myUserGuild.guildCode, guild.activeWeekly, guild.activeUpdateTime, guild);
        }

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

    // debug接口： 添加公会活跃值
    async debugAddActive(msg: guildInter & { magicWord: string, code: string, active: number, id: number }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const { code, active, id } = msg;

        const result = await addActive(roleId, serverId, id, null, active);
        if (result.status == 0) return result.resResult;
        const { guild, userGuild } = result;
        let today = getZeroPointD();
        let guildActive = await GuildActiveModel.addActive(code, today, active);

        let { activeWeekly } = guild;
        await pushGuildInfoUpdate(code, { activeDaily: guildActive? guildActive.active: 0, activeWeekly });
        return resResult(STATUS.SUCCESS, { activeDaily: guildActive? guildActive.active: 0, activeWeekly, myInfo: userGuild });
    }

    // debug接口： 调用定时任务
    async debugWeeklyRask(msg: guildInter & { magicWord: string }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        await settleGuildWeekly();
        return resResult(STATUS.SUCCESS);
    }

    // debug接口： 添加军团资金
    async debugAdddFund(msg: guildInter & { magicWord: string, code: string, count: number }, session: BackendSession) {

        const { code, count, magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const guild = await GuildModel.updateInfo(code, {}, { fund: count }, 'fund');
        await pushGuildInfoUpdate(code, { fund: guild.fund });
        return resResult(STATUS.SUCCESS, { code, fund: guild.fund });
    }

    // debug接口： 加长会长离线时间
    async debugLeaderLeaveTime(msg: guildInter & { magicWord: string, code: string }, session: BackendSession) {

        const { code, magicWord } = msg;
        // if (magicWord !== DEBUG_MAGIC_WORD) {
        //     return resResult(STATUS.TOKEN_ERR);
        // }
        const serverId = session.get('serverId');
        const guild = await GuildModel.findByCode(code, serverId);
        const leader = <RoleType>guild.leader;
        let threeDaysBefore = <number>getTimeFun().getBeforeDay(3);
        await RoleModel.updateRoleInfo(leader.roleId, { quitTime: threeDaysBefore });

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

    // debug接口： 情况退军团时间
    async debugClearQuitGuildTime(msg: { magicWord: string, type: number }, session: BackendSession) {

        const { magicWord, type = 0 } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const roleId = session.get('roleId');
        const quitGuildTime = type ? Math.floor((new Date().getTime() - HOUR_TO_MS * 2) / 1000) : 0;
        await RoleModel.updateRoleInfo(roleId, { quitGuildTime: quitGuildTime });

        return resResult(STATUS.SUCCESS);
    }

    // debug接口： 加入公会
    async debugJoinGuild(msg: guildInter & { magicWord: string, code: string }, session: BackendSession) {
        const { code, magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const sid = session.get('sid');

        const guild = await GuildModel.findByCode(code, serverId);
        if (!guild) return resResult(STATUS.GUILD_NOT_FOUND);

        const { isMemberMax, isAuto, ceLimit, lv } = guild;

        let role = await RoleModel.findByRoleId(roleId);
        if (role.guildCode) {
            let oldCode = role.guildCode;
            const userGuild = await UserGuildModel.quit(oldCode, roleId);
            if (!userGuild) return resResult(STATUS.GUILD_QUIT_ERROR);

            role = await RoleModel.quitGuild(roleId, nowSeconds());
            if (!role) return resResult(STATUS.GUILD_QUIT_ERROR);

            const guild = await GuildModel.quit(oldCode, roleId, serverId, role.ce, userGuild.auth == GUILD_AUTH.MANAGER);
            if (!guild) return resResult(STATUS.GUILD_QUIT_ERROR);
            await updateUserInfo(REDIS_KEY.GUILD_INFO, guild.code, [{ field: 'guildCe', value: guild.guildCe }])

            //删除排名信息
            await removeBossRank(oldCode, roleId);
            await removeTrainRank(oldCode, roleId, guild.trainId);
            // 添加动态
            await addGuildRecord(roleId, oldCode, GUILD_REC_TYPE.QUIT_GUILD, [roleName]);
            await pushGuildMemberQuit(roleId, oldCode, guild, sid);

            setUserGuildSession(session, userGuild);
        }

        const joinResult = await joinGuild(code, guild.name, lv, roleId, serverId, session);
        if (joinResult.status == -1) {
            return joinResult.resResult;
        }

        // 添加动态
        await addGuildRecord(roleId, code, GUILD_REC_TYPE.JOIN_GUILD, [roleName]);
        // 更新人数增加
        await pushGuildInfoUpdate(code, { memberCnt: joinResult.memberCnt, guildCe: joinResult.guildCe });
        return resResult(STATUS.SUCCESS, { code });
    }
}

