import { _decorator, Component, Node } from 'cc';
import { Prefab } from 'cc';
import ChatData from '../../../data/ChatData';
import { instantiate } from 'cc';
import { Label } from 'cc';
import { EditBox } from 'cc';
import { GUI } from '../../UIConfig';
import { GUIChatMessage, GUIChatMessageDTO } from '../../../consts/GActionType';
import { Widget } from 'cc';
import JScrollExceedHide from '../../../../../extensions/ngame/assets/ngame/util/components/JScrollExceedHide';
import { JNGLayerBase } from '../../../components/JNComponent';
import { app } from '../../../App';
const { ccclass, property } = _decorator;

@ccclass('MainChatView')
export class MainChatView extends JNGLayerBase {

    @property(Node)
    content:Node; //聊天内容

    @property(Prefab)
    chatPrefab:Prefab; //聊天预制体

    @property(EditBox)
    inputMessage:EditBox; //聊天输入框

    onJNLoad(data?: any): void {

        super.onJNLoad(data);
        this.onInitUpdate();

        //监听消息
        ChatData.getIns().on(this.onMessage.bind(this),this);

    }

    onJNClose(): void {
        super.onJNClose();
        ChatData.getIns().off(this.onMessage.bind(this),this);
    }

    //初始化聊天显示
    onInitUpdate(){

        this.content.destroyAllChildren();
        let messages = ChatData.getIns().datas;

        messages.forEach(message => {
            this.onMessage(message);
        })

    }

    //发送消息
    onClickSendMessage(){

        if(!this.inputMessage.string){
            app.layer.Open(GUI.Tips,{text:"请输入内容"})
            return;
        }

        ChatData.getIns().onSend({
            message:this.inputMessage.string
        });

    }

    //接受到消息
    onMessage(info:GUIChatMessageDTO){

        //插入数据
        let node = instantiate(this.chatPrefab);

        node.getComponent(Label).string = `${info.playerName} : ${info.message.message}`;
        this.content.addChild(node);
        this.scheduleOnce(() => {
            this.getComponentInChildren(JScrollExceedHide).onUpdate();
        })

    }
    
}


