// 聊天模块
import Gamecfg from "../../../common/gameCfg";
import { gameMethod } from "../../../common/gameMethod";
import { ChatHistory, ChatHistoryPram, ChatSend, ChatSendPram } from "../../../common/Xyc";
import { ChannelType, ChatInfo, SevBack, SevBackType } from "../../../common/Xys";
import { RedUtil } from "../../../frameWork/fgui/RedUtil";
import EventMng from "../../../manager/EventMng";
import { ChatType, ResChatSend } from "../../../shared/chat/PtlChatSend";
import GameMath from "../../../utils/GameMath";
import { ChatEvent } from "../../const/EventConst";
import GameDataCenter from "../../GameDataCenter";
import { ChatModelData } from "./ChatModelData";

export default class ChatModel extends ChatModelData {
	// chatCd: number = 0 // 下一次可聊天的时间戳
	private _lastId: Map<ChannelType, number> = new Map();
	private _chatNewId: Map<ChannelType, number> = new Map(); // 最新的一条消息ID
	chatCd: number = 0;
	refreshCd: number = 0;
	readonly getChatNum: number = 10; //每次获取的，聊天信息的数量

	readonly historyMinCd: number = 3;
	readonly sendChatMinCd: number = 3;

	curChannel: ChannelType;

	get lastId() {
		return this._lastId.get(this.curChannel);
	}

	set lastId(id: number) {
		this._lastId.set(this.curChannel, id);
	}

	get chatNewId() {
		return this._chatNewId.get(this.curChannel);
	}

	set chatNewId(id: number) {
		this._chatNewId.set(this.curChannel, id);
	}

	constructor() {
		super("chat");
	}

	onRegister(): void {
        GameDataCenter.gameServer.ListenMsg("chat/server/ChatNew_s", this.onItemChange, this);
    }

	onItemChange(res: ResChatSend) {
		this.chatInfo = res;
	}
	// 发送聊天信息
	async sendChat(chatType: ChatType, str: string, cb: Function = () => { }) {
		let ret = await GameDataCenter.gameServer.ReqApi("chat/ChatSend", {
			type: chatType,
			str: str
		});
		if (ret?.res) {
			cb(ret.res);
		}
	}

	checkHistory() {
		let list = Object.keys(GameDataCenter.sevBack.chat?.[this.curChannel]?.a ?? {});
		return list.length < this.getChatNum;
	}

	/**获得聊天同服 */
	getServerList() {
		let sid = GameDataCenter.user?.userInfo?.sid;
		let serverList = GameDataCenter.login.playerInfo?.qufuList;
		let heid = serverList?.[sid]?.heid;
		let list: string[] = []
		for (let key in serverList) {
			if (serverList[key].heid == heid) {
				list.push(serverList[key].sid);
			}
		}

		return list;
	}

	showTime(time: number): string {
		let dhms = this.getHM(time);
		let tTime: string = `${GameMath.addZero(dhms.h)}:${GameMath.addZero(dhms.m)}`;
		return tTime;
	}

	getHM(time: number) {
		if (time.toString().length == 10) {
			time = time * 1000
		}
		var date = new Date(time);
		var hour = date.getHours()
		var minute = date.getMinutes()
		return { h: hour, m: minute };
	}
}
