import { Application, BackendSession, pinus } from 'pinus';
import { RoleModel } from '../../../db/Role';
import { EventRecordModel } from '../../../db/EventRecord';
import { getEvent } from '../../../services/eventSercive';
import { getRandSingleEelm, resResult } from '../../../pubUtils/util';
import { STATUS } from '../../../consts/statusCode';
import { GMMailModel } from '../../../db/GMMail';
import { delGuildActivityRank, getRoleOnlineInfo } from '../../../services/redisService';
import { SendMailFun } from '../../../services/mailService';
import { GM_MAIL_TYPE } from '../../../consts';
import { RewardInter } from '../../../pubUtils/interface';
import { MarqueeModel } from '../../../db/Marquee';
import { ServerlistModel } from '../../../db/Serverlist';
import { pushCurrentTime } from '../../../services/chatService';
import { MaintenanceModel } from '../../../db/Maintenance';
import { initMaintenance, stopMaintenance } from '../../../services/gmService';
import { checkActivityEditable, checkActivityGroupType } from '../../../services/activity/activityService';
import { ActivityModel } from '../../../db/Activity';
import { ActivityGroupModel } from '../../../db/ActivityGroup';
import { ActivityGroupTypeModel } from '../../../db/ActivityGroupType';
import { GuildActivityCityModel } from '../../../db/GuildActivityCity';
import { GuildActivityRecordModel } from '../../../db/GuildActivityRec';
import { getTimeFunM } from '../../../pubUtils/timeUtil';
import { sendUngotDividend } from '../../../services/auctionService';
let timer: NodeJS.Timer;
export default function (app: Application) {
    return new GmHandler(app);
}

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

    async pushEvent(msg: { uid: number, serverId: number }, session: BackendSession) {

        let { uid, serverId } = msg;
        let role = await RoleModel.findByUid(uid, serverId);
        if (!role) return resResult(STATUS.GM_ROLE_NOT_FOUND);
        let { roleId, roleName, eventStatus } = role;

        let channelService = this.app.get('channelService');
        let event = await getEvent(eventStatus, roleId, roleName);
        let hisOnlineInfo = await getRoleOnlineInfo(role.roleId);
        if (hisOnlineInfo.isOnline) {
            channelService.pushMessageByUids('onSpecialEvent', resResult(STATUS.SUCCESS, { event }), [{
                uid: roleId,
                sid: hisOnlineInfo.sid
            }]);
        }
        return resResult(STATUS.SUCCESS, { list: event });
    }

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

        await EventRecordModel.deleteAccount(roleId);
        return resResult(STATUS.SUCCESS);
    }


    async pushMessage(msg: { uid: number, serverId: number, eventName: string, message: string }, session: BackendSession) {

        let { uid, serverId, eventName, message } = msg;

        let content = {};
        try {
            content = JSON.parse(message);
        } catch (e) {
            return resResult(STATUS.GM_JSON_FORMAT_ERR);
        }
        // console.log(uid, serverId)
        let role = await RoleModel.findByUid(uid, serverId);
        if (!role) return resResult(STATUS.GM_ROLE_NOT_FOUND);
        let { roleId } = role;

        let hisOnlineInfo = await getRoleOnlineInfo(role.roleId);
        if (hisOnlineInfo.isOnline) {
            let sid = hisOnlineInfo.sid;
            if (!!sid) {//下发邮件，对应前端红点提示
                pinus.app.channelService.pushMessageByUids(eventName, resResult(STATUS.SUCCESS, content), [{ uid: roleId, sid }]);
            }
        }
        return resResult(STATUS.SUCCESS, { msg: content });
    }

    //对接gm后台，下发邮件
    async addMail(msg: { endTime: number, sendName: string, content: string, goods: RewardInter[], sendTime: number }) {
        let { endTime, content, sendName, sendTime, goods } = msg;
        let mail = await GMMailModel.addMail({ endTime, content, sendName, sendTime, goods });
        return resResult(STATUS.SUCCESS, { mail });
    }

    async sendMail(msg: { id: string, mailType: number, roleIds?: string[], serverIds?: number[] }, session: BackendSession) {
        const uid: number = session.get('uid')
        let { id, mailType, roleIds, serverIds } = msg;
        let f = new SendMailFun();
        await f.setWithGmMail(id);
        if (mailType == GM_MAIL_TYPE.SINGLE || mailType == GM_MAIL_TYPE.GROUP) {
            await f.sendToUsers(mailType, roleIds);
        } else {
            await f.sendToServer(serverIds);
        }
        await f.saveRecord(uid);
        return resResult(STATUS.SUCCESS);
    }

    async sendWithContent(msg: { contentId: number, mailType: number, params: { params?: string[], sendName?: string, goods?: RewardInter[], endTime?: number }, roleIds?: string[], serverIds?: number[] }, session: BackendSession) {
        let { contentId, mailType, roleIds, serverIds, params } = msg;
        let f = new SendMailFun();
        f.setWithContentId(contentId, params);
        if (mailType == GM_MAIL_TYPE.SINGLE || mailType == GM_MAIL_TYPE.GROUP) {
            await f.sendToUsers(mailType, roleIds);
        } else {
            await f.sendToServer(serverIds);
        }
        return resResult(STATUS.SUCCESS);
    }

    async reloadResource(msg: {}, session: BackendSession) {
        try {
            let activityServers = this.app.getServersByType('activity');
            for (let { id } of activityServers) {
                await this.app.rpc.activity.activityRemote.reloadResources.toServer(id);
            }
            let battleServers = this.app.getServersByType('battle');
            for (let { id } of battleServers) {
                await this.app.rpc.battle.battleRemote.reloadResources.toServer(id);
            }
            let chatServers = this.app.getServersByType('chat');
            for (let { id } of chatServers) {
                await this.app.rpc.chat.chatRemote.reloadResources.toServer(id);
            }
            let connectServers = this.app.getServersByType('connector');
            for (let { id } of connectServers) {
                await this.app.rpc.connector.connectorRemote.reloadResources.toServer(id);
            }
            let guildServers = this.app.getServersByType('guild');
            for (let { id } of guildServers) {
                await this.app.rpc.guild.guildRemote.reloadResources.toServer(id);
            }
            let roleServers = this.app.getServersByType('role');
            for (let { id } of roleServers) {
                await this.app.rpc.role.roleRemote.reloadResources.toServer(id);
            }
            let systimerServers = this.app.getServersByType('systimer');
            for (let { id } of systimerServers) {
                await this.app.rpc.systimer.systimerRemote.reloadResources.toServer(id);
            }
            let orderServers = this.app.getServersByType('order');
            for (let { id } of orderServers) {
                await this.app.rpc.order.orderRemote.reloadResources.toServer(id);
            }
            return resResult(STATUS.SUCCESS, {
                isOK: true
            });
        } catch (e) {
            return resResult(STATUS.SUCCESS, {
                isOK: false,
                err: e.stack
            });
        }
    }

    async createMarquee(msg: { startTime: string, endTime: string, interval: number, content: string }, session: BackendSession) {
        const { startTime, endTime, interval, content } = msg;
        let marquee = await MarqueeModel.createData({ serverIds: [1], type: 2, startTime: new Date(startTime), endTime: new Date(endTime), interval, content });
        return resResult(STATUS.SUCCESS, {
            code: marquee.code
        });
    }

    async sendMarquee(msg: { code: string }, session: BackendSession) {
        const { code } = msg;
        let systimerServers = this.app.getServersByType('systimer');
        for (let { id } of systimerServers) {
            let result = await this.app.rpc.systimer.systimerRemote.setMarquee.toServer(id, code);
            if (!result) return resResult(STATUS.GM_MARQUEE_ERR);
        }
        return resResult(STATUS.SUCCESS);
    }

    async cancelMarquee(msg: { code: string }, session: BackendSession) {
        const { code } = msg;
        let systimerServers = this.app.getServersByType('systimer');
        for (let { id } of systimerServers) {
            let result = await this.app.rpc.systimer.systimerRemote.cancelMarquee.toServer(id, code);
            if (!result) return resResult(STATUS.GM_MARQUEE_CANCEL_ERR);
        }
        return resResult(STATUS.SUCCESS);
    }

    async startMaintenance(msg: { code: string }, session: BackendSession) {
        const { code } = msg;
        const uid = session.get('uid');
        const maintenance = await MaintenanceModel.updateStatusByCode(code, true, uid);
        if (!maintenance) return resResult(STATUS.WRONG_PARMS);
        await initMaintenance(maintenance);

        return resResult(STATUS.SUCCESS,);
    }

    async stopMaintenance(msg: { code: string }, session: BackendSession) {
        const { code } = msg;
        const uid = session.get('uid');
        const maintenance = await MaintenanceModel.updateStatusByCode(code, false, uid);
        if (!maintenance) return resResult(STATUS.WRONG_PARMS);
        await stopMaintenance(maintenance, uid);

        return resResult(STATUS.SUCCESS,);
    }

    async setMaintenance() {
        pinus.app.rpc.connector.connectorRemote.setServerMainten.broadcast([1]);
        return resResult(STATUS.SUCCESS);
    }

    async updateActivity(msg: { activityId: number|string, groupId: number, beginTime: number, endTime: number, type: number, data: string }, session: BackendSession) {
        const { activityId, groupId, beginTime, endTime, type, data } = msg;
        const uid = session.get('uid');
        if (!type || !data) {
            return resResult(STATUS.WRONG_PARMS);
        }
        let aids: number[] = [];
        if (typeof activityId == 'number') {
            aids.push(activityId);
        } else {
            activityId.split(',').forEach(aidStr => {
                aids.push(parseInt(aidStr));
            });
        }
        let activities = await ActivityModel.findActivityByIds(aids);
        let checkTimeResult = await checkActivityEditable(activities);
        if(!checkTimeResult) return resResult(STATUS.GM_CAN_NOT_EDIT_ACT);
        let checkGroup = await checkActivityGroupType(groupId, activities);
        if(!checkGroup) return resResult(STATUS.GM_ACTIVITY_NOT_FIT_GROUP_TYPE);

        activities = await ActivityModel.addActivity(aids, groupId, beginTime ? new Date(beginTime) : undefined, endTime ? new Date(endTime) : undefined, type, data, uid);

        let activityServers = pinus.app.getServersByType('activity');
        for(let server of activityServers) {
            pinus.app.rpc.activity.activityRemote.updateActivities.toServer(server.id, activities);
        }

        return resResult(STATUS.SUCCESS, {
            activity: activities
        });
    }

    async deleteActivity(msg: { activityId: number}, session: BackendSession) {
        const { activityId } = msg;
        const uid = session.get('uid');

        const result = await ActivityModel.deleteActivity(activityId, uid);
        if (!result) {
            return resResult(STATUS.ACTIVITY_MISSING);
        }
        let activityServers = pinus.app.getServersByType('activity');
        for(let server of activityServers) {
            pinus.app.rpc.activity.activityRemote.deleteActivities.toServer(server.id, [activityId]);
        }

        return resResult(STATUS.SUCCESS);
    }

    async saveGroupToServer(msg: { groupId: number, serverIds: number[] }, session: BackendSession) {
        const { groupId, serverIds } = msg;
        const uid = session.get('uid');
        
        await ServerlistModel.pullByGroupId(groupId);
        let servers = await ServerlistModel.findServerByIds(serverIds);
        for(let server of servers) {
            let pushArr: number[] = [], pullArr: number[] = [];
            let activityGroupId = server.activityGroupId||[];
            if(!activityGroupId.includes(groupId)) {
                pushArr.push(groupId);
            }
            await ServerlistModel.updateActivityGroup(server._id, pushArr, pullArr);
        }
        await ActivityGroupModel.updateServerData(groupId, serverIds, uid);

        let activityServers = pinus.app.getServersByType('activity');
        for(let server of activityServers) {
            pinus.app.rpc.activity.activityRemote.saveGroupToServer.toServer(server.id, groupId, serverIds);
        }

        return resResult(STATUS.SUCCESS);
    }

    /**
     * 选择活动组内的活动
     */
    async saveActivitiesToGroup(msg: { groupId: number, activities: number[] }, session: BackendSession) {
        const { groupId, activities: activityIds } = msg;
        const uid = session.get('uid');

        let activities = await ActivityModel.findActivityByIds(activityIds);
        let checkResult = await checkActivityGroupType(groupId, activities);
        if(!checkResult) return resResult(STATUS.GM_ACTIVITY_NOT_FIT_GROUP_TYPE);

        await ActivityGroupModel.setActivitiesToGroupData(groupId, activityIds, uid);
    
        let activityServers = pinus.app.getServersByType('activity');
        for(let server of activityServers) {
            pinus.app.rpc.activity.activityRemote.saveActivitiesToGroup.toServer(server.id, groupId, activityIds);
        }
        return resResult(STATUS.SUCCESS)
    }

    async saveSingleActivityToGroup(msg: { groupId: number, index: number, activityId: number }, session: BackendSession) {
        const { groupId, index, activityId } = msg;
        const uid = session.get('uid');
        
        let activity = await ActivityModel.findActivity(activityId);
        if(!activity) return resResult(STATUS.ACTIVITY_MISSING);
        let checkResult = await checkActivityGroupType(groupId, [activity]);
        if(checkResult) return checkResult;

        let activityGroup = await ActivityGroupModel.findGroupData(groupId);
        if(!activityGroup) return resResult(STATUS.GM_ACTIVITY_GROUP_NOT_FOUND);

        if(activityGroup.type != 0) {
            let activityGroupType = await ActivityGroupTypeModel.findByGroupType(activityGroup.type);
            if(!activityGroupType) return resResult(STATUS.GM_ACTIVITY_GROUP_TYPE_NOT_FOUND);
            let dic = activityGroupType.activityTypes;
            let curDic = dic.find(cur => cur.index == index);
            // console.log(dic, curDic)
            if(curDic.activityType != activity.type) return resResult(STATUS.GM_ACTIVITY_NOT_FIT_GROUP_TYPE)
        }

        let activityIds = activityGroup.activities||[];
        if(activityIds.indexOf(activityId) == -1) activityIds.push(activityId);

        await ActivityGroupModel.setActivitiesToGroupData(groupId, activityIds, uid);
    
        let activityServers = pinus.app.getServersByType('activity');
        for(let server of activityServers) {
            pinus.app.rpc.activity.activityRemote.saveActivitiesToGroup.toServer(server.id, groupId, activityIds);
        }
        return resResult(STATUS.SUCCESS)
    }

    /**
     * 开启军团活动到拍卖行debug
     * @param msg 
     * @param session 
     */
    async setGuildActivityDebug(msg: { aid: number, day: number, startActivity: number, endActivity: number, startGuildAuction: number, endGuildAuction: number, startWorldAuction: number, endWorldAuction: number, startNextDay: number  }, session: BackendSession) {
        let { aid, day, startActivity = 0, endActivity = 0, startGuildAuction = 0, endGuildAuction = 0, startWorldAuction = 0, endWorldAuction = 0, startNextDay = 0 } = msg;
        if(timer) {
            clearTimeout(timer);
        }
        const uid = session.get('uid');
        if(aid == undefined || day == undefined ) {
            return resResult(STATUS.WRONG_PARMS);
        }
        if(aid == 0) {
            day = new Date().getDay();
        }
    
        // 设置字典
        let now = new Date();

        let startTimes = await pinus.app.rpc.guild.guildActivityRemote.setDicGuildActivity.broadcast(now.getTime(), aid, startActivity, endActivity);
        await pinus.app.rpc.systimer.systimerRemote.setDicGuildActivity.broadcast(now.getTime(), aid, startActivity, endActivity);
        await pinus.app.rpc.guild.guildActivityRemote.setDicAuctionTime.broadcast(startTimes[0], endActivity, startGuildAuction, endGuildAuction, startWorldAuction, endWorldAuction);
        await pinus.app.rpc.systimer.systimerRemote.setDicAuctionTime.broadcast(startTimes[0], endActivity, startGuildAuction, endGuildAuction, startWorldAuction, endWorldAuction);
        await pinus.app.rpc.guild.guildActivityRemote.setDay.broadcast(day);
        await pinus.app.rpc.systimer.systimerRemote.setDay.broadcast(day);
        await pinus.app.rpc.guild.guildActivityRemote.guildActivityEnd.broadcast(aid);

        // 清空旧数据
        if (day <= 2) {
            await GuildActivityCityModel.deleteMany({});
        }
        if(aid != 0) await delGuildActivityRank(aid);
        await GuildActivityRecordModel.updateTodayInfo({ status: 2 });

        // 开启定时器
        await pinus.app.rpc.systimer.systimerRemote.setAuctionSchedule.broadcast();
        await pinus.app.rpc.systimer.systimerRemote.setGuildActivitySchedule.broadcast();
        // 向客户端发送时间
        let time = <number>getTimeFunM().getTimeWithWeek(day, 20, 0, 0) - startActivity * 1000;
        pinus.app.rpc.guild.guildActivityRemote.setCurrentTime.broadcast(time);
        await pushCurrentTime(time);
        timer = setTimeout(async () => {
            let time = <number>getTimeFunM().getAfterDayWithHour(0);
            pinus.app.rpc.guild.guildActivityRemote.setCurrentTime.broadcast(time);
            await pushCurrentTime(time);
            let guilds = pinus.app.getServersByType('guild');
            let guild = getRandSingleEelm(guilds);
            await pinus.app.rpc.guild.guildActivityRemote.sendUngotDividend.toServer(guild.id);
        }, startActivity * 1000 + endActivity * 1000 + startGuildAuction * 1000 + endGuildAuction * 1000 + startWorldAuction * 1000 + endWorldAuction * 1000 + startNextDay * 1000)
        return resResult(STATUS.SUCCESS, {
            startActivity: startTimes[0],
            endActivity: startTimes[0] + endActivity * 1000,
            startGuildAuction: startTimes[0] + endActivity * 1000 + startGuildAuction * 1000,
            endGuildAuction: startTimes[0] + endActivity * 1000 + startGuildAuction * 1000 + endGuildAuction * 1000,
            startWorldAuction: startTimes[0] + endActivity * 1000 + startGuildAuction * 1000 + endGuildAuction * 1000 + startWorldAuction * 1000,
            endWorldAuction: startTimes[0] + endActivity * 1000 + startGuildAuction * 1000 + endGuildAuction * 1000 + startWorldAuction * 1000 + endWorldAuction * 1000,
            startNextDay: startTimes[0] + endActivity * 1000 + startGuildAuction * 1000 + endGuildAuction * 1000 + startWorldAuction * 1000 + endWorldAuction * 1000 + startNextDay * 1000,
        });
    }

    async cancelGuildActivityDebug(msg: {  }, session: BackendSession) {
        // 设置字典
        let now = new Date();
        if(timer) {
            clearTimeout(timer);
        }
        await pinus.app.rpc.guild.guildRemote.reloadResources.broadcast();
        await pinus.app.rpc.systimer.systimerRemote.reloadResources.broadcast();
        await pinus.app.rpc.guild.guildActivityRemote.setDay.broadcast(now.getDay());
        await pinus.app.rpc.systimer.systimerRemote.setDay.broadcast(now.getDay());

        // 开启定时器
        await pinus.app.rpc.systimer.systimerRemote.setAuctionSchedule.broadcast();
        await pinus.app.rpc.systimer.systimerRemote.setGuildActivitySchedule.broadcast();
        // 向客户端发送时间
        pinus.app.rpc.guild.guildActivityRemote.setCurrentTime.broadcast(now.getTime());
        await pushCurrentTime(now.getTime());
        return resResult(STATUS.SUCCESS);
    }
}