import { Application, BackendSession, pinus } from 'pinus';
import { genCode, getRandSingleEelm, resResult } from '../../../pubUtils/util';
import { STATUS } from '../../../consts/statusCode';
import moment = require('moment');
import { CreateServerParam, UpdateRegionParams } from '../../../domain/backEndField/params';
import { RegionModel, RegionType } from '../../../db/Region';
import { gameData } from '../../../pubUtils/data';
import { Maintenance, ServerlistModel, ServerlistUpdate } from '../../../db/Serverlist';
import { nowSeconds } from '../../../pubUtils/timeUtil';
import { GM_MAIL_TYPE, MAIL_TIME_TYPE, REF_CIRCLE_MAIL_TIME } from '../../../consts';
import { SendMailFun } from '../../../services/mailService';
import { createNewServer, sendOpenServerMail } from '../../../services/gmService';
import { initAutoCreateServer, initMaintenance, stopMaintenance } from '../../../services/timeTaskService';
import { isNumber } from 'util';
import { MarqueeModel } from '../../../db/Marquee';
let timer: NodeJS.Timer;
export default function (app: Application) {
    return new GmHandler(app);
}

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

    // 保存大区配置
    async saveRegionConf(msg: UpdateRegionParams, session: BackendSession) {
        let params = new UpdateRegionParams(msg);
        let uid = session.get('uid');
        if(!params.checkParams()) return resResult(STATUS.WRONG_PARMS);
        let region: RegionType;
        if(params.id == 'new') {
            let update = params.getUpdateParam();
            region = await RegionModel.createNewRegion(update, uid);
        } else {
            let oldRegion = await RegionModel.findRegionById(params.id);
            if(!oldRegion) return resResult(STATUS.WRONG_PARMS);
            let update = params.getUpdateParam(oldRegion);
            region = await RegionModel.updateRegion(params.id, update, uid);
        }
        await pinus.app.rpc.systimer.systimerRemote.initAutoCreateServer.broadcast(region);
        
        return resResult(STATUS.SUCCESS);
    }

    // 手动开服
    async createNewServer(msg: CreateServerParam, session: BackendSession) {
        let params = new CreateServerParam(msg);
        let uid = session.get('uid');
        if(!params.checkParams()) return resResult(STATUS.WRONG_PARMS);

        console.log('*******', params);
        let curRegion = await RegionModel.findRegionByEnv(params.env);
        if(!curRegion) return resResult(STATUS.WRONG_PARMS);

        let { latestServer = 0 } = curRegion;
        let dicServerName = gameData.serverNames.get(latestServer + 1);
        if(!dicServerName) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        await createNewServer(curRegion, latestServer + 1, params, uid);
        return resResult(STATUS.SUCCESS);
    }

    // 开始维护
    async startMaintenance(msg: { id: number, startTime: number, endTime: number, hasNotify: boolean }, session: BackendSession) {
        const { id, startTime, endTime, hasNotify } = msg;
        if(!id || !isNumber(startTime) || !isNumber(endTime)) return resResult(STATUS.WRONG_PARMS);
        const uid = session.get('uid');
        let newMaintenance: Maintenance = { batchCode: genCode(10), startTime, endTime, hasNotify, isOpen: true }
        let server = await ServerlistModel.updateByServerId(id, { maintenance: newMaintenance });
        await pinus.app.rpc.systimer.systimerRemote.initMaintenance.broadcast([server]);

        return resResult(STATUS.SUCCESS,);
    }

    // 大区一起维护
    async startRegionMaintenance(msg: { startTime: number, endTime: number, hasNotify: boolean }, session: BackendSession) {
        const { startTime, endTime, hasNotify } = msg;
        if(!isNumber(startTime) || !isNumber(endTime)) return resResult(STATUS.WRONG_PARMS);
        const uid = session.get('uid');
        let newMaintenance: Maintenance = { batchCode: genCode(10), startTime, endTime, hasNotify, isOpen: true }
        let servers = await ServerlistModel.findByEnv(this.app.get('env'));
        console.log('*********servers', servers)
        await ServerlistModel.updateByServerIds(servers.map(server => server.id), { maintenance: newMaintenance });
        await pinus.app.rpc.systimer.systimerRemote.initMaintenance.broadcast(servers);

        return resResult(STATUS.SUCCESS,);
    }

    // 提前结束维护
    async stopMaintenance(msg: { id: number }, session: BackendSession) {
        const { id } = msg;
        const uid = session.get('uid');
        let server = await ServerlistModel.findByServerId(id);
        let maintenance = server.maintenance;
        if(maintenance) {
            // 更新serverlist上的status
            await ServerlistModel.updateByServerId(server.id, { 'maintenance.isOpen': false } as ServerlistUpdate);
            
            // console.log('&&&', server, server.id)
            await pinus.app.rpc.systimer.systimerRemote.stopMaintenance.broadcast(maintenance.batchCode, [server.id]);
        }

        return resResult(STATUS.SUCCESS,);
    }

    async sendMarquee(msg: { code: string }, session: BackendSession) {
        const { code } = msg;
        let marquee = await MarqueeModel.findByCode(code);
        if(!marquee) return resResult(STATUS.DB_DATA_NOT_FOUND);

        await MarqueeModel.updateData(code, { isEnable: true });
        let result = await this.app.rpc.systimer.systimerRemote.setMarquee.broadcast(marquee);
        if (!result) return resResult(STATUS.GM_MARQUEE_ERR);
        return resResult(STATUS.SUCCESS);
    }

    async cancelMarquee(msg: { code: string }, session: BackendSession) {
        const { code } = msg;
        await MarqueeModel.updateData(code, { isEnable: false });
        let result = await this.app.rpc.systimer.systimerRemote.cancelMarquee.broadcast(code);
        if (!result) return resResult(STATUS.GM_MARQUEE_CANCEL_ERR);
        return resResult(STATUS.SUCCESS);
    }
}