import { STATUS } from './../../../consts/statusCode';
import { EquipModel } from './../../../db/Equip';
import { RoleModel, RoleType } from './../../../db/Role';
import { UserModel } from '../../../db/User';
import { GMUserModel } from '../../../db/GMUser';
import { Application, HandlerService, pinus, } from 'pinus';
import { FrontendSession } from 'pinus';
import { HeroModel } from './../../../db/Hero';
import { genCode, generateStr, resResult } from '../../../pubUtils/util';
import { COM_BTL_QUALITY, HERO_SELECT, DEBUG_MAGIC_WORD, REDIS_KEY, TASK_TYPE, ENTERY_ROLE_PICK, COUNTER, DEFAULT_LV } from '../../../consts';
import { getAp } from '../../../services/actionPointService';
import { ItemModel } from '../../../db/Item';
import { SkinModel } from '../../../db/Skin';
// import { loginRefresh } from '../../../services/playerEventService';
import { nowSeconds, getZeroPoint } from '../../../pubUtils/timeUtil';
import { rmRoleFromQueue, roleLeave, getRoleOnlineInfo, roleLogin } from '../../../services/redisService';

import { addRoleToGuildChannel, addRoleToSysChannel, addRoleToWorldChannel, leaveGuildAuctionChannel, leaveGuildChannel, leaveSysChannel, leaveWorldAuctionChannel, leaveWorldChannel, recentGuildMsgs, recentPrivateChatInfos, recentSysMsgs, recentWorldMsgs } from '../../../services/chatService';
import { reportOneOnline, savePlayTime } from '../../../services/authenticateService';
import { Rank } from '../../../services/rankService';
import { checkTaskWithRole, } from '../../../services/taskService';
import { pushData, everydayRefresh, kickUser } from '../../../services/connectorService';
import { pick } from 'lodash';
import { setComBtlOnUserLeave } from '../../../services/comBattleService';
import Counter from '../../../db/Counter';
import { getExpByLv } from '../../../pubUtils/data';

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

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

    /**
     * New client entry chat server.
     *
     * @param  {Object}   msg     request message
     * @param  {Object}   session current session object
     */
    async enter(msg: { token: string, serverId: number }, session: FrontendSession) {
        console.log('****** entry before', Date.now());
        let self = this;
        let serverId = msg.serverId;

        let user = await UserModel.findUserByToken(msg.token);
        if (!user) {
            console.log('user token not found');
            return resResult(STATUS.TOKEN_ERR);
        }

        let role = await RoleModel.findByUidAndSetTime(user.uid, serverId, null, true);
        if (!role) {
            return resResult(STATUS.ROLE_NOT_FOUND);
        }

        let connect = await getRoleOnlineInfo(role.roleId);

        if (connect.isOnline) { // 多地登陆踢下线
            if (connect.sid = self.app.getServerId()) {
                await kickUser(self.app, role.roleId);
            } else {
                await self.app.rpc.connector.connectorRemote.remoteLogin.toServer(connect.sid, role.roleId);
            }
        }
        let serverName = this.app.getServerId();
        await roleLogin(role.roleId, user.userCode, serverName, user.pkgName); // 保存在线用户
        await this.addSession(role, session);

        // put user into channel
        // console.log(JSON.stringify(self.app.rpc.battle))
        // await self.app.rpc.battle.battleRemote.add.route(session)(role.roleId, self.app.get('serverId'), role.serverId, true);
        addRoleToSysChannel(role.roleId, self.app.get('serverId'), role.serverId);
        addRoleToWorldChannel(role.roleId, self.app.get('serverId'), role.serverId);
        await self.app.rpc.chat.chatRemote.addWorldChannel.route(session)(role.roleId, serverId, self.app.get('serverId'));
        let heros = await HeroModel.findByRole(role.roleId, [], HERO_SELECT.ENTRY, true);
        let equips = await EquipModel.findbyRole(role.roleId);
        let items = await ItemModel.findbyRole(role.roleId);
        let skins = await SkinModel.findbyRole(role.roleId);
        // if (role.hasInit) await loginRefresh(role.roleId); // pvp在getData的时候会做初始，这里先注掉
        reportOneOnline(role.roleId, user.userCode, self.app.get('serverId'), true, user);

        let r = new Rank(REDIS_KEY.HERO_NUM_RANK, { serverId });
        r.setRankWithRoleInfo(role.roleId, role.heroNum, role.heroNumUpdatedAt, role);
        let r2 = new Rank(REDIS_KEY.SUM_CE_RANK, { serverId });
        r2.setRankWithRoleInfo(role.roleId, role.lv, role.updatedAt.getTime(), role);

        // 任务
        checkTaskWithRole(serverId, role.roleId, self.app.get('serverId'), TASK_TYPE.LOGIN_SUM, role);
        checkTaskWithRole(serverId, role.roleId, self.app.get('serverId'), TASK_TYPE.LOGIN_SERIES, role);
        // 推送数据
        if (role.hasInit) pushData(role, session);

        role['heros'] = heros;
        role['equips'] = equips;
        role['consumeGoods'] = items;
        role['skins'] = skins;
        let apJson = await getAp(role.roleId, role.lv);
        role['apJson'] = apJson;

        if (!role.showLineup) role.showLineup = role.topLineup.map(cur => cur.hid);
        role.heads = role.heads.filter(cur => cur.status);
        role.frames = role.frames.filter(cur => cur.status);
        role.spines = role.spines.filter(cur => cur.status);

        if (role.hasGuild) {
            addRoleToGuildChannel(role.roleId, self.app.get('serverId'), role.guildCode);
        }

        let todayZeroPoint = getZeroPoint();
        role['todayZeroPoint'] = todayZeroPoint;

        console.log('****** entry after', Date.now());
        return resResult(STATUS.SUCCESS, { role: pick(role, ENTERY_ROLE_PICK) });
    }


    async addSession(role: RoleType, session: FrontendSession) {
        const self = this;
        await session.abind(role.roleId);
        session.set('userid', role.userInfo.uid);
        session.set('uid', role.roleId);
        session.set('roleId', role.roleId);
        let updatedMailAt = role.updatedMailAt ? role.updatedMailAt : 0;
        session.set('updatedMailAt', updatedMailAt);
        session.set('roleName', role.roleName);
        session.set('eventStatus', role.eventStatus);
        session.set('sid', self.app.get('serverId'));
        session.set('serverId', role.serverId);
        session.set('guildCode', role.guildCode);
        session.push('userid', () => { });
        session.push('sid', () => { });
        session.push('roleId', () => { });
        session.push('roleName', () => { });
        session.push('eventStatus', () => { });
        session.push('serverId', () => { });
        session.push('updatedMailAt', () => { });
        session.push('guildCode', () => { });
        // console.log(role.guildCode)
        // session.push('rid', function (err) {
        //     if (err) {
        //         console.error('set rid for session service failed! error is : %j', err.stack);
        //     }
        // });
        session.on('closed', this.onUserLeave.bind(this));
    }


    /**
     * 每天5点时的刷新数据.
     *
     * @param  {Object}   msg     request message
     * @param  {Object}   session current session object
     */
    async refresh(msg: {}, session: FrontendSession) {
        let self = this;
        let roleId = session.get('roleId');

        let role = await RoleModel.findByRoleId(roleId, null, true, true);
        if (!role) {
            return resResult(STATUS.ROLE_NOT_FOUND);
        }

        let { serverId } = role;
        // 任务
        checkTaskWithRole(serverId, role.roleId, self.app.get('serverId'), TASK_TYPE.LOGIN_SUM, role);
        checkTaskWithRole(serverId, role.roleId, self.app.get('serverId'), TASK_TYPE.LOGIN_SERIES, role);
        // 推送数据
        pushData(role, session, 'refresh');

        let todayZeroPoint = getZeroPoint();
        return resResult(STATUS.SUCCESS, { todayZeroPoint });
    }


    /**
     * User log out handler
     *
     * @param {Object} app current application
     * @param {Object} session current session object
     *
     */
    async onUserLeave(session: FrontendSession, reason: string) {
        if (!session || !session.uid) {
            return;
        }

        let roleId = session.get('roleId');
        let sid = session.get('sid');
        let serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        const teamCode: string = session.get('teamCode');
        roleLeave(roleId).then(function (roleInfo) {
            if (roleInfo.isOnline) {
                savePlayTime(roleInfo.userCode);
            }
        });
        rmRoleFromQueue(roleId, sid, COM_BTL_QUALITY, null); // 删除redis中寻宝的匹配记录
        let channelService = this.app.get('channelService');
        let channel = channelService.getChannel(roleId, true);
        channel.leave(roleId, sid);
        this.app.rpc.chat.chatRemote.kickWorldChannel.route(session, true)(roleId, sid, serverId);
        await leaveSysChannel(roleId, sid, serverId);
        await leaveWorldChannel(roleId, sid, serverId);
        await leaveGuildChannel(roleId, sid, guildCode);
        await leaveGuildAuctionChannel(roleId, sid, guildCode);
        await leaveWorldAuctionChannel(roleId, sid, serverId);
        RoleModel.updateRoleInfo(roleId, { quitTime: nowSeconds() });
        if(teamCode) { // 如果有寻宝中的队伍，那么等于战败
            setComBtlOnUserLeave(roleId, teamCode)
        }
    }


    /**
     * New client entry chat server.
     *
     * @param  {Object}   msg     request message
     * @param  {Object}   session current session object
     */
    async gmEnter(msg: { token: string, serverId: number }, session: FrontendSession) {

        let self = this;

        let user = await GMUserModel.getGmAccountByToken(msg.token);
        if (!user) {
            console.log('user token not found');
            return resResult(STATUS.TOKEN_ERR);
        }

        // console.log(self.app.get('serverId'));
        await session.abind(user.username);
        session.set('uid', user.uid);
        session.set('roleId', user.username);
        session.set('roleName', user.name);
        session.set('eventStatus', 0);
        session.set('sid', self.app.get('serverId'));
        session.push('sid', () => { });
        session.push('roleId', () => { });
        session.push('roleName', () => { });
        session.push('eventStatus', () => { });
        // session.push('rid', function (err) {
        //     if (err) {
        //         console.error('set rid for session service failed! error is : %j', err.stack);
        //     }
        // });
        session.on('closed', this.onGmUserLeave.bind(this));

        // put user into channel
        return resResult(STATUS.SUCCESS, {
            serverType: this.app.get('serverName')
        });
    }

    /**
     * User log out handler
     *
     * @param {Object} app current application
     * @param {Object} session current session object
     *
     */
    async onGmUserLeave(session: FrontendSession, reason: string) {
        if (!session || !session.uid) {
            return;
        }
    }

    /**
     * ! 仅用于测试
     * @description 测试接口，用于查询和返回 token
     * @param {{ tel: string, magicWord: string }} msg 要查询的手机号；需要验证的密码
     * @param {FrontendSession} session
     * @returns
     * @memberof EntryHandler
     */
    async debugQueryToken(msg: { tel: string, magicWord: string }, session: FrontendSession) {
        const { tel, magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const token = await UserModel.findTokenByTel(tel);
        return resResult(STATUS.SUCCESS, { token });
    }

    /**
     * ! 仅用于测试
     * @description 测试接口，用于查询和返回 token
     * @param {{ seqId: string, magicWord: string }} msg 要查询的手机号；需要验证的密码
     * @param {FrontendSession} session
     * @returns
     * @memberof EntryHandler
     */
    async debugQueryTokenById(msg: { uid: number, magicWord: string }, session: FrontendSession) {
        const { uid, magicWord } = msg;
        console.log('debugQueryTokenById msg:', msg);
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        const user = await UserModel.findTokenByUid(uid);
        console.log('debugQueryTokenById got user:', user);
        return resResult(STATUS.SUCCESS, { user });
    }

    async debugQueryTokenByTel(msg: { tel: string, magicWord: string, serverId: number }, session: FrontendSession) {
        const { tel, magicWord, serverId } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        let token = await UserModel.findTokenByTel(tel);
        if(!token) {
                    // 用户注册登录
            token = generateStr(256);
            let user = await UserModel.createOrUpdate(false, tel, token, 'pc', ' ', pinus.app.get('env'), '', '');
            const roleId = genCode(10);
            const code = genCode(6);
            const seqId = await Counter.getNewCounter(COUNTER.ROLE) || -1;
    
            await RoleModel.createRole(user.uid, serverId, { roleId, code, roleName: roleId, seqId, lv: DEFAULT_LV, exp: (getExpByLv(DEFAULT_LV - 1) || { sum: 0 }).sum || 0 });
        }
        console.log('debugQueryTokenByTel got user:', token);
        return resResult(STATUS.SUCCESS, { user: token });
    }

    async debugPushRefToOnlineUsers(msg: { magicWord: string }, session: FrontendSession) {
        const { magicWord } = msg;
        console.log('debugQueryTokenById msg:', msg);
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        await everydayRefresh();

        return resResult(STATUS.SUCCESS);
    }
}