合并初始化

This commit is contained in:
落日晚风
2023-12-11 09:24:16 +08:00
parent 376376b875
commit c5b1f3ac93
533 changed files with 82087 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
<template>
<view class="goods ss-flex">
<image class="image" :src="sheep.$url.cdn(goodsData.image)" mode="aspectFill"> </image>
<view class="ss-flex-1">
<view class="title ss-line-2">
{{ goodsData.title }}
</view>
<view v-if="goodsData.subtitle" class="subtitle ss-line-1">
{{ goodsData.subtitle }}
</view>
<view class="price ss-m-t-8">
{{ isArray(goodsData.price) ? goodsData.price[0] : goodsData.price }}
</view>
</view>
</view>
</template>
<script setup>
import sheep from '@/sheep';
import { isArray } from 'lodash';
const props = defineProps({
goodsData: {
type: Object,
default: {},
},
});
</script>
<style lang="scss" scoped>
.goods {
background: #fff;
padding: 20rpx;
border-radius: 12rpx;
.image {
width: 116rpx;
height: 116rpx;
flex-shrink: 0;
margin-right: 20rpx;
}
.title {
height: 64rpx;
line-height: 32rpx;
font-size: 26rpx;
font-weight: 500;
color: #333;
}
.subtitle {
font-size: 24rpx;
font-weight: 400;
color: #999;
}
.price {
font-size: 26rpx;
font-weight: 500;
color: #ff3000;
}
}
</style>
+122
View File
@@ -0,0 +1,122 @@
<template>
<view class="order">
<view class="top ss-flex ss-row-between">
<span>{{ orderData.order_sn }}</span>
<span>{{ orderData.create_time.split(' ')[1] }}</span>
</view>
<template v-if="from != 'msg'">
<view class="bottom ss-flex" v-for="item in orderData.items" :key="item">
<image class="image" :src="sheep.$url.cdn(item.goods_image)" mode="aspectFill"> </image>
<view class="ss-flex-1">
<view class="title ss-line-2">
{{ item.goods_title }}
</view>
<view v-if="item.goods_num" class="num ss-m-b-10"> 数量{{ item.goods_num }} </view>
<view class="ss-flex ss-row-between ss-m-t-8">
<span class="price">{{ item.goods_price }}</span>
<span class="status">{{ orderData.status_text }}</span>
</view>
</view>
</view>
</template>
<template v-else>
<view class="bottom ss-flex" v-for="item in [orderData.items[0]]" :key="item">
<image class="image" :src="sheep.$url.cdn(item.goods_image)" mode="aspectFill"> </image>
<view class="ss-flex-1">
<view class="title title-1 ss-line-1">
{{ item.goods_title }}
</view>
<view class="order-total ss-flex ss-row-between ss-m-t-8">
<span>{{ orderData.items.length }}件商品</span>
<span>合计 ¥{{ orderData.pay_fee }}</span>
</view>
<view class="ss-flex ss-row-right ss-m-t-8">
<span class="status">{{ orderData.status_text }}</span>
</view>
</view>
</view>
</template>
</view>
</template>
<script setup>
import sheep from '@/sheep';
const props = defineProps({
from: String,
orderData: {
type: Object,
default: {},
},
});
</script>
<style lang="scss" scoped>
.order {
background: #fff;
padding: 20rpx;
border-radius: 12rpx;
.top {
line-height: 40rpx;
font-size: 24rpx;
font-weight: 400;
color: #999;
border-bottom: 1px solid rgba(223, 223, 223, 0.5);
margin-bottom: 20rpx;
}
.bottom {
margin-bottom: 20rpx;
&:last-of-type {
margin-bottom: 0;
}
.image {
flex-shrink: 0;
width: 116rpx;
height: 116rpx;
margin-right: 20rpx;
}
.title {
height: 64rpx;
line-height: 32rpx;
font-size: 26rpx;
font-weight: 500;
color: #333;
&.title-1 {
height: 32rpx;
width: 300rpx;
}
}
.num {
font-size: 24rpx;
font-weight: 400;
color: #999;
}
.price {
font-size: 26rpx;
font-weight: 500;
color: #ff3000;
}
.status {
font-size: 24rpx;
font-weight: 500;
color: var(--ui-BG-Main);
}
.order-total {
line-height: 28rpx;
font-size: 24rpx;
font-weight: 400;
color: #999;
}
}
}
</style>
+151
View File
@@ -0,0 +1,151 @@
<template>
<su-popup :show="show" showClose round="10" backgroundColor="#eee" @close="emits('close')">
<view class="select-popup">
<view class="title">
<span>{{ mode == 'goods' ? '我的浏览' : '我的订单' }}</span>
</view>
<scroll-view
class="scroll-box"
scroll-y="true"
:scroll-with-animation="true"
:show-scrollbar="false"
@scrolltolower="loadmore"
>
<view
class="item"
v-for="item in state.pagination.data"
:key="item"
@tap="emits('select', { type: mode, data: item })"
>
<template v-if="mode == 'goods'">
<GoodsItem :goodsData="item.goods" />
</template>
<template v-if="mode == 'order'">
<OrderItem :orderData="item" />
</template>
</view>
<uni-load-more :status="state.loadStatus" :content-text="{ contentdown: '上拉加载更多' }" />
</scroll-view>
</view>
</su-popup>
</template>
<script setup>
import { reactive, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import _ from 'lodash';
import GoodsItem from './goods.vue';
import OrderItem from './order.vue';
const emits = defineEmits(['select', 'close']);
const props = defineProps({
mode: {
type: String,
default: 'goods',
},
show: {
type: Boolean,
default: false,
},
});
watch(
() => props.mode,
() => {
state.pagination.data = [];
if (props.mode) {
getList(state.pagination.page);
}
},
);
const state = reactive({
loadStatus: '',
pagination: {
data: [],
current_page: 1,
total: 1,
last_page: 1,
},
});
async function getList(page, list_rows = 5) {
state.loadStatus = 'loading';
const res =
props.mode == 'goods'
? await sheep.$api.user.view.list({
page,
list_rows,
})
: await sheep.$api.order.list({
page,
list_rows,
});
let orderList = _.concat(state.pagination.data, res.data.data);
state.pagination = {
...res.data,
data: orderList,
};
if (state.pagination.current_page < state.pagination.last_page) {
state.loadStatus = 'more';
} else {
state.loadStatus = 'noMore';
}
}
function loadmore() {
if (state.loadStatus !== 'noMore') {
getList(state.pagination.current_page + 1);
}
}
</script>
<style lang="scss" scoped>
.select-popup {
max-height: 600rpx;
.title {
height: 100rpx;
line-height: 100rpx;
padding: 0 26rpx;
background: #fff;
border-radius: 20rpx 20rpx 0 0;
span {
font-size: 32rpx;
position: relative;
&::after {
content: '';
display: block;
width: 100%;
height: 2px;
z-index: 1;
position: absolute;
left: 0;
bottom: -15px;
background: var(--ui-BG-Main);
pointer-events: none;
}
}
}
.scroll-box {
height: 500rpx;
}
.item {
background: #fff;
margin: 26rpx 26rpx 0;
border-radius: 20rpx;
:deep() {
.image {
width: 140rpx;
height: 140rpx;
}
}
}
}
</style>
+58
View File
@@ -0,0 +1,58 @@
export const emojiList = [
{ name: '[笑掉牙]', file: 'xiaodiaoya.png' },
{ name: '[可爱]', file: 'keai.png' },
{ name: '[冷酷]', file: 'lengku.png' },
{ name: '[闭嘴]', file: 'bizui.png' },
{ name: '[生气]', file: 'shengqi.png' },
{ name: '[惊恐]', file: 'jingkong.png' },
{ name: '[瞌睡]', file: 'keshui.png' },
{ name: '[大笑]', file: 'daxiao.png' },
{ name: '[爱心]', file: 'aixin.png' },
{ name: '[坏笑]', file: 'huaixiao.png' },
{ name: '[飞吻]', file: 'feiwen.png' },
{ name: '[疑问]', file: 'yiwen.png' },
{ name: '[开心]', file: 'kaixin.png' },
{ name: '[发呆]', file: 'fadai.png' },
{ name: '[流泪]', file: 'liulei.png' },
{ name: '[汗颜]', file: 'hanyan.png' },
{ name: '[惊悚]', file: 'jingshu.png' },
{ name: '[困~]', file: 'kun.png' },
{ name: '[心碎]', file: 'xinsui.png' },
{ name: '[天使]', file: 'tianshi.png' },
{ name: '[晕]', file: 'yun.png' },
{ name: '[啊]', file: 'a.png' },
{ name: '[愤怒]', file: 'fennu.png' },
{ name: '[睡着]', file: 'shuizhuo.png' },
{ name: '[面无表情]', file: 'mianwubiaoqing.png' },
{ name: '[难过]', file: 'nanguo.png' },
{ name: '[犯困]', file: 'fankun.png' },
{ name: '[好吃]', file: 'haochi.png' },
{ name: '[呕吐]', file: 'outu.png' },
{ name: '[龇牙]', file: 'ziya.png' },
{ name: '[懵比]', file: 'mengbi.png' },
{ name: '[白眼]', file: 'baiyan.png' },
{ name: '[饿死]', file: 'esi.png' },
{ name: '[凶]', file: 'xiong.png' },
{ name: '[感冒]', file: 'ganmao.png' },
{ name: '[流汗]', file: 'liuhan.png' },
{ name: '[笑哭]', file: 'xiaoku.png' },
{ name: '[流口水]', file: 'liukoushui.png' },
{ name: '[尴尬]', file: 'ganga.png' },
{ name: '[惊讶]', file: 'jingya.png' },
{ name: '[大惊]', file: 'dajing.png' },
{ name: '[不好意思]', file: 'buhaoyisi.png' },
{ name: '[大闹]', file: 'danao.png' },
{ name: '[不可思议]', file: 'bukesiyi.png' },
{ name: '[爱你]', file: 'aini.png' },
{ name: '[红心]', file: 'hongxin.png' },
{ name: '[点赞]', file: 'dianzan.png' },
{ name: '[恶魔]', file: 'emo.png' },
];
export let emojiPage = {};
emojiList.forEach((item, index) => {
if (!emojiPage[Math.floor(index / 30) + 1]) {
emojiPage[Math.floor(index / 30) + 1] = [];
}
emojiPage[Math.floor(index / 30) + 1].push(item);
});
+870
View File
@@ -0,0 +1,870 @@
<template>
<s-layout class="chat-wrap" title="客服" navbar="inner">
<div class="status">
{{ socketState.isConnect ? customerServiceInfo.title : '网络已断开,请检查网络后刷新重试' }}
</div>
<div class="page-bg" :style="{ height: sys_navBar + 'px' }"></div>
<view class="chat-box" :style="{ height: pageHeight + 'px' }">
<scroll-view
:style="{ height: pageHeight + 'px' }"
scroll-y="true"
:scroll-with-animation="false"
:enable-back-to-top="true"
:scroll-into-view="chat.scrollInto"
>
<button
class="loadmore-btn ss-reset-button"
v-if="
chatList.length &&
chatHistoryPagination.lastPage > 1 &&
loadingMap[chatHistoryPagination.loadStatus].title
"
@click="onLoadMore"
>
{{ loadingMap[chatHistoryPagination.loadStatus].title }}
<i
class="loadmore-icon sa-m-l-6"
:class="loadingMap[chatHistoryPagination.loadStatus].icon"
></i>
</button>
<view class="message-item ss-flex-col" v-for="(item, index) in chatList" :key="index">
<view class="ss-flex ss-row-center ss-col-center">
<!-- 日期 -->
<view v-if="item.from !== 'system' && showTime(item, index)" class="date-message">
{{ formatTime(item.date) }}
</view>
<!-- 系统消息 -->
<view v-if="item.from === 'system'" class="system-message">
{{ item.content.text }}
</view>
</view>
<!-- 常见问题 -->
<view v-if="item.mode === 'template' && item.content.list.length" class="template-wrap">
<view class="title">猜你想问</view>
<view
class="item"
v-for="(item, index) in item.content.list"
:key="index"
@click="onTemplateList(item)"
>
* {{ item.title }}
</view>
</view>
<view
v-if="
(item.from === 'customer_service' && item.mode !== 'template') ||
item.from === 'customer'
"
class="ss-flex ss-col-top"
:class="[
item.from === 'customer_service'
? `ss-row-left`
: item.from === 'customer'
? `ss-row-right`
: '',
]"
>
<!-- 客服头像 -->
<image
v-show="item.from === 'customer_service'"
class="chat-avatar ss-m-r-24"
:src="
sheep.$url.cdn(item?.sender?.avatar) ||
sheep.$url.static('/static/img/shop/chat/default.png')
"
mode="aspectFill"
></image>
<!-- 发送状态 -->
<span
v-if="
item.from === 'customer' &&
index == chatData.chatList.length - 1 &&
chatData.isSendSucces !== 0
"
class="send-status"
>
<image
v-if="chatData.isSendSucces == -1"
class="loading"
:src="sheep.$url.static('/static/img/shop/chat/loading.png')"
mode="aspectFill"
></image>
<!-- <image
v-if="chatData.isSendSucces == 1"
class="warning"
:src="sheep.$url.static('/static/img/shop/chat/warning.png')"
mode="aspectFill"
@click="onAgainSendMessage(item)"
></image> -->
</span>
<!-- 内容 -->
<template v-if="item.mode === 'text'">
<view class="message-box" :class="[item.from]">
<div
class="message-text ss-flex ss-flex-wrap"
@click="onRichtext"
v-html="replaceEmoji(item.content.text)"
></div>
</view>
</template>
<template v-if="item.mode === 'image'">
<view class="message-box" :class="[item.from]" :style="{ width: '200rpx' }">
<su-image
class="message-img"
isPreview
:previewList="[sheep.$url.cdn(item.content.url)]"
:current="0"
:src="sheep.$url.cdn(item.content.url)"
:height="200"
:width="200"
mode="aspectFill"
></su-image>
</view>
</template>
<template v-if="item.mode === 'goods'">
<GoodsItem
:goodsData="item.content.item"
@tap="
sheep.$router.go('/pages/goods/index', {
id: item.content.item.id,
})
"
/>
</template>
<template v-if="item.mode === 'order'">
<OrderItem
from="msg"
:orderData="item.content.item"
@tap="
sheep.$router.go('/pages/order/detail', {
id: item.content.item.id,
})
"
/>
</template>
<!-- user头像 -->
<image
v-show="item.from === 'customer'"
class="chat-avatar ss-m-l-24"
:src="sheep.$url.cdn(customerUserInfo.avatar)"
mode="aspectFill"
>
</image>
</view>
</view>
<view id="scrollBottom"></view>
</scroll-view>
</view>
<su-fixed bottom>
<view class="send-wrap ss-flex">
<view class="left ss-flex ss-flex-1">
<uni-easyinput
class="ss-flex-1 ss-p-l-22"
:inputBorder="false"
:clearable="false"
v-model="chat.msg"
placeholder="请输入你要咨询的问题"
></uni-easyinput>
</view>
<text class="sicon-basic bq" @tap.stop="onTools('emoji')"></text>
<text
v-if="!chat.msg"
class="sicon-edit"
:class="{ 'is-active': chat.toolsMode == 'tools' }"
@tap.stop="onTools('tools')"
></text>
<button v-if="chat.msg" class="ss-reset-button send-btn" @tap="onSendMessage">
发送
</button>
</view>
</su-fixed>
<su-popup
:show="chat.showTools"
@close="
chat.showTools = false;
chat.toolsMode = '';
"
>
<view class="ss-modal-box ss-flex-col">
<view class="send-wrap ss-flex">
<view class="left ss-flex ss-flex-1">
<uni-easyinput
class="ss-flex-1 ss-p-l-22"
:inputBorder="false"
:clearable="false"
v-model="chat.msg"
placeholder="请输入你要咨询的问题"
></uni-easyinput>
</view>
<text class="sicon-basic bq" @tap.stop="onTools('emoji')"></text>
<text></text>
<text
v-if="!chat.msg"
class="sicon-edit"
:class="{ 'is-active': chat.toolsMode == 'tools' }"
@tap.stop="onTools('tools')"
></text>
<button v-if="chat.msg" class="ss-reset-button send-btn" @tap="onSendMessage">
发送
</button>
</view>
<view class="content ss-flex ss-flex-1">
<template v-if="chat.toolsMode == 'emoji'">
<swiper
class="emoji-swiper"
:indicator-dots="true"
circular
indicator-active-color="#7063D2"
indicator-color="rgba(235, 231, 255, 1)"
:autoplay="false"
:interval="3000"
:duration="1000"
>
<swiper-item v-for="emoji in emojiPage" :key="emoji">
<view class="ss-flex ss-flex-wrap">
<template v-for="item in emoji" :key="item">
<image
class="emoji-img"
:src="sheep.$url.cdn(`/static/img/chat/emoji/${item.file}`)"
@tap="onEmoji(item)"
>
</image>
</template>
</view>
</swiper-item>
</swiper>
</template>
<template v-else>
<view class="image">
<s-uploader
file-mediatype="image"
:imageStyles="{ width: 50, height: 50, border: false }"
@select="onSelect({ type: 'image', data: $event })"
>
<image
class="icon"
:src="sheep.$url.static('/static/img/shop/chat/image.png')"
mode="aspectFill"
></image>
</s-uploader>
<view>图片</view>
</view>
<view class="goods" @tap="onShowSelect('goods')">
<image
class="icon"
:src="sheep.$url.static('/static/img/shop/chat/goods.png')"
mode="aspectFill"
></image>
<view>商品</view>
</view>
<view class="order" @tap="onShowSelect('order')">
<image
class="icon"
:src="sheep.$url.static('/static/img/shop/chat/order.png')"
mode="aspectFill"
></image>
<view>订单</view>
</view>
</template>
</view>
</view>
</su-popup>
<SelectPopup
:mode="chat.selectMode"
:show="chat.showSelect"
@select="onSelect"
@close="chat.showSelect = false"
/>
</s-layout>
</template>
<script setup>
import sheep from '@/sheep';
import { computed, reactive, toRefs } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { emojiList, emojiPage } from './emoji.js';
import SelectPopup from './components/select-popup.vue';
import GoodsItem from './components/goods.vue';
import OrderItem from './components/order.vue';
import { useChatWebSocket } from './socket';
const {
socketInit,
state: chatData,
socketSendMsg,
formatChatInput,
socketHistoryList,
onDrop,
onPaste,
getFocus,
// upload,
getUserToken,
// socketTest,
showTime,
formatTime,
} = useChatWebSocket();
const chatList = toRefs(chatData).chatList;
const customerServiceInfo = toRefs(chatData).customerServerInfo;
const chatHistoryPagination = toRefs(chatData).chatHistoryPagination;
const customerUserInfo = toRefs(chatData).customerUserInfo;
const socketState = toRefs(chatData).socketState;
const sys_navBar = sheep.$platform.navbar;
const chatConfig = computed(() => sheep.$store('app').chat);
const { screenHeight, safeAreaInsets, safeArea, screenWidth } = sheep.$platform.device;
const pageHeight = safeArea.height - 44 - 35 - 50;
const chatStatus = {
online: {
text: '在线',
colorVariate: '#46c55f',
},
offline: {
text: '离线',
colorVariate: '#b5b5b5',
},
busy: {
text: '忙碌',
colorVariate: '#ff0e1b',
},
};
// 加载更多
const loadingMap = {
loadmore: {
title: '查看更多',
icon: 'el-icon-d-arrow-left',
},
nomore: {
title: '没有更多了',
icon: '',
},
loading: {
title: '加载中... ',
icon: 'el-icon-loading',
},
};
const onLoadMore = () => {
chatHistoryPagination.value.page < chatHistoryPagination.value.lastPage && socketHistoryList();
};
const chat = reactive({
msg: '',
scrollInto: '',
showTools: false,
toolsMode: '',
showSelect: false,
selectMode: '',
chatStyle: {
mode: 'inner',
color: '#F8270F',
type: 'color',
alwaysShow: 1,
src: '',
list: {},
},
});
// 点击工具栏开关
function onTools(mode) {
if (!socketState.value.isConnect) {
sheep.$helper.toast(socketState.value.tip || '您已掉线!请返回重试');
return;
}
if (!chat.toolsMode || chat.toolsMode === mode) {
chat.showTools = !chat.showTools;
}
chat.toolsMode = mode;
if (!chat.showTools) {
chat.toolsMode = '';
}
}
function onShowSelect(mode) {
chat.showTools = false;
chat.showSelect = true;
chat.selectMode = mode;
}
async function onSelect({ type, data }) {
let msg = '';
switch (type) {
case 'image':
const { path, fullurl } = await sheep.$api.app.upload(data.tempFiles[0].path, 'default');
msg = {
from: 'customer',
mode: 'image',
date: new Date().getTime(),
content: {
url: fullurl,
path: path,
},
};
break;
case 'goods':
msg = {
from: 'customer',
mode: 'goods',
date: new Date().getTime(),
content: {
item: {
id: data.goods.id,
title: data.goods.title,
image: data.goods.image,
price: data.goods.price,
stock: data.goods.stock,
},
},
};
break;
case 'order':
msg = {
from: 'customer',
mode: 'order',
date: new Date().getTime(),
content: {
item: {
id: data.id,
order_sn: data.order_sn,
create_time: data.create_time,
pay_fee: data.pay_fee,
items: data.items.filter((item) => ({
goods_id: item.goods_id,
goods_title: item.goods_title,
goods_image: item.goods_image,
goods_price: item.goods_price,
})),
status_text: data.status_text,
},
},
};
break;
}
if (msg) {
socketSendMsg(msg, () => {
scrollBottom();
});
// scrollBottom();
chat.showTools = false;
chat.showSelect = false;
chat.selectMode = '';
}
}
function onAgainSendMessage(item) {
if (!socketState.value.isConnect) {
sheep.$helper.toast(socketState.value.tip || '您已掉线!请返回重试');
return;
}
if (!item) return;
const data = {
from: 'customer',
mode: 'text',
date: new Date().getTime(),
content: item.content,
};
socketSendMsg(data, () => {
scrollBottom();
});
}
function onSendMessage() {
if (!socketState.value.isConnect) {
sheep.$helper.toast(socketState.value.tip || '您已掉线!请返回重试');
return;
}
if (!chat.msg) return;
const data = {
from: 'customer',
mode: 'text',
date: new Date().getTime(),
content: {
text: chat.msg,
},
};
socketSendMsg(data, () => {
scrollBottom();
});
chat.showTools = false;
// scrollBottom();
setTimeout(() => {
chat.msg = '';
}, 100);
}
// 点击猜你想问
function onTemplateList(e) {
if (!socketState.value.isConnect) {
sheep.$helper.toast(socketState.value.tip || '您已掉线!请返回重试');
return;
}
const data = {
from: 'customer',
mode: 'text',
date: new Date().getTime(),
content: {
text: e.title,
},
customData: {
question_id: e.id,
},
};
socketSendMsg(data, () => {
scrollBottom();
});
// scrollBottom();
}
function onEmoji(item) {
chat.msg += item.name;
}
function selEmojiFile(name) {
for (let index in emojiList) {
if (emojiList[index].name === name) {
return emojiList[index].file;
}
}
return false;
}
function replaceEmoji(data) {
let newData = data;
if (typeof newData !== 'object') {
let reg = /\[(.+?)\]/g; // [] 中括号
let zhEmojiName = newData.match(reg);
if (zhEmojiName) {
zhEmojiName.forEach((item) => {
let emojiFile = selEmojiFile(item);
newData = newData.replace(
item,
`<img class="chat-img" style="width: 24px;height: 24px;margin: 0 3px;" src="${sheep.$url.cdn(
'/static/img/chat/emoji/' + emojiFile,
)}"/>`,
);
});
}
}
return newData;
}
function scrollBottom() {
let timeout = null;
chat.scrollInto = '';
clearTimeout(timeout);
timeout = setTimeout(() => {
chat.scrollInto = 'scrollBottom';
}, 100);
}
onLoad(async () => {
const { error } = await getUserToken();
if (error === 0) {
socketInit(chatConfig.value, () => {
scrollBottom();
});
} else {
socketState.value.isConnect = false;
}
});
</script>
<style lang="scss" scoped>
.page-bg {
width: 100%;
position: absolute;
top: 0;
left: 0;
background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
background-size: 750rpx 100%;
z-index: 1;
}
.chat-wrap {
// :deep() {
// .ui-navbar-box {
// background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
// }
// }
.status {
position: relative;
box-sizing: border-box;
z-index: 3;
height: 70rpx;
padding: 0 30rpx;
background: var(--ui-BG-Main-opacity-1);
display: flex;
align-items: center;
font-size: 30rpx;
font-weight: 400;
color: var(--ui-BG-Main);
}
.chat-box {
padding: 0 20rpx 0;
.loadmore-btn {
width: 98%;
height: 40px;
font-size: 12px;
color: #8c8c8c;
.loadmore-icon {
transform: rotate(90deg);
}
}
.message-item {
margin-bottom: 33rpx;
}
.date-message,
.system-message {
width: fit-content;
border-radius: 12rpx;
padding: 8rpx 16rpx;
margin-bottom: 16rpx;
background-color: var(--ui-BG-3);
color: #999;
font-size: 24rpx;
}
.chat-avatar {
width: 70rpx;
height: 70rpx;
border-radius: 50%;
}
.send-status {
color: #333;
height: 80rpx;
margin-right: 8rpx;
display: flex;
align-items: center;
.loading {
width: 32rpx;
height: 32rpx;
-webkit-animation: rotating 2s linear infinite;
animation: rotating 2s linear infinite;
@-webkit-keyframes rotating {
0% {
transform: rotateZ(0);
}
100% {
transform: rotateZ(360deg);
}
}
@keyframes rotating {
0% {
transform: rotateZ(0);
}
100% {
transform: rotateZ(360deg);
}
}
}
.warning {
width: 32rpx;
height: 32rpx;
color: #ff3000;
}
}
.message-box {
max-width: 50%;
font-size: 16px;
line-height: 20px;
// max-width: 500rpx;
white-space: normal;
word-break: break-all;
word-wrap: break-word;
padding: 20rpx;
border-radius: 10rpx;
color: #fff;
background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
&.customer_service {
background: #fff;
color: #333;
}
:deep() {
.imgred {
width: 100%;
}
.imgred,
img {
width: 100%;
}
}
}
:deep() {
.goods,
.order {
max-width: 500rpx;
}
}
.message-img {
width: 100px;
height: 100px;
border-radius: 6rpx;
}
.template-wrap {
// width: 100%;
padding: 20rpx 24rpx;
background: #fff;
border-radius: 10rpx;
.title {
font-size: 26rpx;
font-weight: 500;
color: #333;
margin-bottom: 29rpx;
}
.item {
font-size: 24rpx;
color: var(--ui-BG-Main);
margin-bottom: 16rpx;
&:last-of-type {
margin-bottom: 0;
}
}
}
.error-img {
width: 400rpx;
height: 400rpx;
}
#scrollBottom {
height: 120rpx;
}
}
.send-wrap {
padding: 18rpx 20rpx;
background: #fff;
.left {
height: 64rpx;
border-radius: 32rpx;
background: var(--ui-BG-1);
}
.bq {
font-size: 50rpx;
margin-left: 10rpx;
}
.sicon-edit {
font-size: 50rpx;
margin-left: 10rpx;
transform: rotate(0deg);
transition: all linear 0.2s;
&.is-active {
transform: rotate(45deg);
}
}
.send-btn {
width: 100rpx;
height: 60rpx;
line-height: 60rpx;
border-radius: 30rpx;
background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
font-size: 26rpx;
color: #fff;
margin-left: 11rpx;
}
}
}
.content {
width: 100%;
align-content: space-around;
border-top: 1px solid #dfdfdf;
padding: 20rpx 0 0;
.emoji-swiper {
width: 100%;
height: 280rpx;
padding: 0 20rpx;
.emoji-img {
width: 50rpx;
height: 50rpx;
display: inline-block;
margin: 10rpx;
}
}
.image,
.goods,
.order {
width: 33.3%;
height: 280rpx;
text-align: center;
font-size: 24rpx;
color: #333;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.icon {
width: 50rpx;
height: 50rpx;
margin-bottom: 21rpx;
}
}
:deep() {
.uni-file-picker__container {
justify-content: center;
}
.file-picker__box {
display: none;
&:last-of-type {
display: flex;
}
}
}
}
</style>
<style>
.chat-img {
width: 24px;
height: 24px;
margin: 0 3px;
}
.full-img {
object-fit: cover;
width: 100px;
height: 100px;
border-radius: 6px;
}
</style>
+821
View File
@@ -0,0 +1,821 @@
import { reactive, ref, unref } from 'vue';
import sheep from '@/sheep';
import chat from '@/sheep/api/chat';
import dayjs from 'dayjs';
import io from '@hyoga/uni-socket.io';
export function useChatWebSocket(socketConfig) {
let SocketIo = null;
// chat状态数据
const state = reactive({
chatDotNum: 0, //总状态红点
chatList: [], //会话信息
customerUserInfo: {}, //用户信息
customerServerInfo: {
//客服信息
title: '连接中...',
state: 'connecting',
avatar: null,
nickname: '',
},
socketState: {
isConnect: true, //是否连接成功
isConnecting: false, //重连中,不允许新的socket开启。
tip: '',
},
chatHistoryPagination: {
page: 0, //当前页
list_rows: 10, //每页条数
last_id: 0, //最后条ID
lastPage: 0, //总共多少页
loadStatus: 'loadmore', //loadmore-加载前的状态,loading-加载中的状态,nomore-没有更多的状态
},
templateChatList: [], //猜你想问
chatConfig: {}, // 配置信息
isSendSucces: -1, // 是否发送成功 -1=发送中|0=发送成功|1发送失败
});
/**
* 连接初始化
* @param {Object} config - 配置信息
* @param {Function} callBack -回调函数,有新消息接入,保持底部
*/
const socketInit = (config, callBack) => {
state.chatConfig = config;
if (SocketIo && SocketIo.connected) return; // 如果socket已经连接,返回false
if (state.socketState.isConnecting) return; // 重连中,返回false
// 启动初始化
SocketIo = io(config.chat_domain, {
reconnection: true, // 默认 true 是否断线重连
reconnectionAttempts: 5, // 默认无限次 断线尝试次数
reconnectionDelay: 1000, // 默认 1000,进行下一次重连的间隔。
reconnectionDelayMax: 5000, // 默认 5000, 重新连接等待的最长时间 默认 5000
randomizationFactor: 0.5, // 默认 0.5 [0-1],随机重连延迟时间
timeout: 20000, // 默认 20s
transports: ['websocket', 'polling'], // websocket | polling,
...config,
});
// 监听连接
SocketIo.on('connect', async (res) => {
socketReset(callBack);
// socket连接
// 用户登录
// 顾客登录
console.log('socket:connect');
});
// 监听消息
SocketIo.on('message', (res) => {
if (res.error === 0) {
const { message, sender } = res.data;
state.chatList.push(formatMessage(res.data.message));
// 告诉父级页面
// window.parent.postMessage({
// chatDotNum: ++state.chatDotNum
// })
callBack && callBack();
}
});
// 监听客服接入成功
SocketIo.on('customer_service_access', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: res.data.customer_service.name,
state: 'online',
avatar: res.data.customer_service.avatar,
});
state.chatList.push(formatMessage(res.data.message));
// callBack && callBack()
}
});
// 监听排队等待
SocketIo.on('waiting_queue', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: res.data.title,
state: 'waiting',
avatar: '',
});
// callBack && callBack()
}
});
// 监听没有客服在线
SocketIo.on('no_customer_service', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: '暂无客服在线...',
state: 'waiting',
avatar: '',
});
}
state.chatList.push(formatMessage(res.data.message));
// callBack && callBack()
});
// 监听客服上线
SocketIo.on('customer_service_online', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: res.data.customer_service.name,
state: 'online',
avatar: res.data.customer_service.avatar,
});
}
});
// 监听客服下线
SocketIo.on('customer_service_offline', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: res.data.customer_service.name,
state: 'offline',
avatar: res.data.customer_service.avatar,
});
}
});
// 监听客服忙碌
SocketIo.on('customer_service_busy', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: res.data.customer_service.name,
state: 'busy',
avatar: res.data.customer_service.avatar,
});
}
});
// 监听客服断开链接
SocketIo.on('customer_service_break', (res) => {
if (res.error === 0) {
editCustomerServerInfo({
title: '客服服务结束',
state: 'offline',
avatar: '',
});
state.socketState.isConnect = false;
state.socketState.tip = '当前服务已结束';
}
state.chatList.push(formatMessage(res.data.message));
// callBack && callBack()
});
// 监听自定义错误 custom_error
SocketIo.on('custom_error', (error) => {
editCustomerServerInfo({
title: error.msg,
state: 'offline',
avatar: '',
});
console.log('custom_error:', error);
});
// 监听错误 error
SocketIo.on('error', (error) => {
console.log('error:', error);
});
// 重连失败 connect_error
SocketIo.on('connect_error', (error) => {
console.log('connect_error');
});
// 连接上,但无反应 connect_timeout
SocketIo.on('connect_timeout', (error) => {
console.log(error, 'connect_timeout');
});
// 服务进程销毁 disconnect
SocketIo.on('disconnect', (error) => {
console.log(error, 'disconnect');
});
// 服务重启重连上reconnect
SocketIo.on('reconnect', (error) => {
console.log(error, 'reconnect');
});
// 开始重连reconnect_attempt
SocketIo.on('reconnect_attempt', (error) => {
state.socketState.isConnect = false;
state.socketState.isConnecting = true;
editCustomerServerInfo({
title: `重连中,第${error}次尝试...`,
state: 'waiting',
avatar: '',
});
console.log(error, 'reconnect_attempt');
});
// 重新连接中reconnecting
SocketIo.on('reconnecting', (error) => {
console.log(error, 'reconnecting');
});
// 重新连接错误reconnect_error
SocketIo.on('reconnect_error', (error) => {
console.log('reconnect_error');
});
// 重新连接失败reconnect_failed
SocketIo.on('reconnect_failed', (error) => {
state.socketState.isConnecting = false;
editCustomerServerInfo({
title: `重连失败,请刷新重试~`,
state: 'waiting',
avatar: '',
});
console.log(error, 'reconnect_failed');
// setTimeout(() => {
state.isSendSucces = 1;
// }, 500)
});
};
// 重置socket
const socketReset = (callBack) => {
state.chatList = [];
state.chatHistoryList = [];
state.chatHistoryPagination = {
page: 0,
per_page: 10,
last_id: 0,
totalPage: 0,
};
socketConnection(callBack); // 连接
};
// 退出连接
const socketClose = () => {
SocketIo.emit('customer_logout', {}, (res) => {
console.log('socket:退出', res);
});
};
// 测试事件
const socketTest = () => {
SocketIo.emit('test', {}, (res) => {
console.log('test:test', res);
});
};
// 发送消息
const socketSendMsg = (data, sendMsgCallBack) => {
state.isSendSucces = -1;
state.chatList.push(data);
sendMsgCallBack && sendMsgCallBack();
SocketIo.emit(
'message',
{
message: formatInput(data),
...data.customData,
},
(res) => {
// setTimeout(() => {
state.isSendSucces = res.error;
// }, 500)
// console.log(res, 'socket:send');
// sendMsgCallBack && sendMsgCallBack()
},
);
};
// 连接socket,存入sessionId
const socketConnection = (callBack) => {
SocketIo.emit(
'connection',
{
auth: 'user',
token: uni.getStorageSync('socketUserToken') || '',
session_id: uni.getStorageSync('socketSessionId') || '',
},
(res) => {
if (res.error === 0) {
socketCustomerLogin(callBack);
uni.setStorageSync('socketSessionId', res.data.session_id);
// uni.getStorageSync('socketUserToken') && socketLogin(uni.getStorageSync(
// 'socketUserToken')) // 如果有用户token,绑定
state.customerUserInfo = res.data.chat_user;
state.socketState.isConnect = true;
} else {
editCustomerServerInfo({
title: `服务器异常!`,
state: 'waiting',
avatar: '',
});
state.socketState.isConnect = false;
}
},
);
};
// 用户id,获取token
const getUserToken = async (id) => {
const res = await chat.unifiedToken();
if (res.error === 0) {
uni.setStorageSync('socketUserToken', res.data.token);
// SocketIo && SocketIo.connected && socketLogin(res.data.token)
}
return res;
};
// 用户登录
const socketLogin = (token) => {
SocketIo.emit(
'login',
{
token: token,
},
(res) => {
console.log(res, 'socket:login');
state.customerUserInfo = res.data.chat_user;
},
);
};
// 顾客登录
const socketCustomerLogin = (callBack) => {
SocketIo.emit(
'customer_login',
{
room_id: state.chatConfig.room_id,
},
(res) => {
state.templateChatList = res.data.questions.length ? res.data.questions : [];
state.chatList.push({
from: 'customer_service', // 用户customer右 | 顾客customer_service左 | 系统system中间
mode: 'template', // goods,order,image,text,system
date: new Date().getTime(), //时间
content: {
//内容
list: state.templateChatList,
},
});
res.error === 0 && socketHistoryList(callBack);
},
);
};
// 获取历史消息
const socketHistoryList = (historyCallBack) => {
state.chatHistoryPagination.loadStatus = 'loading';
state.chatHistoryPagination.page += 1;
SocketIo.emit('messages', state.chatHistoryPagination, (res) => {
if (res.error === 0) {
state.chatHistoryPagination.total = res.data.messages.total;
state.chatHistoryPagination.lastPage = res.data.messages.last_page;
state.chatHistoryPagination.page = res.data.messages.current_page;
res.data.messages.data.forEach((item) => {
item.message_type && state.chatList.unshift(formatMessage(item));
});
state.chatHistoryPagination.loadStatus =
state.chatHistoryPagination.page < state.chatHistoryPagination.lastPage
? 'loadmore'
: 'nomore';
if (state.chatHistoryPagination.last_id == 0) {
state.chatHistoryPagination.last_id = res.data.messages.data.length
? res.data.messages.data[0].id
: 0;
}
state.chatHistoryPagination.page === 1 && historyCallBack && historyCallBack();
}
// 历史记录之后,猜你想问
// state.chatList.push({
// from: 'customer_service', // 用户customer右 | 顾客customer_service左 | 系统system中间
// mode: 'template', // goods,order,image,text,system
// date: new Date().getTime(), //时间
// content: { //内容
// list: state.templateChatList
// }
// })
});
};
// 修改客服信息
const editCustomerServerInfo = (data) => {
state.customerServerInfo = {
...state.customerServerInfo,
...data,
};
};
/**
* ================
* 工具函数 ↓
* ===============
*/
/**
* 是否显示时间
* @param {*} item - 数据
* @param {*} index - 索引
*/
const showTime = (item, index) => {
if (unref(state.chatList)[index + 1]) {
let dateString = dayjs(unref(state.chatList)[index + 1].date).fromNow();
if (dateString === dayjs(unref(item).date).fromNow()) {
return false;
} else {
dateString = dayjs(unref(item).date).fromNow();
return true;
}
}
return false;
};
/**
* 格式化时间
* @param {*} time - 时间戳
*/
const formatTime = (time) => {
let diffTime = new Date().getTime() - time;
if (diffTime > 28 * 24 * 60 * 1000) {
return dayjs(time).format('MM/DD HH:mm');
}
if (diffTime > 360 * 28 * 24 * 60 * 1000) {
return dayjs(time).format('YYYY/MM/DD HH:mm');
}
return dayjs(time).fromNow();
};
/**
* 获取焦点
* @param {*} virtualNode - 节点信息 ref
*/
const getFocus = (virtualNode) => {
if (window.getSelection) {
let chatInput = unref(virtualNode);
chatInput.focus();
let range = window.getSelection();
range.selectAllChildren(chatInput);
range.collapseToEnd();
} else if (document.selection) {
let range = document.selection.createRange();
range.moveToElementText(chatInput);
range.collapse(false);
range.select();
}
};
/**
* 文件上传
* @param {Blob} file -文件数据流
* @return {path,fullPath}
*/
const upload = (name, file) => {
return new Promise((resolve, reject) => {
let data = new FormData();
data.append('file', file, name);
data.append('group', 'chat');
ajax({
url: '/upload',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
data,
success: function (res) {
resolve(res);
},
error: function (err) {
reject(err);
},
});
});
};
/**
* 粘贴到输入框
* @param {*} e - 粘贴内容
* @param {*} uploadHttp - 上传图片地址
*/
const onPaste = async (e) => {
let paste = e.clipboardData || window.clipboardData;
let filesArr = Array.from(paste.files);
filesArr.forEach(async (child) => {
if (child && child.type.includes('image')) {
e.preventDefault(); //阻止默认
let file = child;
const img = await readImg(file);
const blob = await compressImg(img, file.type);
const { data } = await upload(file.name, blob);
let image = `<img class="full-url" src='${data.fullurl}'>`;
document.execCommand('insertHTML', false, image);
} else {
document.execCommand('insertHTML', false, paste.getData('text'));
}
});
};
/**
* 拖拽到输入框
* @param {*} e - 粘贴内容
* @param {*} uploadHttp - 上传图片地址
*/
const onDrop = async (e) => {
e.preventDefault(); //阻止默认
let filesArr = Array.from(e.dataTransfer.files);
filesArr.forEach(async (child) => {
if (child && child.type.includes('image')) {
let file = child;
const img = await readImg(file);
const blob = await compressImg(img, file.type);
const { data } = await upload(file.name, blob);
let image = `<img class="full-url" src='${data.fullurl}' >`;
document.execCommand('insertHTML', false, image);
} else {
ElMessage({
message: '禁止拖拽非图片资源',
type: 'warning',
});
}
});
};
/**
* 解析富文本输入框内容
* @param {*} virtualNode -节点信息
* @param {Function} formatInputCallBack - cb 回调
*/
const formatChatInput = (virtualNode, formatInputCallBack) => {
let res = '';
let elemArr = Array.from(virtualNode.childNodes);
elemArr.forEach((child, index) => {
if (child.nodeName === '#text') {
//如果为文本节点
res += child.nodeValue;
if (
//文本节点的后面是图片,并且不是emoji,分开发送。输入框中的图片和文本表情分开。
elemArr[index + 1] &&
elemArr[index + 1].nodeName === 'IMG' &&
elemArr[index + 1] &&
elemArr[index + 1].name !== 'emoji'
) {
const data = {
from: 'customer',
mode: 'text',
date: new Date().getTime(),
content: {
text: filterXSS(res),
},
};
formatInputCallBack && formatInputCallBack(data);
res = '';
}
} else if (child.nodeName === 'BR') {
res += '<br/>';
} else if (child.nodeName === 'IMG') {
// 有emjio 和 一般图片
// 图片解析后直接发送,不跟文字表情一组
if (child.name !== 'emoji') {
let srcReg = /src=[\'\']?([^\'\']*)[\'\']?/i;
let src = child.outerHTML.match(srcReg);
const data = {
from: 'customer',
mode: 'image',
date: new Date().getTime(),
content: {
url: src[1],
path: src[1].replace(/http:\/\/[^\/]*/, ''),
},
};
formatInputCallBack && formatInputCallBack(data);
} else {
// 非表情图片跟文字一起发送
res += child.outerHTML;
}
} else if (child.nodeName === 'DIV') {
res += `<div style='width:200px; white-space: nowrap;'>${child.outerHTML}</div>`;
}
});
if (res) {
const data = {
from: 'customer',
mode: 'text',
date: new Date().getTime(),
content: {
text: filterXSS(res),
},
};
formatInputCallBack && formatInputCallBack(data);
}
unref(virtualNode).innerHTML = '';
};
/**
* 状态回调
* @param {*} res -接口返回数据
*/
const callBackNotice = (res) => {
ElNotification({
title: 'socket',
message: res.msg,
showClose: true,
type: res.error === 0 ? 'success' : 'warning',
duration: 1200,
});
};
/**
* 格式化发送信息
* @param {Object} message
* @returns obj - 消息对象
*/
const formatInput = (message) => {
let obj = {};
switch (message.mode) {
case 'text':
obj = {
message_type: 'text',
message: message.content.text,
};
break;
case 'image':
obj = {
message_type: 'image',
message: message.content.path,
};
break;
case 'goods':
obj = {
message_type: 'goods',
message: message.content.item,
};
break;
case 'order':
obj = {
message_type: 'order',
message: message.content.item,
};
break;
default:
break;
}
return obj;
};
/**
* 格式化接收信息
* @param {*} message
* @returns obj - 消息对象
*/
const formatMessage = (message) => {
let obj = {};
switch (message.message_type) {
case 'system':
obj = {
from: 'system', // 用户customer左 | 顾客customer_service右 | 系统system中间
mode: 'system', // goods,order,image,text,system
date: message.create_time * 1000, //时间
content: {
//内容
text: message.message,
},
};
break;
case 'text':
obj = {
from: message.sender_identify,
mode: message.message_type,
date: message.create_time * 1000, //时间
sender: message.sender,
content: {
text: message.message,
messageId: message.id,
},
};
break;
case 'image':
obj = {
from: message.sender_identify,
mode: message.message_type,
date: message.create_time * 1000, //时间
sender: message.sender,
content: {
url: sheep.$url.cdn(message.message),
messageId: message.id,
},
};
break;
case 'goods':
obj = {
from: message.sender_identify,
mode: message.message_type,
date: message.create_time * 1000, //时间
sender: message.sender,
content: {
item: message.message,
messageId: message.id,
},
};
break;
case 'order':
obj = {
from: message.sender_identify,
mode: message.message_type,
date: message.create_time * 1000, //时间
sender: message.sender,
content: {
item: message.message,
messageId: message.id,
},
};
break;
default:
break;
}
return obj;
};
/**
* file 转换为 img
* @param {*} file - file 文件
* @returns img - img标签
*/
const readImg = (file) => {
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
};
reader.onerror = function (e) {
reject(e);
};
reader.readAsDataURL(file);
img.onload = function () {
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
});
};
/**
* 压缩图片
*@param img -被压缩的img对象
* @param type -压缩后转换的文件类型
* @param mx -触发压缩的图片最大宽度限制
* @param mh -触发压缩的图片最大高度限制
* @returns blob - 文件流
*/
const compressImg = (img, type = 'image/jpeg', mx = 1000, mh = 1000, quality = 1) => {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const { width: originWidth, height: originHeight } = img;
// 最大尺寸限制
const maxWidth = mx;
const maxHeight = mh;
// 目标尺寸
let targetWidth = originWidth;
let targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > 1) {
// 宽图片
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
// 高图片
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片绘制
context.drawImage(img, 0, 0, targetWidth, targetHeight);
canvas.toBlob(
function (blob) {
resolve(blob);
},
type,
quality,
);
});
};
return {
compressImg,
readImg,
formatMessage,
formatInput,
callBackNotice,
socketInit,
socketSendMsg,
socketClose,
socketHistoryList,
getFocus,
formatChatInput,
onDrop,
onPaste,
upload,
getUserToken,
state,
socketTest,
showTime,
formatTime,
};
}