using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using Newtonsoft.Json;
using SGModule.Common.Helper;
using SGModule.NetKit;
using RedHotRoast;
using UnityEngine;


public class ChatSendClass
{
    [JsonProperty("role")] public string role;
    [JsonProperty("content")] public string content;
    [JsonProperty("style")] public string style;
}
public class ChatetClass
{
    [JsonProperty("role")] public string role;
    [JsonProperty("style")] public string style;
}
public class ChatHelper : MonoBehaviour
{

    public static void SendMessage(int type, string text)
    {

        ChatSendClass respData = new ChatSendClass
        {
            role = ChatType.GetType(type),
            content = text,
            style = ChatType.GetStyle(type)
        };

        NetKit.Instance.Post<object>("chat/sendAiMsg", respData, response =>
        {
            if (response.IsSuccess)
            {
                Debug.Log(JsonConvert.SerializeObject(response.Data));
            }
        });
    }

    public static void GetMessage(int type)
    {

        ChatetClass respData = new ChatetClass
        {
            role = ChatType.GetType(type),
            style = ChatType.GetStyle(type),
        };

        NetKit.Instance.Post<object>("chat/initiateAi", respData, response =>
        {
            if (response.IsSuccess)
            {
                Debug.Log(JsonConvert.SerializeObject(response.Data));
            }
        });
    }
    public static void ResetMessage(int type)
    {

        var respData = new
        {
            role = ChatType.GetType(type),
        };

        NetKit.Instance.Post<object>("chat/resetAiChat", respData, response =>
        {
            if (response.IsSuccess)
            {
                Debug.Log(JsonConvert.SerializeObject(response.Data));
            }
        });
    }
    public static void CheckReply()
    {
        if (DataMgr.ChatData.Value == null)
        {
            DataMgr.ChatData.Value = new List<ChatItem>();
        }
        if (pollingCoroutine == null) pollingCoroutine = CrazyAsyKit.StartCoroutine(CheckReplyLoop());
        // NetKit.Instance.Post<List<ReplyItem>>("chat/checkAiReply", null, response =>
        // {
        //     if (response.IsSuccess)
        //     {
        //         Debug.Log(response.Data);
        //         Debug.Log(JsonConvert.SerializeObject(response.Data));
        //         Debug.Log(JsonConvert.SerializeObject(response.Data[0]));
        //         Debug.Log(JsonConvert.SerializeObject(response.Data[0].list));
        //         Debug.Log(response.Data[0].list == null);
        //         Debug.Log(response.Data[0].list.Count);
        //         for (int i = 0; i < response.Data.Count; i++)
        //         {
        //             if (response.Data[i].list.Count > 0)
        //             {
        //                 for (int j = 0; j < response.Data[i].list.Count; j++)
        //                 {
        //                     Debug.Log(response.Data[i].list[j].content);
        //                     ChatItem item = DataMgr.ChatData.Value.FirstOrDefault(c => c.role == response.Data[i].role);
        //                     Debug.Log(JsonConvert.SerializeObject(item));
        //                     if (item == null)
        //                     {
        //                         item = new ChatItem()
        //                         {
        //                             role = response.Data[i].role,
        //                             content_list = new List<ChatText>(),
        //                             chat_time = GameHelper.GetNowTime(),
        //                         };
        //                         DataMgr.ChatData.Value.Add(item);
        //                     }
        //                     item.content_list.Add(new ChatText()
        //                     {
        //                         type = 1,
        //                         text_content = response.Data[i].list[j].content
        //                     });
        //                 }
        //             }

        //         }
        //         Debug.Log(JsonConvert.SerializeObject(DataMgr.ChatData.Value));
        //         DataMgr.ChatData.Save();
        //     }
        // });

    }
    // public static List<ChatItem> Chat_Object;

    // public static List<ChatItem> GetChatObject()
    // {
    //     if (DataMgr.ChatData.Value == null)
    //     {
    //         DataMgr.ChatData.Value = new List<ChatItem>();
    //     }
    //     return DataMgr.ChatData.Value;

    // }
    private static Coroutine pollingCoroutine;
    private static IEnumerator CheckReplyLoop()
    {
        while (true)
        {
            bool shouldStop = true;

            NetKit.Instance.Post<List<ReplyItem>>("chat/checkAiReply", null, response =>
            {
                if (response.IsSuccess)
                {
                    //Debug.Log(response.Data);
                    Debug.Log(JsonConvert.SerializeObject(response.Data));
                    // Debug.Log(JsonConvert.SerializeObject(response.Data[0]));
                    // Debug.Log(JsonConvert.SerializeObject(response.Data[0].list));
                    // Debug.Log(response.Data[0].list == null);
                    // Debug.Log(response.Data[0].list.Count);

                    for (int i = 0; i < response.Data.Count; i++)
                    {

                        if (response.Data[i].list.Count > 0)
                        {
                            for (int j = 0; j < response.Data[i].list.Count; j++)
                            {
                                string content = response.Data[i].list[j].content;
                                string role = response.Data[i].role;

                                ChatItem item = DataMgr.ChatData.Value.FirstOrDefault(c => c.role == role);
                                if (item == null)
                                {
                                    item = new ChatItem()
                                    {
                                        role = role,
                                        content_list = new List<ChatText>(),
                                    };
                                    DataMgr.ChatData.Value.Add(item); // ⚠️ 注意：要在这里添加，否则闭包中可能重复添加
                                }
                                unshow_message[ChatType.GetIndex(role)]++;
                                int delay_time = j * 2; // 每条消息延迟2秒

                                DOVirtual.DelayedCall(delay_time, () =>
                                {
                                    item.content_list.Add(new ChatText()
                                    {
                                        type = 1,
                                        text_content = content,
                                        chat_time = GameHelper.GetNowTime(),
                                    });
                                    chat_red_list[ChatType.GetIndex(role)] = true;
                                    unshow_message[ChatType.GetIndex(role)]--;
                                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshRedDot);
                                    GameDispatcher.Instance.Dispatch(GameMsg.LiveChange);
                                });
                            }


                        }
                        if (response.Data[i].status == "pending") shouldStop = false;

                    }
                    //  Debug.Log(JsonConvert.SerializeObject(DataMgr.ChatData.Value));
                    DataMgr.ChatData.Save();
                }
            });

            if (UIManager.Instance.IsExistUI(UIConst.ChatUI)) yield return new WaitForSeconds(3f);
            else yield return new WaitForSeconds(10f);

            // 等待回调完成 + 间隔一秒
            if (shouldStop)
            {
                Debug.Log("检测到 status 为 done，停止轮询");
                // StopCoroutine("CheckReplyLoop");
                // pollingCoroutine = null;
                pollingCoroutine = null;
                yield break;
            }

        }
    }
    public static List<int> unshow_message = new List<int> { 0, 0, 0 };
    public static List<bool> chat_red_list = new List<bool> { false, false, false };
    public static bool GetChatRed(int index = -1)
    {
        if (index >= 0)
        {
            return chat_red_list[index];
        }
        else
        {
            for (int i = 0; i < chat_red_list.Count; i++)
            {
                if (chat_red_list[i]) return true;
            }
            return false;
        }
    }

}

public class ChatItem
{
    [JsonProperty("role")] public string role;
    [JsonProperty("content_list")] public List<ChatText> content_list;

}
public class ChatText
{
    [JsonProperty("type")] public int type;
    [JsonProperty("text_content")] public string text_content;
    [JsonProperty("chat_time")] public long chat_time;
}
public class ReplyItem
{
    [JsonProperty("role")] public string role { get; set; }
    [JsonProperty("list")] public List<ReplyContent> list { get; set; }
    [JsonProperty("status")] public string status { get; set; }
}

public class ReplyContent
{
    [JsonProperty("type")] public int type { get; set; }
    [JsonProperty("content")] public string content { get; set; }
}

public static class ChatType
{
    public const string Ainsley = "Ainsley";
    public const string Lacey = "Lacey";
    public const string Beatrice = "Beatrice";
    public const string Taffy = "Taffy";
    public const string Quinn = "Quinn";

    public static string GetType(int type)
    {
        switch (type)
        {
            case 0:
                return Ainsley;
            case 1:
                return Lacey;
            case 2:
                return Beatrice;
            case 3:
                return Taffy;
            case 4:
                return Quinn;
        }
        return Ainsley;
    }
    public static string GetStyle(int type)
    {
        switch (type)
        {
            case 0:
                return "playful";
            case 1:
                return "nurturing";
            case 2:
                return "confident";
            case 3:
                return "affectionate";
            case 4:
                return "reserved";
        }
        return "playful";
    }
    public static int GetIndex(string type)
    {
        switch (type)
        {
            case Ainsley:
                return 0;
            case Lacey:
                return 1;
            case Beatrice:
                return 2;
            case Taffy:
                return 3;
            case Quinn:
                return 4;
        }
        return 0;
    }
}


