CustomerService.vue 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <template>
  2. <HeaderNav headerText="商家昵称" headerRouter="/" />
  3. <div class="customer-service">
  4. <!-- 聊天消息区域 -->
  5. <div class="chat-box" ref="chatBoxRef">
  6. <div
  7. v-for="msg in msgList"
  8. :key="msg.id"
  9. class="msg-item"
  10. :class="{ self: msg.isSelf }">
  11. <img class="avatar" :src="msg.isSelf ? userAvatar : serviceAvatar" />
  12. <div class="msg-content">
  13. <!-- 文本消息 -->
  14. <div v-if="msg.messageType === 'text'" class="text">
  15. {{ msg.text }}
  16. </div>
  17. <!-- 图片消息 -->
  18. <img
  19. v-else-if="msg.messageType === 'image'"
  20. class="img-msg"
  21. :src="msg.text"
  22. alt="图片消息" />
  23. <!-- 时间/已读显示 -->
  24. <div class="time">
  25. <!-- 最后一条我的消息 已读 -->
  26. <template v-if="msg.isSelf && msg.read && msg.id === lastSelfMsgId">
  27. 已读
  28. </template>
  29. <!-- 其他显示时间 -->
  30. <template v-else>
  31. {{ formatTime(msg.time) }}
  32. </template>
  33. </div>
  34. </div>
  35. </div>
  36. </div>
  37. <!-- 底部输入栏 -->
  38. <div class="bottom-bar">
  39. <input
  40. v-model="inputValue"
  41. type="text"
  42. placeholder="请输入内容..."
  43. class="input pf500 fs14" />
  44. <img
  45. src="@/assets/icon/asset/send.png"
  46. class="send-btn"
  47. @click="sendMessage"
  48. alt="" />
  49. </div>
  50. </div>
  51. </template>
  52. <script setup>
  53. import { ref, onMounted, nextTick, onUnmounted, computed } from "vue";
  54. import { useRoute } from "vue-router";
  55. import { GetOTCChatDetails } from "@/api/otc";
  56. import HeaderNav from "@/views/index/components/HeaderNav.vue";
  57. const route = useRoute();
  58. // 用户头像(自己)
  59. const userAvatar = require("@/assets/img/asset/head-img.png");
  60. // 商家头像(对方)
  61. const serviceAvatar = require("@/assets/img/index/user/default-head.png");
  62. let ws = null;
  63. const msgList = ref([]);
  64. const inputValue = ref("");
  65. const chatBoxRef = ref(null);
  66. // 自动滚动到底部
  67. function scrollToBottom() {
  68. nextTick(() => {
  69. if (chatBoxRef.value) {
  70. chatBoxRef.value.scrollTop = chatBoxRef.value.scrollHeight;
  71. }
  72. });
  73. }
  74. // 格式化时间
  75. function formatTime(t) {
  76. if (!t) return "";
  77. const d = new Date(t);
  78. return `${d.getHours().toString().padStart(2, "0")}:${d
  79. .getMinutes()
  80. .toString()
  81. .padStart(2, "0")}`;
  82. }
  83. // 最后一条自己的消息 ID(用于显示“已读”)
  84. const lastSelfMsgId = computed(() => {
  85. const selfMsgs = msgList.value.filter((m) => m.isSelf);
  86. return selfMsgs.length ? selfMsgs[selfMsgs.length - 1].id : null;
  87. });
  88. async function loadHistory() {
  89. const res = await GetOTCChatDetails(route.params.chatId);
  90. msgList.value = res.list.map((item) => ({
  91. id: item.id,
  92. text: item.context,
  93. time: item.update_time,
  94. read: item.is_read,
  95. isSelf: !item.is_otc, // true=右侧(自己),false=左侧(商家)
  96. messageType: "text",
  97. }));
  98. scrollToBottom();
  99. }
  100. /* ==========================================================
  101. ② 发送消息
  102. ========================================================== */
  103. function sendMessage() {
  104. if (!inputValue.value.trim()) return;
  105. const msg = {
  106. id: Date.now(),
  107. otc: route.params.otcId,
  108. text: inputValue.value,
  109. time: Date.now(),
  110. isSelf: true,
  111. type: "chat",
  112. messageType: "text",
  113. read: false,
  114. };
  115. msgList.value.push(msg);
  116. // WebSocket 发送
  117. if (ws && ws.readyState === WebSocket.OPEN) {
  118. ws.send(JSON.stringify(msg));
  119. }
  120. inputValue.value = "";
  121. scrollToBottom();
  122. }
  123. /* ==========================================================
  124. ③ WebSocket 处理
  125. ========================================================== */
  126. const initWebSocket = () => {
  127. const token = localStorage.getItem("token");
  128. ws = new WebSocket(`wss://test2.66linknow.com/ws/custom_chat/?token=${token}`);
  129. ws.onopen = () => {
  130. console.log("WebSocket 已连接");
  131. };
  132. ws.onmessage = (e) => {
  133. let data = {};
  134. try {
  135. data = JSON.parse(e.data);
  136. } catch {
  137. return;
  138. }
  139. console.log("收到数据:", data);
  140. /* --- 已读处理 --- */
  141. if (data.message?.type === "read") {
  142. const lastSelf = [...msgList.value].reverse().find((m) => m.isSelf && !m.read);
  143. if (lastSelf) lastSelf.read = true;
  144. return;
  145. }
  146. /* --- 普通消息 --- */
  147. const text = data.message?.text || "";
  148. const isImage = /^https?:\/\/.+\.(png|jpg|jpeg|gif|webp)(\?.*)?$/i.test(text);
  149. msgList.value.push({
  150. id: Date.now(),
  151. text,
  152. time: Date.now(),
  153. isSelf: false,
  154. messageType: isImage ? "image" : "text",
  155. read: false,
  156. });
  157. scrollToBottom();
  158. };
  159. ws.onerror = () => {
  160. console.error("WebSocket 错误");
  161. };
  162. ws.onclose = () => {
  163. console.log("WebSocket 已关闭");
  164. };
  165. };
  166. onMounted(() => {
  167. loadHistory(); // ← 添加历史记录加载
  168. initWebSocket(); // ← WebSocket 初始化
  169. });
  170. onUnmounted(() => {
  171. ws && ws.close();
  172. });
  173. </script>
  174. <style lang="less" scoped>
  175. .customer-service {
  176. display: flex;
  177. flex-direction: column;
  178. padding-top: 50px;
  179. width: 375px;
  180. height: 100vh;
  181. box-sizing: border-box;
  182. }
  183. /* 聊天内容区域 */
  184. .chat-box {
  185. flex: 1;
  186. overflow-y: auto;
  187. padding: 12px;
  188. background: #f5f5f5;
  189. }
  190. .msg-item {
  191. display: flex;
  192. margin-bottom: 12px;
  193. &.self {
  194. flex-direction: row-reverse;
  195. .msg-content {
  196. align-items: flex-end;
  197. }
  198. .text {
  199. background: #4dabf7;
  200. color: #fff;
  201. }
  202. }
  203. }
  204. .avatar {
  205. width: 40px;
  206. height: 40px;
  207. border-radius: 50%;
  208. }
  209. .msg-content {
  210. display: flex;
  211. flex-direction: column;
  212. margin: 0 10px;
  213. .text {
  214. max-width: 70vw;
  215. background: #ffffff;
  216. padding: 8px 12px;
  217. border-radius: 8px;
  218. line-height: 1.5;
  219. font-size: 14px;
  220. }
  221. .img-msg {
  222. max-width: 180px;
  223. max-height: 400px;
  224. display: block;
  225. border-radius: 10px;
  226. }
  227. .time {
  228. margin-top: 4px;
  229. font-size: 12px;
  230. color: #999;
  231. }
  232. }
  233. /* 底部栏 */
  234. .bottom-bar {
  235. display: flex;
  236. flex-direction: row;
  237. justify-content: space-between;
  238. align-items: center;
  239. padding-left: 16px;
  240. padding-right: 16px;
  241. border-top: 1px solid #ddd;
  242. height: 70px;
  243. box-sizing: border-box;
  244. .input {
  245. padding-left: 12px;
  246. width: 283px;
  247. height: 48px;
  248. border: 1px solid #ddd;
  249. border-radius: 40px;
  250. outline: none;
  251. box-sizing: border-box;
  252. }
  253. .send-btn {
  254. margin-left: 12px;
  255. width: 48px;
  256. height: 48px;
  257. }
  258. }
  259. </style>