Files
5.24BuYu/Assets/MyGame/aa/UI/Home/Sub/UIHome_BY_ServicePanel.cs
T
2026-08-09 17:57:46 +08:00

216 lines
6.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Assets.MyGame.Scripts.Net;
using Assets.MyGame.Scripts.Net.APIResponses.Customer_SubClass;
using Assets.MyGame.Scripts.Net.WebResponses;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class UIHome_BY_ServicePanel : SubUIBase
{
public Toggle toggle_DefaultQuestion;
public Toggle toggle_YouChangeIChange;
public Toggle toggle_OnlineService;
[Header("客服")]
public TMP_InputField tMPInput_Text;
public DialogItem dialogGreenPrefab;
public DialogItem dialogOrangePrefab;
public Transform dialogPrefabParent;
public Button btn_SendText;
public string conversationId;
Dictionary<string, DialogItem> dic_dialogItems = new Dictionary<string, DialogItem>();
private bool _historyLoaded = false;
/// <summary>游客模式下生成的临时用户id(登录界面无user时使用)</summary>
private string _guestUserId;
// ==================== 生命周期 ====================
public override void Awake()
{
base.Awake();
btn_Close.onClick.RemoveAllListeners();
btn_Close.onClick.AddListener(() => uIManager.Close(UIPanel.ServicePanel));
// 游客模式(登录界面无user):生成临时身份
if (GameManager.Instance.user == null)
_guestUserId = Guid.NewGuid().ToString();
// 连接 Socket(仅收发实时消息,不再 StartConversation)
WebSocketManager.Instance.Connect(SocketType.customer, null);
toggle_DefaultQuestion.onValueChanged.AddListener((a) => { if (a) { } });
btn_SendText.onClick.AddListener(SendMessage);
}
protected override void OnShow(object args = null)
{
base.OnShow(args);
// 拉取历史消息(只拉一次)
if (!_historyLoaded)
{
_historyLoaded = true;
LoadHistory();
}
}
// ==================== 加载历史 ====================
private void LoadHistory()
{
// 清空旧气泡
for (int i = dialogPrefabParent.childCount - 1; i >= 0; i--)
Destroy(dialogPrefabParent.GetChild(i).gameObject);
dic_dialogItems.Clear();
APIRequestList.GetMyConversations(list =>
{
if (list != null && list.Count > 0)
{
var conv = list[0];
conversationId = conv.id;
// 显示历史消息(倒序逐一创建气泡)
if (conv.messages != null)
{
foreach (var msg in conv.messages)
{
AddHistoryBubble(msg);
}
ScrollToBottom();
}
}
});
}
private void AddHistoryBubble(CustomerMessageInfo msg)
{
if (msg.senderType == 1)
{
var green = Instantiate(dialogGreenPrefab, dialogPrefabParent);
green.showAvatar = true;
green.SetMessage(msg.content);
if (green.waitMessage != null) green.waitMessage.SetActive(false);
}
else
{
var orange = Instantiate(dialogOrangePrefab, dialogPrefabParent);
orange.showAvatar = false;
orange.SetMessage(msg.content);
if (orange.waitMessage != null) orange.waitMessage.SetActive(false);
}
}
// ==================== WebSocket 回调 ====================
public void OnMessageReceived(CustomerMessageReceived msg)
{
// 首次消息 → 获取 conversationId
if (string.IsNullOrEmpty(conversationId) && !string.IsNullOrEmpty(msg.conversationId))
conversationId = msg.conversationId;
if (msg.senderType == 1)
{
// 自己发的消息确认 → 隐藏等待图标
if (!string.IsNullOrEmpty(msg.guid) && dic_dialogItems.TryGetValue(msg.guid, out var item))
{
if (item.waitMessage != null)
item.waitMessage.SetActive(false);
}
}
else
{
// 客服新消息
var orange = Instantiate(dialogOrangePrefab, dialogPrefabParent);
orange.showAvatar = false;
orange.SetMessage(msg.content);
ScrollToBottom();
}
}
public void OnConversationStarted(CustomerConversationStartedResult result)
{
conversationId = result.conversation.id;
}
// ==================== 发送消息 ====================
private void SendMessage()
{
if (string.IsNullOrEmpty(tMPInput_Text.text.Trim()))
{
UIManager.Instance.ShowBoardError("不能发送空白");
return;
}
var content = tMPInput_Text.text.Trim();
tMPInput_Text.text = "";
// 绿色气泡
var green = Instantiate(dialogGreenPrefab, dialogPrefabParent);
green.showAvatar = true;
green.SetMessage(content);
ScrollToBottom();
string guid = Guid.NewGuid().ToString();
// 身份选择:有user用真实身份,无user(登录界面游客)用临时guid
string userId, userName;
if (GameManager.Instance.user != null)
{
userId = GameManager.Instance.user.id;
userName = GameManager.Instance.user.BaseInfo.userName;
}
else
{
userId = _guestUserId;
userName = _guestUserId.Substring(_guestUserId.Length - 6);
}
WebSocketSendList.Customer_SendMessage(
conversationId ?? "", // 首次发传空串,服务端自动创建
1,
userId,
userName,
null, 1, content, guid
);
dic_dialogItems[guid] = green;
}
private void OnDestroy()
{
if (!string.IsNullOrEmpty(conversationId))
WebSocketSendList.Customer_LeaveConversation(conversationId);
WebSocketManager.Instance.Close(SocketType.customer);
}
protected override void OnHide()
{
base.OnHide();
_historyLoaded = false;
}
// ==================== 滚动 ====================
public void ScrollToBottom()
{
StartCoroutine(ScrollBottomCoroutine());
}
IEnumerator ScrollBottomCoroutine()
{
yield return null;
yield return null;
yield return null;
var scrollRect = dialogPrefabParent.parent.parent.GetComponent<ScrollRect>();
scrollRect.verticalNormalizedPosition = 0;
Canvas.ForceUpdateCanvases();
scrollRect.verticalNormalizedPosition = 0;
}
}