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, GMMailType } from '../../../db/GMMail';
import { delGuildActivityRank, getRoleOnlineInfo } from '../../../services/redisService';
import { SendMailFun } from '../../../services/mailService';
import { GM_MAIL_STATUS, GM_MAIL_TYPE, MAIL_TIME_TYPE, REF_CIRCLE_MAIL_TIME } from '../../../consts';
import { RewardInter } from '../../../pubUtils/interface';
import { MarqueeModel } from '../../../db/Marquee';
import { ServerlistModel } from '../../../db/Serverlist';
import { pushCurrentTime } from '../../../services/chatService';
import { checkActivityEditable, checkActivityGroupType, checkActivityGroupTypeWithId } 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, nowSeconds } from '../../../pubUtils/timeUtil';
import moment = require('moment');
import { sendUngotDividend } from '../../../services/auctionService';
import { taflush } from '../../../services/sdkService';
import { ActivityInRemote } from '../../../domain/activityField/activityField';
let timer: NodeJS.Timer;
export default function (app: Application) {
    return new GmHandler(app);
}

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

    async sendSingleMail(msg: { id: string, isPass: boolean }, session: BackendSession) {
        const uid: number = session.get('uid')
        let { id, isPass } = msg;
        let gmmail = await GMMailModel.getGmMailByIdAndType(id, GM_MAIL_TYPE.SINGLE, true);
        if(!gmmail) return resResult(STATUS.GM_MAIL_NOT_FOUND);
        return await this.sendMail(gmmail, isPass, uid);
    }

    async sendSingleMailTxt(msg: { id: string, isPass: boolean }, session: BackendSession) {
        const uid: number = session.get('uid')
        let { id, isPass } = msg;
        let gmmail = await GMMailModel.getGmMailByIdAndType(id, GM_MAIL_TYPE.SINGLE, false);
        if(!gmmail) return resResult(STATUS.GM_MAIL_NOT_FOUND);
        return await this.sendMail(gmmail, isPass, uid);
    }

    async sendServerMail(msg: { id: string, isPass: boolean }, session: BackendSession) {
        const uid: number = session.get('uid')
        let { id, isPass } = msg;
        let gmmail = await GMMailModel.getGmMailByIdAndType(id, GM_MAIL_TYPE.SERVER, true);
        if(!gmmail) return resResult(STATUS.GM_MAIL_NOT_FOUND);
        return await this.sendMail(gmmail, isPass, uid);
    }

    async sendServerMailTxt(msg: { id: string, isPass: boolean }, session: BackendSession) {
        const uid: number = session.get('uid')
        let { id, isPass } = msg;
        let gmmail = await GMMailModel.getGmMailByIdAndType(id, GM_MAIL_TYPE.SERVER, false);
        if(!gmmail) return resResult(STATUS.GM_MAIL_NOT_FOUND);
        return await this.sendMail(gmmail, isPass, uid);
    }

    //对接gm后台，下发邮件
    async sendMail(gmmail: GMMailType, isPass: boolean, uid: number) {
        let id = gmmail._id;
        let { receivers, mailType, status, timeType, startTime, circleHour, circleDay } = gmmail;
        if(status != GM_MAIL_STATUS.CREATE) {
            return resResult(STATUS.GM_MAIL_HAS_SENT);
        }
        let needSend = false;
        if(isPass) {
            if(timeType == MAIL_TIME_TYPE.CIRCLE) {
                let refTime = moment(moment().format(`YYYY-MM-DD ${REF_CIRCLE_MAIL_TIME}:00:00`)).unix();
                let sendTime = moment(moment().format('YYYY-MM-DD '+circleHour)).unix();
                if(sendTime < refTime) sendTime += 86400;
                let now = nowSeconds();
                if(refTime < now && sendTime > now) {
                    needSend = true;
                }
            } else {
                needSend = true;
            }
        }
        if(needSend) {
            let f = new SendMailFun();
            await f.setWithGmMail(gmmail);
    
            if (mailType == GM_MAIL_TYPE.SINGLE || mailType == GM_MAIL_TYPE.GROUP) {
                let roleIds = receivers.filter(cur => cur.env == this.app.get('env')).map(cur => cur.roleId);
                await f.sendToUsers(mailType, roleIds);
            } else {
                let serverIds = receivers.filter(cur => cur.env == this.app.get('env')).map(cur => cur.serverId);
                await f.sendToServer(serverIds);
            }
            // await f.saveRecord(uid);
        }
        let sendTime = '';
        if(isPass) {
            if(timeType == MAIL_TIME_TYPE.IMMEDIATE) {
                sendTime = moment().format('YYYY-MM-DD HH:mm:ss');
            } else if (timeType == MAIL_TIME_TYPE.DELAY) {
                sendTime = moment(startTime * 1000).format('YYYY-MM-DD HH:mm:ss');
            } else if (timeType == MAIL_TIME_TYPE.CIRCLE) {
                sendTime = (circleDay == 0?'每天': '每周'+circleDay) + ' ' + circleHour;
            }
        }
        await GMMailModel.updateMailById(id, { status: isPass? GM_MAIL_STATUS.PASS: GM_MAIL_STATUS.NOT_PASS, viewAt: new Date(), viewBy: uid, sendTime }, uid);
        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 updateActivity(msg: { activityId: number|string, groupId: number, beginTime: number, endTime: number, type: number, data: string, timeType: number, days: number, delayDay: number, interval: number }, session: BackendSession) {
        const { activityId, groupId, beginTime, endTime, type, data, timeType = 3, days = 0, delayDay = 0, interval = 0 } = 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 checkActivityGroupTypeWithId(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, timeType, days, delayDay, interval, uid);

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

        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);
        }
        await ActivityGroupModel.pullByActivityIds([activityId]);
        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 updateActivityGroup(msg: { groupId: number, groupName: string, serverIds: number[], activities: number[], type: number }, session: BackendSession) {
        const uid = session.get('uid');
        let { groupId, groupName, serverIds, activities, type } = msg;
        let groupTypeObj = await ActivityGroupTypeModel.findByGroupType(type);
        if(!groupTypeObj) return resResult(STATUS.GM_ACTIVITY_GROUP_TYPE_NOT_FOUND);

        {
            let result = await this.saveActivitiesToGroup(groupId, type, activities, uid);
            if(result.code != 0) return result;
        }
        {
            let result = await this.saveGroupToServer(groupId, serverIds, uid);
            if(result.code != 0) return result;
        }
        await ActivityGroupModel.updateGroup(groupId, {groupName, type}, uid);
        return resResult(STATUS.SUCCESS);
    }

    async saveGroupToServer(groupId: number, serverIds: number[], uid: number) {
        
        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(groupId: number, groupType: number, activityIds: number[], uid: number) {

        let activities = await ActivityModel.findActivityByIds(activityIds);
        let checkResult = await checkActivityGroupType(groupType, 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 checkActivityGroupTypeWithId(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.connector.connectorRemote.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);
    }

    async taflus() {
        taflush();
        pinus.app.rpc.activity.activityRemote.taflush.broadcast();
        pinus.app.rpc.battle.battleRemote.taflush.broadcast();
        pinus.app.rpc.chat.chatRemote.taflush.broadcast();
        pinus.app.rpc.connector.connectorRemote.taflush.broadcast();
        pinus.app.rpc.guild.guildRemote.taflush.broadcast();
        pinus.app.rpc.order.orderRemote.taflush.broadcast();
        pinus.app.rpc.role.roleRemote.taflush.broadcast();
        pinus.app.rpc.systimer.systimerRemote.taflush.broadcast();
    }
}