
using FGUI.ZM_Common_01;
using UnityEngine;
using FairyGUI;
using IgnoreOPS;
using Newtonsoft.Json;
using System.Linq;
using FGUI.LG_AIchat;
using DG.Tweening;
using System.Collections.Generic;
using System;
using System.Linq.Expressions;

namespace RedHotRoast
{
    public class ChatUI : BaseUI
    {
        private ChatUICtrl ctrl;
        private ChatModel model;
        private FGUI.LG_AIchat.com_chat ui;

        public ChatUI(ChatUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.ChatUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "LG_AIchat";
            uiInfo.assetName = "com_chat";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

        #region 生命周期
        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.ChatModel) as ChatModel;
        }

        protected override void OnClose()
        {
            ChatHelper.chat_red_list[chat_index] = false;
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshRedDot);
            UnityManager.ShezhiACT(true);
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.LG_AIchat.com_chat;
        }

        protected override void OnOpenBefore(object args)
        {
            // ChatHelper.GetMessage(1);
            //  ChatHelper.ResetMessage(1);
            if (args != null) chat_index = (int)args;
            if (DataMgr.ChatData.Value == null)
            {
                DataMgr.ChatData.Value = new List<ChatItem>();
            }

            if (Screen.safeArea.y != 0)
            {
                ui.group_.y += Screen.safeArea.y - 15;
            }
            Debug.Log(JsonConvert.SerializeObject(DataMgr.ChatData.Value));
            ui.btn_close.SetClick(CtrlCloseUI);
            ui.type.selectedIndex = ui.btn_tophead.type.selectedIndex = chat_index;
            InitView();
            ui.btn_photo.SetClick(() =>
            {
                GameHelper.ShowTips("launching_soon", true);
            });
            ui.btn_video.SetClick(() =>
            {
                GameHelper.ShowTips("launching_soon", true);
            });
            UnityManager.ShezhiACT(false);
        }
        public static bool IsSameDay(long timestamp)
        {
            // 假设时间戳是 Unix 时间戳（秒），如果是毫秒记得除以 1000
            DateTime inputTime = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;
            DateTime now = DateTimeOffset.FromUnixTimeSeconds(GameHelper.GetNowTime()).DateTime;

            // 比较年月日是否一致
            return inputTime.Date == now.Date;
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }
        #endregion

        #region 消息
        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.LiveChange, addNewItem);
            GameDispatcher.Instance.AddListener(GameMsg.AddChatNum, setChatNum);
            GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, SetTopCurr);
        }
        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.LiveChange, addNewItem);
            GameDispatcher.Instance.RemoveListener(GameMsg.AddChatNum, setChatNum);
            GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr);
        }
        public void SetTopCurr(object a = null)
        {
            Debug.Log("??????????");
            var btn_gold = ui.btn_gold as com_gold;
            btn_gold.text_gold.text = $"{DataMgr.Coin.Value:N0}";



        }
        private void addNewItem(object a = null)
        {
            _ChatItem = DataMgr.ChatData.Value.FirstOrDefault(c => c.role == ChatType.GetType(chat_index));
            if (_ChatItem.content_list.Count > list_count)
            {
                if (have_inputani && ChatHelper.unshow_message[chat_index] <= 0)
                {
                    ui.list_.RemoveChildAt(list_count);
                    have_inputani = false;
                }
                // else if (have_inputani && ChatHelper.unshow_message[chat_index] > 0)
                // {

                // }
                for (int i = list_count; i < _ChatItem.content_list.Count; i++)
                {
                    if (_ChatItem.content_list[i].type == 1)
                    {
                        item_chatText_left com_msg = (item_chatText_left)UIPackage.CreateObject("LG_AIchat", "item_chatText_left");
                        com_msg.text_content.text = _ChatItem.content_list[i].text_content;
                        // if (chat_index == 0) com_msg.head.url = "ui://tksc66j2ljeg27";
                        // else if (chat_index == 1) com_msg.head.url = "ui://tksc66j2ljeg25";
                        // else if (chat_index == 2) com_msg.head.url = "ui://tksc66j2ljeg20";
                        com_msg.type.selectedIndex = chat_index;
                        if (ChatHelper.unshow_message[chat_index] <= 0 || (!have_inputani)) ui.list_.AddChild(com_msg);
                        else ui.list_.AddChildAt(com_msg, ui.list_.numChildren - 1);
                    }
                }

                // if (ChatHelper.unshow_message[chat_index] > 0)
                // {
                //     item_chatText_left com_msg_ = (item_chatText_left)UIPackage.CreateObject("LG_AIchat", "item_chatText_left");
                //     com_msg_.t0.Play(-1, 0, null);
                //     if (chat_index == 0) com_msg_.head.url = "ui://tksc66j2ljeg27";
                //     else if (chat_index == 1) com_msg_.head.url = "ui://tksc66j2ljeg25";
                //     else if (chat_index == 2) com_msg_.head.url = "ui://tksc66j2ljeg20";
                //     ui.list_.AddChild(com_msg_);
                //     have_inputani = true;
                // }

                list_count = _ChatItem.content_list.Count;
                ui.list_.ScrollToView(list_count - 1);
            }
        }
        private void setChatNum(object a = null)
        {

            if (DataMgr.ChatFreeNumber.Value == 0 && DataMgr.ChatNumber.Value == 0)
            {
                // ui.have_free.selectedIndex = 1;
                // ui.text_remainfreeNum.text = "Free:" + DataMgr.ChatFreeNumber.Value;
                // ui.btn_send.state.selectedIndex = 0;
                ui.btn_send.title = Language.GetContent("get_more");
            }
            else
            {
                // ui.have_free.selectedIndex = 0;
                // ui.text_remainNum.text = ":" + DataMgr.ChatNumber.Value;
                // ui.btn_send.state.selectedIndex = 1;
                ui.btn_send.title = Language.GetContent("Send");
            }
            if (DataMgr.ChatFreeNumber.Value > 0)
            {
                ui.btn_send.text_remainNum.text = Language.GetContentParams("Free_1", DataMgr.ChatFreeNumber.Value);
            }
            else
            {
                ui.btn_send.text_remainNum.text = DataMgr.ChatNumber.Value.ToString();
            }
            // if (DataMgr.ChatFreeNumber.Value <= 0 && DataMgr.ChatNumber.Value <= 0) ui.btn_send.title = "Get More";
            // else ui.btn_send.title = "Send";

        }

        #endregion
        private ChatItem _ChatItem;
        private int chat_index = 2;
        private int list_count = 0;
        //初始化页面逻辑
        private void InitView()
        {
            Debug.Log(DataMgr.ChatData.Value);
            SetTopCurr();
            _ChatItem = DataMgr.ChatData.Value.FirstOrDefault(c => c.role == ChatType.GetType(chat_index));
            Debug.Log(JsonConvert.SerializeObject(_ChatItem));
            if (DataMgr.ChatRecoverDays.Value != DateTime.Now.Day)
            {
                DataMgr.ChatFreeNumber.Value = GameHelper.GetCommonModel().FreeMessages;
                DataMgr.ChatRecoverDays.Value = DateTime.Now.Day;
            }
            setChatNum();
            if (_ChatItem != null)
            {
                _ChatItem.content_list.RemoveAll(item => !IsSameDay(item.chat_time));
                if (_ChatItem.content_list.Count > 100)
                {
                    _ChatItem.content_list.RemoveRange(0, _ChatItem.content_list.Count - 100);
                }
                DataMgr.ChatData.Save();
                list_count = _ChatItem.content_list.Count;
                Debug.Log(list_count + "..................");
                for (int i = 0; i < _ChatItem.content_list.Count; i++)
                {
                    if (_ChatItem.content_list[i].type == 0)
                    {
                        item_chatText_right com_msg = (item_chatText_right)UIPackage.CreateObject("LG_AIchat", "item_chatText_right");
                        com_msg.text_content.text = _ChatItem.content_list[i].text_content;
                        GameHelper.SetSelfAvatar(com_msg.btn_head.load_avatar, DataMgr.PlayerAvatarId.Value);
                        ui.list_.AddChild(com_msg);
                    }
                    else
                    {
                        item_chatText_left com_msg = (item_chatText_left)UIPackage.CreateObject("LG_AIchat", "item_chatText_left");
                        com_msg.text_content.text = _ChatItem.content_list[i].text_content;
                        // if (chat_index == 0) com_msg.head.url = "ui://tksc66j2ljeg27";
                        // else if (chat_index == 1) com_msg.head.url = "ui://tksc66j2ljeg25";
                        // else if (chat_index == 2) com_msg.head.url = "ui://tksc66j2ljeg20";
                        com_msg.type.selectedIndex = chat_index;
                        ui.list_.AddChild(com_msg);
                    }
                }
                if (list_count > 3) ui.list_.ScrollToView(list_count - 1);
                ChatHelper.CheckReply();
            }
            else
            {
                ChatHelper.GetMessage(chat_index);
                DOVirtual.DelayedCall(1, () =>
                {
                    ChatHelper.CheckReply();
                });
            }

            // DataMgr.ChatData.Value = "";
            ui.btn_send.SetClick(() =>
            {
                if (DataMgr.ChatFreeNumber.Value > 0 || DataMgr.ChatNumber.Value > 0)
                {
                    if (ui.input_message.text.IsNullOrWhiteSpace())
                    {
                        GameHelper.ShowTips("message_tips", true);
                        return;
                    }
                    Debug.Log(ui.input_message.text.Length);
                    if (ui.input_message.text.Length > 200)
                    {
                        GameHelper.ShowTips("character_limit", true);
                        return;
                    }
                    if (DataMgr.ChatFreeNumber.Value > 0)
                    {
                        DataMgr.ChatFreeNumber.Value--;
                    }
                    else DataMgr.ChatNumber.Value--;
                    setChatNum();
                    ChatHelper.SendMessage(chat_index, ui.input_message.text);

                    list_count++;
                    DOVirtual.DelayedCall(4, () =>
                    {
                        Debug.Log("重复一次");
                        ChatHelper.CheckReply();
                    });

                    if (have_inputani)
                    {
                        ui.list_.RemoveChildAt(ui.list_.numItems - 1);

                    }


                    item_chatText_right com_msg = (item_chatText_right)UIPackage.CreateObject("LG_AIchat", "item_chatText_right");
                    com_msg.text_content.text = ui.input_message.text;
                    GameHelper.SetSelfAvatar(com_msg.btn_head.load_avatar, DataMgr.PlayerAvatarId.Value);
                    ui.list_.AddChild(com_msg);

                    item_chatText_left com_msg_ = (item_chatText_left)UIPackage.CreateObject("LG_AIchat", "item_chatText_left");
                    com_msg_.t0.Play(-1, 0, null);
                    // if (chat_index == 0) com_msg_.head.url = "ui://tksc66j2ljeg27";
                    // else if (chat_index == 1) com_msg_.head.url = "ui://tksc66j2ljeg25";
                    // else if (chat_index == 2) com_msg_.head.url = "ui://tksc66j2ljeg20";
                    com_msg_.type.selectedIndex = chat_index;
                    ui.list_.AddChild(com_msg_);

                    have_inputani = true;


                    if (_ChatItem == null)
                    {
                        _ChatItem = new ChatItem()
                        {
                            role = ChatType.GetType(chat_index),
                            content_list = new List<ChatText>(),
                        };
                        DataMgr.ChatData.Value.Add(_ChatItem);
                    }
                    _ChatItem.content_list.Add(new ChatText()
                    {
                        type = 0,
                        text_content = ui.input_message.text,
                        chat_time = GameHelper.GetNowTime(),
                    });
                    DataMgr.ChatData.Save();
                    ui.input_message.text = "";
                    ui.list_.ScrollToView(ui.list_.numItems - 1);

                    DOVirtual.DelayedCall(1, () =>
                    {
                        ChatHelper.CheckReply();
                    });

                }
                else
                {
                    uiCtrlDispatcher.Dispatch(UICtrlMsg.ChatNumberUI_Open);
                }

            });

        }
        private bool have_inputani = false;

    }
}