聊天问题修复优化

This commit is contained in:
2025-12-05 19:19:54 +08:00
parent b534344b25
commit 28041ddb09
6 changed files with 1322 additions and 382 deletions

View File

@@ -40,12 +40,14 @@
>
<view class="user u-flex u-row-right">
<view class="u-p-r-18">
<view class="color-000 u-line-1 text-right">{{ item.nick_name }}</view>
<view class="color-000 u-line-1 text-right">{{
item.nick_name
}}</view>
<view
class="u-m-t-14 msg u-p-l-30"
:class="['type' + item.msg_type]"
>
<chatItem :item="item"></chatItem>
<chatItem :item="item" @previewImage="previewImage"></chatItem>
</view>
</view>
<up-avatar
@@ -60,21 +62,26 @@
<template v-else>
<view class="shop u-flex">
<up-avatar
:src="shopInfo.logo"
:src="item.avatar"
size="122rpx"
shape="square"
bg-color="#fff"
></up-avatar>
<view class="u-p-l-18">
<view class="u-flex">
<view class="tag">商家</view>
<view class="color-000">{{ shopInfo.shopName }}</view>
<template v-if="item.is_shop == 1">
<view class="tag">商家</view>
<view class="color-000">{{ item.nick_name }}</view>
</template>
<template v-else>
<view class="color-000">{{ item.nick }}</view>
</template>
</view>
<view
class="u-m-t-14 msg"
:class="['type' + item.msg_type]"
>
<chatItem :item="item" @getCoupon="getCoupon"></chatItem>
<chatItem :item="item" @getCoupon="getCoupon" @previewImage="previewImage"></chatItem>
</view>
</view>
</view>
@@ -92,7 +99,11 @@
<!-- <view :style="bottomSlotHeight"></view> -->
<view class="bottom" :class="[showMoreBtn ? '' : 'safe-bottom']">
<view class="u-flex" style="padding: 14rpx 28rpx" v-if="groupInfo&&!groupInfo.is_mute">
<view
class="u-flex"
style="padding: 14rpx 28rpx"
v-if="groupInfo && !groupInfo.is_mute"
>
<!-- <input
type="text"
class="u-flex-1 u-m-r-52 iput"
@@ -112,12 +123,14 @@
<up-icon
name="plus-circle"
color="#666"
size="40rpx"
size="60rpx"
@click="showMoreBtnToggle"
v-else
></up-icon>
</view>
<view class="color-666 u-font-28 text-center u-m-t-28" v-else>商家已禁言</view>
<view class="color-666 u-font-28 text-center u-m-t-28" v-else
>商家已禁言</view
>
<view class="more-btn" v-if="showMoreBtn">
<view
v-for="(item, index) in moreBtns"
@@ -144,7 +157,7 @@
<view class="header-wrap">
<text class="t">退出群{{ "{" + groupInfo.name + "}" }}</text>
<view class="close" @click="popupShow = false">
<u-icon name="close" size="16" color="#666"></u-icon>
<u-icon name="close" size="20" color="#666"></u-icon>
</view>
</view>
<view class="u-p-40 text-center u-font-28 color-333 border-bottom"
@@ -168,10 +181,16 @@
</view>
</view>
</u-popup>
<!-- 预览图 -->
<xbSwiperPreview :visable="showPrveImg" :imgs="prveImgsList" @update:visable="showPrveImg = $event"></xbSwiperPreview>
</template>
<script setup>
import {
onReady,
onShow,
onReachBottom,
onLoad,
onPageScroll,
@@ -183,12 +202,18 @@ import {
nextTick,
reactive,
watch,
onUnmounted,
computed,
} from "vue";
import { useChatStore } from "@/stores/chat";
import * as chatApi from "@/http/php/chat";
import { uploadFile } from "@/common/api/upload.js";
import * as javaChatApi from "@/common/api/market/chat";
import xbSwiperPreview from '@/components/xb-swiper-preview/index.vue';
const showPrveImg = ref(false);
const prveImgsList = ref([]);
function exitGroup() {
chatApi
@@ -214,7 +239,8 @@ function getCoupon(item) {
javaChatApi
.couponGrant({
id: item.coupon.activity_id,
shopUserId: shopInfo.id,
// shopUserId: shopUserInfo.id,
shopId: groupInfo.value.shop_id,
userId: uni.cache.get("userInfo").id,
})
.then((res) => {
@@ -224,13 +250,12 @@ function getCoupon(item) {
icon: "none",
duration: 2000,
});
refresh()
}
});
}
function refresh() {
query.page=1;
function refresh() {
query.page = 1;
getMsgList();
}
const go = {
@@ -282,12 +307,7 @@ const modalData = reactive({
});
const chatStore = useChatStore();
chatStore.onReceiveMsg = (msg) => {
nextTick(() => {
scrollView.intoView = "msg-0";
});
};
chatStore.connectSocket();
const msg = ref("");
const shopInfo = uni.cache.get("shopInfo");
@@ -323,67 +343,222 @@ function moreBtnsClick(item, index) {
sendVideo();
}
}
function videoErrorCallback(e) {
console.error("视频播放失败", e);
}
function sendImg() {
uni.chooseImage({
count: 3, //默认9
sizeType: ["original", "compressed"], //可以指定是原图还是压缩图,默认二者都有
sourceType: ["album", "camera "],
success: async function (res) {
uni.showLoading({
title: "发送中",
});
console.log(res);
for (let i = 0; i < res.tempFiles.length; i++) {
const fileRes = await uploadFile(res.tempFiles[i]);
if (fileRes) {
sendMsg({
image_url: fileRes,
msg_type: 2,
});
} else {
// 通用相机权限校验函数参考openLocationAuth逻辑
async function checkCameraAuth() {
return new Promise((resolve, reject) => {
try {
// 1. 检查当前相机权限状态
uni.getSetting({
success: (settingRes) => {
const authSetting = settingRes.authSetting || {};
if (authSetting["scope.camera"]) {
// 2. 已授权:直接返回成功
resolve(true);
} else if (authSetting["scope.camera"] === undefined) {
// 3. 未请求过授权:发起授权请求
uni.authorize({
scope: "scope.camera",
success: () => {
// 授权成功
resolve(true);
},
fail: (authErr) => {
// 授权失败(用户拒绝)
console.error("相机授权失败:", authErr);
reject(false);
}
});
} else {
// 4. 已拒绝授权:提示用户去设置页开启
uni.showModal({
title: "开启相机权限",
content: "请允许“零点八零”使用您的相机,方便您拍摄图片/视频",
confirmText: "去设置",
cancelText: "取消",
success: (modalRes) => {
if (modalRes.confirm) {
// 跳转微信小程序授权设置页
uni.openSetting({
success: (openRes) => {
if (openRes.authSetting["scope.camera"]) {
// 用户在设置页开启授权
resolve(true);
} else {
// 用户未开启授权
reject(false);
}
},
fail: (openErr) => {
console.error("打开设置页失败:", openErr);
reject(false);
}
});
} else {
// 用户取消设置
reject(false);
}
},
fail: (modalErr) => {
console.error("弹窗失败:", modalErr);
reject(false);
}
});
}
},
fail: (settingErr) => {
console.error("获取权限设置失败:", settingErr);
reject(false);
}
}
},
});
} catch (err) {
console.error("相机权限校验异常:", err);
reject(false);
}
});
}
function sendVideo() {
uni.chooseVideo({
count: 1, //默认9
sizeType: ["original", "compressed"], //可以指定是原图还是压缩图,默认二者都有
sourceType: ["album", "camera "],
success: async function (res) {
uni.showLoading({
title: "发送中",
// 图片选择与发送(优化后)
async function sendImg() {
try {
// 1. 调用相机权限校验
const isAuth = await checkCameraAuth();
if (!isAuth) {
// 权限校验失败,终止流程
return;
}
// 2. 权限校验通过调用图片选择API
const res = await new Promise((resolve, reject) => {
uni.chooseImage({
count: 3,
sizeType: ["original", "compressed"],
sourceType: ["album", "camera"],
success: resolve,
fail: (err) => {
// 捕获选择失败(如用户取消选择)
if (err.errMsg && err.errMsg.includes("cancel")) {
// 用户主动取消,静默处理
reject(new Error("user cancel"));
} else {
// 其他错误(如系统异常)
reject(err);
}
}
});
console.log(res);
const fileRes = await uploadFile({ path: res.tempFilePath });
uni.hideLoading();
});
uni.showLoading({ title: "发送中" });
console.log("选择图片成功", res);
// 3. 批量上传图片
for (let i = 0; i < res.tempFiles.length; i++) {
const fileRes = await uploadFile(res.tempFiles[i]);
if (fileRes) {
sendMsg({
image_url: fileRes,
msg_type: 5,
});
} else {
uni.showToast({
title: "发送失败",
icon: "none",
msg_type: 2,
});
}
},
});
}
} catch (err) {
console.error("图片选择/发送失败", err);
// 仅处理非用户取消的错误
if (err.message !== "user cancel") {
uni.showToast({
title: "图片发送失败",
icon: "none",
duration: 2000
});
}
} finally {
uni.hideLoading();
}
}
// 视频选择与发送(优化后)
async function sendVideo() {
try {
// 1. 调用相机权限校验(与图片共用)
const isAuth = await checkCameraAuth();
if (!isAuth) {
// 权限校验失败,终止流程
return;
}
// 2. 权限校验通过调用视频选择API
const res = await new Promise((resolve, reject) => {
uni.chooseVideo({
count: 1,
sizeType: ["original", "compressed"],
sourceType: ["album", "camera"],
success: resolve,
fail: (err) => {
// 捕获选择失败(如用户取消选择)
if (err.errMsg && err.errMsg.includes("cancel")) {
// 用户主动取消,静默处理
reject(new Error("user cancel"));
} else {
// 其他错误(如系统异常)
reject(err);
}
}
});
});
uni.showLoading({ title: "发送中" });
console.log("选择视频成功", res);
// 3. 上传视频
const fileRes = await uploadFile({ path: res.tempFilePath });
if (fileRes) {
sendMsg({
image_url: fileRes,
msg_type: 5,
});
} else {
uni.showToast({
title: "视频发送失败",
icon: "none",
duration: 2000
});
}
} catch (err) {
console.error("视频选择/发送失败", err);
// 仅处理非用户取消的错误
if (err.message !== "user cancel") {
uni.showToast({
title: "视频发送失败",
icon: "none",
duration: 2000
});
}
} finally {
uni.hideLoading();
}
}
const groupInfo = ref({});
const handleReceiveMsg = (msg) => {
nextTick(() => {
scrollView.intoView = "msg-0";
});
};
// 注册消息回调
chatStore.registerReceiveMsgCallback(handleReceiveMsg);
async function init() {
const res = await chatApi.groupInfo({
group_id: options.group_id,
});
console.log(res);
groupInfo.value = res || {};
if (res) {
chatStore.shop_id = groupInfo.value.shop_id;
chatStore.connectSocket();
chatStore.init();
}
getMsgList();
}
const query = reactive({
@@ -395,7 +570,6 @@ async function getMsgList() {
if (isEnd.value) {
scrollView.refresherTriggered = false;
isLoading.value = false;
uni.showToast({ title: "没有更多了", icon: "none" });
return;
}
@@ -443,8 +617,9 @@ onLoad((opt) => {
Object.assign(options, opt);
init();
chatApi.messageMarkReadAll({
session_ids: options.session_id,
session_ids: options.group_id,
});
chatStore.group_id = options.group_id;
chatApi.groupMembers({ group_id: options.group_id }).then((res) => {
console.log(res);
membersRes.value = res;
@@ -474,7 +649,7 @@ function sendMsg(msg) {
content: msg.value,
image_url: "",
order_id: "",
session_id: "",
session_id: groupInfo.value.session_id || options.session_id,
...msg,
});
}
@@ -519,9 +694,9 @@ function confirmCoupon() {
}
function previewImage(url) {
uni.previewImage({
urls: [url],
});
prveImgsList.value = [url];
showPrveImg.value = true;
}
//是否到底了
@@ -556,6 +731,18 @@ const pageHeight = computed(() => {
}
return "";
});
onShow(() => {
// 页面显示时,检查连接状态
if (!chatStore.isConnect || !chatStore.socketTask) {
console.log("聊天页显示检查Socket连接");
chatStore.forceReconnect();
}
});
onUnmounted(() => {
// 组件卸载时,移除消息回调
chatStore.removeReceiveMsgCallback(handleReceiveMsg);
});
</script>
<style lang="scss" scoped>
.top {

View File

@@ -13,11 +13,10 @@
:src="item.image_url"
class="img"
mode="widthFix"
@click="previewVideo(item.video_url)"
></video>
<view class="" v-if="item.msg_type == 4">
<view>{{ item.coupon.title }}</view>
<view class="u-m-t-16 bg-f7 coupon u-flex" style="min-width: 500rpx;">
<view class="u-m-t-16 bg-f7 coupon u-flex u-col-stretch" style="min-width: 500rpx;">
<template v-if="item.coupon.type == 1">
<view class="left">
<view class="price">
@@ -77,11 +76,9 @@
</view>
</template>
<view class="right u-p-l-28">
<view class="right u-p-l-28 u-flex u-col-center">
<view class="u-font-32">{{ item.coupon.couponName }}</view>
<view class="u-font-24 color-999 u-m-t-8"
>有效期{{ returnTime(item.coupon) }}</view
>
</view>
</view>
<view class="u-flex u-row-center u-m-t-32">
@@ -99,14 +96,12 @@ const props = defineProps({
},
});
const emits = defineEmits(["getCoupon"]);
const emits = defineEmits(["getCoupon",'previewImage']);
function getCoupon() {
emits("getCoupon", props.item);
}
function previewImage(url) {
uni.previewImage({
urls: [url],
});
emits('previewImage',url)
}
function returnTime(coupon){
let startTime = coupon.useStartTime;
@@ -149,4 +144,7 @@ function returnTime(coupon){
color: #999;
}
}
.u-col-stretch{
align-items: stretch;
}
</style>

View File

@@ -2,7 +2,7 @@
<view class="min-page bg-f7 color-333 u-font-28">
<up-sticky>
<view class="top u-flex u-row-between u-col-center">
<view style="width: 420rpx;">
<view style="width: 420rpx">
<up-search
v-model="query.key"
placeholder="搜索群名称"
@@ -19,36 +19,37 @@
</up-sticky>
<view class="list">
<up-swipe-action>
<up-swipe-action-item
:options="options1"
v-for="(item, index) in list"
v-model:show="item.showOptions"
@click="optionsClick($event, item, index)"
:key="item.id"
>
<view class="item u-flex" @click="toDetail(item)">
<view class="u-flex avatar">
<up-avatar
size="118rpx"
:src="item.avatar"
shape="square"
round="8rpx"
></up-avatar>
<view class="bandage" v-if="item.unread_count > 0">{{
item.unread_count >= 99 ? "99" : item.unread_count
}}</view>
</view>
<view class="u-flex-1 u-flex u-row-between u-p-l-14">
<view style="max-width: 364rpx">
<view class="color-000 u-line-1">{{ item.name }}</view>
<view class="u-m-t-28 u-line-1 u-font-24 color-999"
>{{ item.msg }}</view
>
<template v-for="(item, index) in list" :key="item.id">
<up-swipe-action-item
:options="options1"
v-model:show="item.showOptions"
@click="optionsClick($event, item, index)"
>
<view class="item u-flex" @click="toDetail(item)">
<view class="u-flex avatar">
<up-avatar
size="118rpx"
:src="item.avatar"
shape="square"
round="8rpx"
></up-avatar>
<view class="bandage" v-if="item.unread_count > 0">{{
item.unread_count >= 99 ? "99" : item.unread_count
}}</view>
</view>
<view class="u-flex-1 u-flex u-row-between u-p-l-14">
<view style="max-width: 364rpx">
<view class="color-000 u-line-1">{{ item.name }}</view>
<view class="u-m-t-28 u-line-1 u-font-24 color-999">{{
item.msg
}}</view>
</view>
<view class="color-333 u-font-24">{{ item.send_time }}</view>
</view>
<view class="color-333 u-font-24">{{ item.send_time }}</view>
</view>
</view>
</up-swipe-action-item>
</up-swipe-action-item>
<view style="height: 16rpx" class="bg-f7"></view>
</template>
</up-swipe-action>
</view>
</view>
@@ -56,8 +57,64 @@
<script setup>
import * as chatApi from "@/http/php/chat";
import { ref, reactive } from "vue";
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useChatStore } from "@/stores/chat";
import dayjs from "dayjs";
const chatStore = useChatStore();
const originalOnReceiveMsg = chatStore.onReceiveMsg;
// 定义消息回调函数
const handleReceiveMsg = (msg) => {
// 先执行原始回调(如果有)
if (typeof originalOnReceiveMsg === "function") {
originalOnReceiveMsg(msg);
}
if (msg.operate_type == "receive_msg" && msg.chat_type == 2) {
const index = allList.value.findIndex((v) => v.group_id == msg.group_id);
if (index != -1) {
allList.value[index].unread_count += 1;
allList.value[index].msg = returnMsg(msg);
allList.value[index].send_time = msg.send_time;
allList.value[index].send_time_origin = msg.send_time_origin;
allList.value = listSort(allList.value);
}
const index1 = list.value.findIndex((v) => v.group_id == msg.group_id);
if (index1 != -1) {
list.value[index1].unread_count += 1;
list.value[index1].msg = returnMsg(msg);
list.value[index1].send_time = msg.send_time;
list.value[index1].send_time_origin = msg.send_time_origin;
list.value = listSort(list.value);
}
}
};
onMounted(() => {
chatStore.registerReceiveMsgCallback(handleReceiveMsg);
});
onUnmounted(() => {
// 移除消息回调,避免内存泄漏
chatStore.removeReceiveMsgCallback(handleReceiveMsg);
});
function returnMsg(msg) {
if (msg.msg_type == 1) {
return msg.nick + "" + msg.content;
}
if (msg.msg_type == 2) {
return msg.nick + "" + "[图片]";
}
if (msg.msg_type == 5) {
return msg.nick + "" + "[视频]";
}
if (msg.msg_type == 4) {
return msg.nick + "" + "[优惠券]";
}
}
chatStore.connectSocket();
// 使用 reactive 创建响应式对象
const options1 = reactive([
@@ -95,7 +152,7 @@ function optionsClick(e, item, index) {
}
const list = ref([]);
let allList = [];
let allList = ref([]);
const query = reactive({
key: "",
@@ -116,7 +173,7 @@ function throttle(fn, delay) {
//使用节流函数
const throttleSearch = throttle(search, 500);
function search() {
list.value = allList
const arr = allList.value
.filter((v) => v.name.includes(query.key.trim()))
.map((v) => {
return {
@@ -124,10 +181,20 @@ function search() {
showOptions: false,
};
});
list.value = listSort(arr);
}
function listSort(arr) {
return arr.sort((a, b) => {
return dayjs(b.send_time_origin).unix() - dayjs(a.send_time_origin).unix();
});
}
async function getList() {
const res = await chatApi.messageSessionList({});
allList = (res.list || []).filter((v) => !v.is_del);
const arr = (res.list || []).filter((v) => !v.is_del);
allList.value = listSort(arr);
search();
}
@@ -138,7 +205,7 @@ async function clearAllmsg() {
success: async (res) => {
if (res.confirm) {
const res = await chatApi.messageMarkReadAll({
session_ids: list.value.map((v) => v.session_id).join(","),
session_ids: list.value.map((v) => v.group_id).join(","),
});
if (res) {
uni.showToast({
@@ -173,6 +240,15 @@ function toDetail(item) {
const messageUnreadCount = ref(0);
onShow(() => {
getList();
// 检查连接状态,确保连接活跃
if (!chatStore.isConnect || !chatStore.socketTask) {
console.log("列表页显示检查Socket连接");
chatStore.forceReconnect();
} else {
chatStore.shop_id = "";
chatStore.init();
}
// 获取未读消息总数
chatApi.messageUnreadCount({}).then((res) => {
console.log(res);
@@ -192,13 +268,11 @@ onShow(() => {
}
.list {
padding: 36rpx 28rpx;
.item {
padding: 32rpx 28rpx;
background-color: #fff;
border-radius: 16rpx;
display: flex;
flex-direction: column;
gap: 16rpx;
.avatar {
position: relative;
.bandage {
@@ -220,4 +294,10 @@ onShow(() => {
}
}
}
:deep(.u-swipe-action-item__content) {
background-color: transparent;
}
:deep(.u-swipe-action-item) {
border-radius: 16rpx;
}
</style>