Compare commits
11 Commits
27b2052cec
...
V1.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
| 06ec029555 | |||
| af615f666c | |||
| fb15b8aec1 | |||
| 7239313f0f | |||
| 5d98b76fd1 | |||
| 9c658e9f9f | |||
| 7e02429f6e | |||
| 71a1083887 | |||
| 972c777177 | |||
|
|
ae2fb40d72 | ||
|
|
3e18c99161 |
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"appid": "wx23f86d809ae80259",
|
||||
"appid": "wx5e79df5996572539",
|
||||
"compileType": "miniprogram",
|
||||
"libVersion": "3.8.10",
|
||||
"packOptions": {
|
||||
|
||||
@@ -200,6 +200,7 @@ function main() {
|
||||
console.log("\n🎉 所有文件更新完成!");
|
||||
console.log(`💡 已切换到 ${CLIENT_CONFIGS[clientName].name} 客户端配置`);
|
||||
console.log("💡 提示: 请检查文件内容确认更新正确");
|
||||
console.log("\n💡 版本升级: 请到request/api/config.js文件中更新versionValue版本号\n");
|
||||
} else {
|
||||
console.log("\n❌ 部分文件更新失败,请检查错误信息");
|
||||
process.exit(1);
|
||||
|
||||
@@ -5,11 +5,14 @@ import { refreshToken } from "@/hooks/useGoLogin";
|
||||
import { getAccessToken } from "@/constant/token";
|
||||
|
||||
onLaunch(async () => {
|
||||
await getEvnUrl({ versionValue: "1.0.3" });
|
||||
/// 获取环境配置
|
||||
await getEvnUrl();
|
||||
|
||||
/// 获取token
|
||||
const token = getAccessToken();
|
||||
|
||||
if (token) {
|
||||
/// 刷新token
|
||||
refreshToken();
|
||||
}
|
||||
});
|
||||
@@ -21,6 +24,7 @@ onShow(() => {
|
||||
onHide(() => {
|
||||
console.log("App Hide");
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
|
||||
@@ -27,6 +27,18 @@
|
||||
</view>
|
||||
<uni-icons type="calendar" size="20" color="#1890ff"></uni-icons>
|
||||
</view>
|
||||
|
||||
<!-- 价格区间选择示例 -->
|
||||
<view class="date-input" @tap="openPriceRangeCalendar">
|
||||
<view class="input-content">
|
||||
<text class="input-label">选择有价格的日期范围</text>
|
||||
<text class="input-value" v-if="selectedRange.start && selectedRange.end">
|
||||
{{ selectedRange.start }} 至 {{ selectedRange.end }}
|
||||
</text>
|
||||
<text class="input-placeholder" v-else>请选择价格区间(仅含有价夜晚)</text>
|
||||
</view>
|
||||
<uni-icons type="calendar" size="20" color="#1890ff"></uni-icons>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 结果显示区域 -->
|
||||
@@ -35,11 +47,13 @@
|
||||
<view class="result-item" v-if="selectedDate">
|
||||
<text class="result-label">单选日期:</text>
|
||||
<text class="result-value">{{ selectedDate }}</text>
|
||||
<text class="result-value" v-if="selectedDatePrice"> ¥{{ selectedDatePrice }} </text>
|
||||
</view>
|
||||
<view class="result-item" v-if="selectedRange.start && selectedRange.end">
|
||||
<text class="result-label">日期范围:</text>
|
||||
<text class="result-value">{{ selectedRange.start }} 至 {{ selectedRange.end }}</text>
|
||||
<text class="result-days">(共{{ rangeDays }}天)</text>
|
||||
<text class="result-value" v-if="selectedRangeTotal"> 总价:¥{{ selectedRangeTotal }} </text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -62,6 +76,17 @@
|
||||
@close="handleRangeCalendarClose"
|
||||
@range-select="handleRangeSelect"
|
||||
/>
|
||||
|
||||
<!-- 日历组件 - 价格区间选择模式(必须有价格的夜晚) -->
|
||||
<Calendar
|
||||
:visible="priceRangeCalendarVisible"
|
||||
:price-data="priceData"
|
||||
mode="range"
|
||||
:range-require-price="true"
|
||||
:default-value="[selectedRange.start, selectedRange.end]"
|
||||
@close="handleRangeCalendarClose"
|
||||
@range-select="handlePriceRangeSelect"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
@@ -72,11 +97,14 @@ import Calendar from './index.vue'
|
||||
// 响应式数据
|
||||
const calendarVisible = ref(false)
|
||||
const rangeCalendarVisible = ref(false)
|
||||
const priceRangeCalendarVisible = ref(false)
|
||||
const selectedDate = ref('')
|
||||
const selectedDatePrice = ref(null)
|
||||
const selectedRange = ref({
|
||||
start: '',
|
||||
end: ''
|
||||
})
|
||||
const selectedRangeTotal = ref(null)
|
||||
|
||||
// 模拟价格数据
|
||||
const priceData = ref({
|
||||
@@ -116,6 +144,11 @@ const openRangeCalendar = () => {
|
||||
rangeCalendarVisible.value = true
|
||||
}
|
||||
|
||||
// 打开价格区间选择器(必须以价格为准)
|
||||
const openPriceRangeCalendar = () => {
|
||||
priceRangeCalendarVisible.value = true
|
||||
}
|
||||
|
||||
// 处理单选日历关闭
|
||||
const handleCalendarClose = () => {
|
||||
calendarVisible.value = false
|
||||
@@ -129,6 +162,7 @@ const handleRangeCalendarClose = () => {
|
||||
// 处理日期选择
|
||||
const handleDateSelect = (data) => {
|
||||
selectedDate.value = data.date
|
||||
selectedDatePrice.value = (data.price !== undefined && data.price !== null && data.price !== '-') ? data.price : null
|
||||
calendarVisible.value = false
|
||||
console.log('选择的日期:', data)
|
||||
}
|
||||
@@ -139,9 +173,37 @@ const handleRangeSelect = (data) => {
|
||||
start: data.startDate,
|
||||
end: data.endDate
|
||||
}
|
||||
if (data.dateRange && Array.isArray(data.dateRange)) {
|
||||
const total = data.dateRange.reduce((sum, d) => {
|
||||
const p = d.price
|
||||
return sum + (typeof p === 'number' ? p : 0)
|
||||
}, 0)
|
||||
selectedRangeTotal.value = total || null
|
||||
} else {
|
||||
selectedRangeTotal.value = null
|
||||
}
|
||||
rangeCalendarVisible.value = false
|
||||
console.log('选择的日期范围:', data)
|
||||
}
|
||||
|
||||
// 处理价格区间选择
|
||||
const handlePriceRangeSelect = (data) => {
|
||||
selectedRange.value = {
|
||||
start: data.startDate,
|
||||
end: data.endDate
|
||||
}
|
||||
if (data.dateRange && Array.isArray(data.dateRange)) {
|
||||
const total = data.dateRange.reduce((sum, d) => {
|
||||
const p = d.price
|
||||
return sum + (typeof p === 'number' ? p : 0)
|
||||
}, 0)
|
||||
selectedRangeTotal.value = total || null
|
||||
} else {
|
||||
selectedRangeTotal.value = null
|
||||
}
|
||||
priceRangeCalendarVisible.value = false
|
||||
console.log('价格区间选择:', data)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<view class="calendar-header">
|
||||
<view class="header-content">
|
||||
<text class="header-title">日历选择</text>
|
||||
<text class="header-subtitle"
|
||||
<text v-if="props.rangeRequirePrice" class="header-subtitle"
|
||||
>选择住宿日期,以下价格为单晚参考价</text
|
||||
>
|
||||
</view>
|
||||
@@ -50,9 +50,7 @@
|
||||
{{ dateInfo.label }}
|
||||
</text>
|
||||
<text class="date-number">{{ dateInfo.day }}</text>
|
||||
<text class="date-price" v-if="dateInfo.price"
|
||||
>¥{{ dateInfo.price }}</text
|
||||
>
|
||||
<text class="date-price" v-if="dateInfo.price !== null && dateInfo.price !== undefined">¥{{ dateInfo.price }}</text>
|
||||
</template>
|
||||
</view>
|
||||
</view>
|
||||
@@ -91,9 +89,10 @@ const props = defineProps({
|
||||
},
|
||||
|
||||
// 价格数据数组
|
||||
// 格式: [{ date: '2024-05-17', price: 449, stock: 3 }, ...]
|
||||
priceData: {
|
||||
type: Array,
|
||||
default: () => [{ date: "", price: "-", stock: "0" }],
|
||||
type: [Object, Array],
|
||||
default: () => ({}),
|
||||
},
|
||||
|
||||
// 默认选中日期
|
||||
@@ -109,6 +108,12 @@ const props = defineProps({
|
||||
validator: (value) => ["single", "range"].includes(value),
|
||||
},
|
||||
|
||||
// 范围选择时是否必须有价格(作为价格区间选择器)
|
||||
rangeRequirePrice: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
|
||||
// 最小可选日期
|
||||
minDate: {
|
||||
type: String,
|
||||
@@ -202,14 +207,36 @@ const getFirstDayOfMonth = (year, month) => {
|
||||
return day === 0 ? 6 : day - 1; // 转换为周一开始 (0=周一, 6=周日)
|
||||
};
|
||||
|
||||
// 获取指定日期的价格
|
||||
const getPriceForDate = (dateStr) => {
|
||||
if (!props.priceData || !Array.isArray(props.priceData)) {
|
||||
// 获取指定日期的价格项(兼容对象或者数组)
|
||||
const getPriceItem = (dateStr) => {
|
||||
if (!props.priceData) return null;
|
||||
|
||||
// 对象映射格式:{ '2024-05-17': 449 }
|
||||
if (!Array.isArray(props.priceData) && typeof props.priceData === "object") {
|
||||
if (Object.prototype.hasOwnProperty.call(props.priceData, dateStr)) {
|
||||
const val = props.priceData[dateStr];
|
||||
// 可能只是数字价格,也可能是对象
|
||||
if (val !== null && typeof val === "object") {
|
||||
return { date: dateStr, price: val.price, stock: val.stock };
|
||||
}
|
||||
return { date: dateStr, price: val };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const priceItem = props.priceData.find((item) => item.date === dateStr);
|
||||
return priceItem ? priceItem.price : null;
|
||||
// 数组格式:[{date, price, stock}, ...]
|
||||
if (Array.isArray(props.priceData)) {
|
||||
const item = props.priceData.find((it) => it.date === dateStr);
|
||||
return item || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// 获取价格值便捷函数
|
||||
const getPriceForDate = (dateStr) => {
|
||||
const item = getPriceItem(dateStr);
|
||||
return item ? item.price : null;
|
||||
};
|
||||
|
||||
// 生成日历网格数据
|
||||
@@ -228,10 +255,12 @@ const generateCalendarGrid = (year, month) => {
|
||||
const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(
|
||||
day
|
||||
).padStart(2, "0")}`;
|
||||
const priceItem = getPriceItem(dateStr);
|
||||
grid.push({
|
||||
date: dateStr,
|
||||
day: day,
|
||||
price: getPriceForDate(dateStr),
|
||||
price: priceItem ? priceItem.price : null,
|
||||
stock: priceItem ? priceItem.stock : undefined,
|
||||
disabled: isDateDisabled(dateStr),
|
||||
selected: isDateSelected(dateStr),
|
||||
inRange: isDateInRange(dateStr),
|
||||
@@ -248,10 +277,14 @@ const isDateDisabled = (dateStr) => {
|
||||
const minDate = new Date(props.minDate);
|
||||
const maxDate = props.maxDate ? new Date(props.maxDate) : null;
|
||||
|
||||
// 过去或超出范围
|
||||
if (date < minDate) return true;
|
||||
if (maxDate && date > maxDate) return true;
|
||||
if (props.disabledDates.includes(dateStr)) return true;
|
||||
|
||||
// 注意:不在此处基于价格全局禁用日期,
|
||||
// 允许未定价的日期被点击作为离店日(结束日),
|
||||
// 价格校验在范围完成时对夜晚(不含离店日)进行。
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -310,13 +343,28 @@ const getDateCellClass = (dateInfo) => {
|
||||
if (dateInfo.disabled) classes.push("date-cell-disabled");
|
||||
if (dateInfo.selected) classes.push("date-cell-selected");
|
||||
if (dateInfo.inRange) classes.push("date-cell-in-range");
|
||||
// 标注无价格但可选的日期(用于视觉区分)
|
||||
if (dateInfo.price === null || dateInfo.price === undefined || dateInfo.price === "-") {
|
||||
classes.push("date-cell-no-price");
|
||||
}
|
||||
|
||||
return classes.join(" ");
|
||||
};
|
||||
|
||||
// 处理日期点击
|
||||
const handleDateClick = (dateInfo) => {
|
||||
if (!dateInfo || dateInfo.disabled) return;
|
||||
if (!dateInfo) return;
|
||||
if (dateInfo.disabled) {
|
||||
uni.showToast({ title: "该日期不可选", icon: "none" });
|
||||
// 仍然触发点击事件,供上层参考
|
||||
emit("date-click", {
|
||||
date: dateInfo.date,
|
||||
price: dateInfo.price,
|
||||
disabled: dateInfo.disabled,
|
||||
selected: dateInfo.selected,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 防抖处理
|
||||
if (clickTimer.value) {
|
||||
@@ -352,59 +400,79 @@ const handleSingleSelect = (dateInfo) => {
|
||||
|
||||
// 处理范围选择
|
||||
const handleRangeSelection = (dateInfo) => {
|
||||
if (dateInfo.price === undefined || dateInfo.price === null || dateInfo.stock === '' || dateInfo.price === '-') {
|
||||
uni.showToast({
|
||||
title: "所选日期不可预订,请重新选择",
|
||||
icon: "none",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果当前没有开始日期或已经完成一次选择,则此次点击作为开始日期
|
||||
if (!rangeStart.value || (rangeStart.value && rangeEnd.value)) {
|
||||
// 开始新的范围选择
|
||||
// 开始新的范围选择:当作为价格区间选择器时,开始日必须有价格且有库存
|
||||
if (props.rangeRequirePrice) {
|
||||
const hasPrice = dateInfo.price !== null && dateInfo.price !== undefined && dateInfo.price !== "-";
|
||||
if (!hasPrice) {
|
||||
uni.showToast({ title: "所选日期不可预订,请重新选择", icon: "none" });
|
||||
return;
|
||||
}
|
||||
if (dateInfo.stock !== undefined && Number(dateInfo.stock) <= 0) {
|
||||
uni.showToast({ title: "所选日期库存不足,请选择其他日期", icon: "none" });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
rangeStart.value = dateInfo.date;
|
||||
rangeEnd.value = null;
|
||||
isRangeSelecting.value = true;
|
||||
} else {
|
||||
// 完成范围选择
|
||||
rangeEnd.value = dateInfo.date;
|
||||
return;
|
||||
}
|
||||
|
||||
// 否则为结束日期(完成选择)——结束日允许无价格(如为紧接有价日的下一天),但区间内的夜晚必须有价格
|
||||
rangeEnd.value = dateInfo.date;
|
||||
isRangeSelecting.value = false;
|
||||
|
||||
// 允许选择相同日期,但确保开始日期不大于结束日期
|
||||
if (new Date(rangeStart.value) > new Date(rangeEnd.value)) {
|
||||
[rangeStart.value, rangeEnd.value] = [rangeEnd.value, rangeStart.value];
|
||||
}
|
||||
|
||||
// 检查日期跨度是否超过28天
|
||||
const daysBetween = calculateDaysBetween(rangeStart.value, rangeEnd.value);
|
||||
if (daysBetween > 28) {
|
||||
uni.showToast({ title: "预定时间不能超过28天", icon: "none", duration: 3000 });
|
||||
rangeStart.value = null;
|
||||
rangeEnd.value = null;
|
||||
isRangeSelecting.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// 允许选择相同日期,但确保开始日期不大于结束日期
|
||||
if (new Date(rangeStart.value) > new Date(rangeEnd.value)) {
|
||||
[rangeStart.value, rangeEnd.value] = [rangeEnd.value, rangeStart.value];
|
||||
}
|
||||
|
||||
// 检查日期跨度是否超过28天(相同日期跨度为0天,允许通过)
|
||||
const daysBetween = calculateDaysBetween(rangeStart.value, rangeEnd.value);
|
||||
if (daysBetween > 28) {
|
||||
// 使用uni.showToast显示错误提示
|
||||
uni.showToast({
|
||||
title: "预定时间不能超过28天",
|
||||
icon: "none",
|
||||
duration: 3000,
|
||||
});
|
||||
|
||||
// 重置选择状态
|
||||
// 如果作为价格区间选择器,验证夜晚(不包含离店日)是否都有价格/库存
|
||||
if (props.rangeRequirePrice) {
|
||||
const nights = generateNightsRange(rangeStart.value, rangeEnd.value);
|
||||
const missing = nights.find((d) => d.price === null || d.price === undefined || d.price === "-");
|
||||
if (missing) {
|
||||
uni.showToast({ title: "所选区间包含无价格日期,请重新选择", icon: "none" });
|
||||
rangeStart.value = null;
|
||||
rangeEnd.value = null;
|
||||
isRangeSelecting.value = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 生成范围内所有日期的数组
|
||||
const dateRange = generateDateRange(rangeStart.value, rangeEnd.value);
|
||||
|
||||
emit("range-select", {
|
||||
startDate: rangeStart.value,
|
||||
endDate: rangeEnd.value,
|
||||
startPrice: getPriceForDate(rangeStart.value),
|
||||
endPrice: getPriceForDate(rangeEnd.value),
|
||||
totalDays: daysBetween,
|
||||
dateRange: dateRange, // 新增:范围内所有日期的数组
|
||||
const badStock = nights.find((d) => {
|
||||
const item = getPriceItem(d.date);
|
||||
return item && item.stock !== undefined && Number(item.stock) <= 0;
|
||||
});
|
||||
if (badStock) {
|
||||
uni.showToast({ title: "所选区间包含库存不足的日期,请重新选择", icon: "none" });
|
||||
rangeStart.value = null;
|
||||
rangeEnd.value = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const dateRange = generateDateRange(rangeStart.value, rangeEnd.value);
|
||||
|
||||
emit("range-select", {
|
||||
startDate: rangeStart.value,
|
||||
startPrice: getPriceForDate(rangeStart.value),
|
||||
endDate: rangeEnd.value,
|
||||
endPrice: getPriceForDate(rangeEnd.value),
|
||||
totalDays: daysBetween,
|
||||
dateRange: dateRange,
|
||||
});
|
||||
};
|
||||
|
||||
// 生成日期范围内所有日期的数组
|
||||
@@ -437,6 +505,32 @@ const generateDateRange = (startDate, endDate) => {
|
||||
return dateRange;
|
||||
};
|
||||
|
||||
// 生成以入住日期为开始、离店日期为结束(离店日不计入夜)的夜晚数组
|
||||
const generateNightsRange = (startDate, endDate) => {
|
||||
const nights = [];
|
||||
const start = new Date(startDate);
|
||||
const end = new Date(endDate);
|
||||
|
||||
// 若相同日期,视为单晚(保留原有兼容行为)
|
||||
if (startDate === endDate) {
|
||||
return [
|
||||
{
|
||||
date: startDate,
|
||||
price: getPriceForDate(startDate),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const current = new Date(start);
|
||||
while (current < end) {
|
||||
const dateStr = current.toISOString().split("T")[0];
|
||||
nights.push({ date: dateStr, price: getPriceForDate(dateStr) });
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
|
||||
return nights;
|
||||
};
|
||||
|
||||
// 计算两个日期之间的天数
|
||||
const calculateDaysBetween = (startDate, endDate) => {
|
||||
const start = new Date(startDate);
|
||||
|
||||
@@ -251,6 +251,24 @@ $font-size-label: 10px;
|
||||
min-height: 14px;
|
||||
}
|
||||
|
||||
// 无价格占位样式
|
||||
.date-cell-no-price {
|
||||
.date-number {
|
||||
color: $text-primary;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.date-price {
|
||||
color: $text-disabled;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.date-price--empty {
|
||||
color: $text-disabled;
|
||||
font-style: normal;
|
||||
}
|
||||
}
|
||||
|
||||
// 自定义标签
|
||||
.date-label {
|
||||
font-size: $font-size-label;
|
||||
|
||||
@@ -12,7 +12,7 @@ import rawConfigs from '../../client-configs.json' with { type: 'json' };
|
||||
export const CLIENT_CONFIGS = rawConfigs;
|
||||
|
||||
// 获取当前用户端配置
|
||||
export const getCurrentConfig = () => CLIENT_CONFIGS.duohua;
|
||||
export const getCurrentConfig = () => CLIENT_CONFIGS.zhinian;
|
||||
export const clientId = getCurrentConfig().clientId;
|
||||
export const appId = getCurrentConfig().appId;
|
||||
|
||||
@@ -42,4 +42,4 @@ export const currentClientType = () => {
|
||||
};
|
||||
|
||||
// 环境配置 - 智念客户端使用测试环境,其他客户端使用生产环境
|
||||
export const isProd = currentClientType() !== ClientType.ZHINIAN;
|
||||
export const isZhiNian = currentClientType() === ClientType.ZHINIAN;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { wxLogin, checkUserPhone } from "@/request/api/LoginApi";
|
||||
import { oauthToken, checkUserPhone } from "@/request/api/LoginApi";
|
||||
import { loginAuth, bindPhone } from "@/manager/LoginManager";
|
||||
import { clientId } from "@/constant/base";
|
||||
import { getAccessToken, removeAccessToken, setAccessToken } from "../constant/token";
|
||||
import { NOTICE_EVENT_LOGIN_SUCCESS } from "@/constant/constant";
|
||||
import { getAccessToken, setAccessToken } from "../constant/token";
|
||||
|
||||
// 跳转登录
|
||||
export const goLogin = () => uni.navigateTo({ url: "/pages/login/index" });
|
||||
@@ -41,7 +41,13 @@ export const onLogin = async (e) => {
|
||||
const params = { wechatPhoneCode: code, clientId: clientId };
|
||||
const res = await bindPhone(params);
|
||||
if (res.data) {
|
||||
// 登录成功后,触发登录成功事件
|
||||
uni.$emit(NOTICE_EVENT_LOGIN_SUCCESS);
|
||||
resolve();
|
||||
} else {
|
||||
console.log("绑定手机号失败");
|
||||
removeAccessToken();
|
||||
reject();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -62,7 +68,7 @@ export const checkToken = () => {
|
||||
};
|
||||
|
||||
// 刷新token
|
||||
export const refreshToken = (needLogin = false) => {
|
||||
export const refreshToken = () => {
|
||||
return new Promise(async (resolve) => {
|
||||
uni.login({
|
||||
provider: "weixin", //使用微信登录
|
||||
@@ -76,13 +82,10 @@ export const refreshToken = (needLogin = false) => {
|
||||
};
|
||||
console.log("获取到的微信授权params:", JSON.stringify(params));
|
||||
|
||||
const response = await wxLogin(params);
|
||||
|
||||
if (needLogin && response.access_token) {
|
||||
setAccessToken(response.access_token);
|
||||
}
|
||||
|
||||
const response = await oauthToken(params);
|
||||
if (response.access_token) {
|
||||
setAccessToken(response.access_token);
|
||||
|
||||
const checkRes = await checkUserPhone({
|
||||
token: response.access_token,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { wxLogin, bindUserPhone } from "../request/api/LoginApi";
|
||||
import { oauthToken, bindUserPhone } from "../request/api/LoginApi";
|
||||
import { getWeChatAuthCode } from "./AuthManager";
|
||||
import { clientId } from "@/constant/base";
|
||||
import { NOTICE_EVENT_LOGIN_SUCCESS } from "@/constant/constant";
|
||||
@@ -17,15 +17,11 @@ const loginAuth = (e) => {
|
||||
clientId: clientId,
|
||||
};
|
||||
console.log("获取到的微信授权params:", JSON.stringify(params));
|
||||
const response = await wxLogin(params);
|
||||
const response = await oauthToken(params);
|
||||
console.log("获取到的微信授权response:", response);
|
||||
|
||||
if (response.access_token) {
|
||||
console.log("进入条件");
|
||||
setAccessToken(response.access_token);
|
||||
|
||||
// 登录成功后,触发登录成功事件
|
||||
uni.$emit(NOTICE_EVENT_LOGIN_SUCCESS);
|
||||
resolve();
|
||||
} else {
|
||||
reject(response.message || "登录失败");
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
朵花:wx23f86d809ae80259
|
||||
*/
|
||||
"mp-weixin": {
|
||||
"appid": "wx23f86d809ae80259",
|
||||
"appid": "wx5e79df5996572539",
|
||||
"setting": {
|
||||
"urlCheck": false,
|
||||
"minified": true
|
||||
|
||||
@@ -65,8 +65,9 @@
|
||||
<!-- 日历组件 -->
|
||||
<Calender
|
||||
:visible="calendarVisible"
|
||||
:price-data="priceData"
|
||||
mode="range"
|
||||
:range-require-price="true"
|
||||
:price-data="priceData"
|
||||
@close="handleCalendarClose"
|
||||
@range-select="handleDateSelect"
|
||||
/>
|
||||
@@ -107,7 +108,8 @@ const selectedDate = ref({
|
||||
endDate: DateUtils.formatDate(new Date(Date.now() + 24 * 60 * 60 * 1000)), // 第二天日期
|
||||
totalDays: 1,
|
||||
});
|
||||
const priceData = ref([]);
|
||||
|
||||
const priceData = ref([])
|
||||
|
||||
// 计算的总价格
|
||||
const calculatedTotalPrice = ref(0);
|
||||
|
||||
@@ -148,8 +148,21 @@ let commonType = "";
|
||||
|
||||
// WebSocket 相关
|
||||
let webSocketManager = null;
|
||||
/// WebSocket 连接状态
|
||||
let webSocketConnectStatus = false;
|
||||
/// 使用统一的连接状态判断函数,避免状态不同步
|
||||
const isWsConnected = () => !!(webSocketManager && typeof webSocketManager.isConnected === "function" && webSocketManager.isConnected());
|
||||
|
||||
// pendingMap: messageId -> msgIndex
|
||||
const pendingMap = new Map();
|
||||
// pendingTimeouts: messageId -> timeoutId
|
||||
const pendingTimeouts = new Map();
|
||||
// 超时时间(ms)
|
||||
const MESSAGE_TIMEOUT = 30000;
|
||||
|
||||
// 防止并发初始化 websocket
|
||||
let isInitializing = false;
|
||||
let pendingInitPromise = null;
|
||||
// sleep helper
|
||||
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
|
||||
|
||||
// 当前会话的消息ID,用于保持发送和终止的messageId一致
|
||||
let currentSessionMessageId = null;
|
||||
@@ -251,7 +264,7 @@ const sendMessageAction = (inputText) => {
|
||||
/// 添加通知
|
||||
const addNoticeListener = () => {
|
||||
uni.$on(NOTICE_EVENT_LOGIN_SUCCESS, () => {
|
||||
if (!webSocketConnectStatus) {
|
||||
if (!isWsConnected()) {
|
||||
initHandler();
|
||||
}
|
||||
});
|
||||
@@ -355,90 +368,136 @@ const getMainPageData = async () => {
|
||||
/// =============对话↓================
|
||||
// 初始化WebSocket
|
||||
const initWebSocket = async () => {
|
||||
// 清理旧实例
|
||||
if (webSocketManager) {
|
||||
webSocketManager.destroy();
|
||||
// 防止并发初始化
|
||||
if (isInitializing) {
|
||||
return pendingInitPromise;
|
||||
}
|
||||
|
||||
// 使用配置的WebSocket服务器地址
|
||||
const token = getAccessToken();
|
||||
const wsUrl = `${appStore.serverConfig.wssUrl}?access_token=${token}`;
|
||||
isInitializing = true;
|
||||
pendingInitPromise = (async () => {
|
||||
// 清理旧实例
|
||||
if (webSocketManager) {
|
||||
try {
|
||||
webSocketManager.destroy();
|
||||
} catch (e) {
|
||||
console.warn("destroy old webSocketManager failed:", e);
|
||||
}
|
||||
webSocketManager = null;
|
||||
}
|
||||
|
||||
// 初始化WebSocket管理器
|
||||
webSocketManager = new WebSocketManager({
|
||||
wsUrl: wsUrl,
|
||||
reconnectInterval: 3000, // 重连间隔
|
||||
maxReconnectAttempts: 5, // 最大重连次数
|
||||
heartbeatInterval: 30000, // 心跳间隔
|
||||
// 使用配置的WebSocket服务器地址
|
||||
const token = getAccessToken();
|
||||
const wsUrl = `${appStore.serverConfig.wssUrl}?access_token=${token}`;
|
||||
|
||||
// 连接成功回调
|
||||
onOpen: (event) => {
|
||||
console.log("WebSocket连接成功");
|
||||
// 重置会话状态
|
||||
webSocketConnectStatus = true;
|
||||
isSessionActive.value = false; // 连接成功时重置会话状态,避免影响新消息发送
|
||||
},
|
||||
// 初始化WebSocket管理器
|
||||
webSocketManager = new WebSocketManager({
|
||||
wsUrl: wsUrl,
|
||||
reconnectInterval: 3000, // 重连间隔
|
||||
maxReconnectAttempts: 5, // 最大重连次数
|
||||
heartbeatInterval: 30000, // 心跳间隔
|
||||
|
||||
// 连接断开回调
|
||||
onClose: (event) => {
|
||||
console.error("WebSocket连接断开:", event);
|
||||
webSocketConnectStatus = false;
|
||||
// 停止当前会话
|
||||
isSessionActive.value = false;
|
||||
},
|
||||
// 连接成功回调
|
||||
onOpen: (event) => {
|
||||
console.log("WebSocket连接成功");
|
||||
// 重置会话状态
|
||||
isSessionActive.value = false; // 连接成功时重置会话状态,避免影响新消息发送
|
||||
},
|
||||
|
||||
// 错误回调
|
||||
onError: (error) => {
|
||||
console.error("WebSocket错误:", error);
|
||||
webSocketConnectStatus = false;
|
||||
isSessionActive.value = false;
|
||||
},
|
||||
// 连接断开回调
|
||||
onClose: (event) => {
|
||||
console.error("WebSocket连接断开:", event);
|
||||
// 停止当前会话
|
||||
isSessionActive.value = false;
|
||||
},
|
||||
|
||||
// 消息回调
|
||||
onMessage: (data) => {
|
||||
handleWebSocketMessage(data);
|
||||
},
|
||||
// 错误回调
|
||||
onError: (error) => {
|
||||
console.error("WebSocket错误:", error);
|
||||
isSessionActive.value = false;
|
||||
},
|
||||
|
||||
// 获取会话ID回调 (用于心跳检测)
|
||||
getConversationId: () => conversationId.value,
|
||||
// 消息回调
|
||||
onMessage: (data) => {
|
||||
handleWebSocketMessage(data);
|
||||
},
|
||||
|
||||
// 获取代理ID回调 (用于心跳检测)
|
||||
getAgentId: () => agentId.value,
|
||||
});
|
||||
// 获取会话ID回调 (用于心跳检测)
|
||||
getConversationId: () => conversationId.value,
|
||||
|
||||
try {
|
||||
// 初始化连接
|
||||
await webSocketManager.connect();
|
||||
console.log("WebSocket连接初始化成功");
|
||||
webSocketConnectStatus = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("WebSocket连接失败:", error);
|
||||
webSocketConnectStatus = false;
|
||||
return false;
|
||||
}
|
||||
// 获取代理ID回调 (用于心跳检测)
|
||||
getAgentId: () => agentId.value,
|
||||
});
|
||||
|
||||
try {
|
||||
// 初始化连接
|
||||
await webSocketManager.connect();
|
||||
console.log("WebSocket连接初始化成功");
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("WebSocket连接失败:", error);
|
||||
return false;
|
||||
} finally {
|
||||
isInitializing = false;
|
||||
pendingInitPromise = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return pendingInitPromise;
|
||||
};
|
||||
|
||||
// 处理WebSocket消息
|
||||
const handleWebSocketMessage = (data) => {
|
||||
const aiMsgIndex = chatMsgList.value.length - 1;
|
||||
if (!chatMsgList.value[aiMsgIndex] || aiMsgIndex < 0) {
|
||||
console.error("处理WebSocket消息时找不到对应的AI消息项");
|
||||
// 验证关键字段(若服务端传回 conversationId/agentId,则校验是否属于当前会话)
|
||||
if (data.conversationId && data.conversationId !== conversationId.value) {
|
||||
console.warn("收到不属于当前会话的消息,忽略", data.conversationId);
|
||||
return;
|
||||
}
|
||||
if (data.agentId && data.agentId !== agentId.value) {
|
||||
console.warn("收到不属于当前 agent 的消息,忽略", data.agentId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 确保消息内容是字符串类型
|
||||
if (data.content && typeof data.content !== "string") {
|
||||
data.content = String(data.content);
|
||||
try {
|
||||
data.content = JSON.stringify(data.content);
|
||||
} catch (e) {
|
||||
data.content = String(data.content);
|
||||
}
|
||||
}
|
||||
|
||||
// 直接拼接内容到AI消息
|
||||
// 优先使用 messageId 进行匹配
|
||||
const msgId = data.messageId || data.id || data.msgId;
|
||||
let aiMsgIndex = -1;
|
||||
if (msgId && pendingMap.has(msgId)) {
|
||||
aiMsgIndex = pendingMap.get(msgId);
|
||||
} else if (!msgId && currentSessionMessageId && pendingMap.has(currentSessionMessageId)) {
|
||||
// 服务端未返回 messageId 的场景:优先使用当前会话的 messageId 映射
|
||||
aiMsgIndex = pendingMap.get(currentSessionMessageId);
|
||||
} else {
|
||||
// 向后搜索最近的 AI 消息
|
||||
for (let i = chatMsgList.value.length - 1; i >= 0; i--) {
|
||||
if (chatMsgList.value[i] && chatMsgList.value[i].msgType === MessageRole.AI) {
|
||||
aiMsgIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (aiMsgIndex === -1) {
|
||||
console.error("处理WebSocket消息时找不到对应的AI消息项");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 直接拼接内容到对应 AI 消息
|
||||
if (data.content) {
|
||||
if (chatMsgList.value[aiMsgIndex].isLoading) {
|
||||
chatMsgList.value[aiMsgIndex].msg = "";
|
||||
// 首次收到内容:替换“加载中”文案并取消 loading 状态(恢复原始渲染逻辑)
|
||||
chatMsgList.value[aiMsgIndex].msg = data.content;
|
||||
chatMsgList.value[aiMsgIndex].isLoading = false;
|
||||
} else {
|
||||
// 后续流式内容追加
|
||||
chatMsgList.value[aiMsgIndex].msg += data.content;
|
||||
}
|
||||
chatMsgList.value[aiMsgIndex].msg += data.content;
|
||||
chatMsgList.value[aiMsgIndex].isLoading = false;
|
||||
nextTick(() => scrollToBottom());
|
||||
}
|
||||
|
||||
@@ -463,8 +522,20 @@ const handleWebSocketMessage = (data) => {
|
||||
chatMsgList.value[aiMsgIndex].question = data.question;
|
||||
}
|
||||
|
||||
// 清理 pendingMap / timeout
|
||||
const ownedMessageId = chatMsgList.value[aiMsgIndex].messageId || msgId;
|
||||
if (ownedMessageId) {
|
||||
if (pendingTimeouts.has(ownedMessageId)) {
|
||||
clearTimeout(pendingTimeouts.get(ownedMessageId));
|
||||
pendingTimeouts.delete(ownedMessageId);
|
||||
}
|
||||
pendingMap.delete(ownedMessageId);
|
||||
}
|
||||
|
||||
// 重置会话状态
|
||||
isSessionActive.value = false;
|
||||
// 清理当前会话的 messageId,避免保留陈旧 id
|
||||
resetMessageState();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -491,7 +562,7 @@ const sendMessage = async (message, isInstruct = false) => {
|
||||
await checkToken();
|
||||
|
||||
// 检查WebSocket连接状态,如果未连接,尝试重新连接
|
||||
if (!webSocketConnectStatus) {
|
||||
if (!isWsConnected()) {
|
||||
console.log("WebSocket未连接,尝试重新连接...");
|
||||
// 显示加载提示
|
||||
uni.showLoading({
|
||||
@@ -505,7 +576,7 @@ const sendMessage = async (message, isInstruct = false) => {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// 检查连接是否成功建立
|
||||
if (!webSocketConnectStatus) {
|
||||
if (!isWsConnected()) {
|
||||
uni.hideLoading();
|
||||
uni.showToast({
|
||||
title: "连接服务器失败,请稍后重试",
|
||||
@@ -550,49 +621,113 @@ const sendMessage = async (message, isInstruct = false) => {
|
||||
console.log("发送的新消息:", JSON.stringify(newMsg));
|
||||
};
|
||||
|
||||
// 通用WebSocket消息发送函数
|
||||
const sendWebSocketMessage = (messageType, messageContent, options = {}) => {
|
||||
// 通用WebSocket消息发送函数 -> 返回 Promise<boolean>
|
||||
const sendWebSocketMessage = async (messageType, messageContent, options = {}) => {
|
||||
const args = {
|
||||
conversationId: conversationId.value,
|
||||
agentId: agentId.value,
|
||||
messageType: String(messageType), // 消息类型 0-对话 1-指令 2-中断停止 3-心跳检测
|
||||
messageContent: messageContent,
|
||||
messageId: currentSessionMessageId,
|
||||
messageId: options.messageId || currentSessionMessageId,
|
||||
};
|
||||
|
||||
try {
|
||||
// 直接调用webSocketManager的sendMessage方法,利用其内部的消息队列机制
|
||||
// 即使当前连接断开,消息也会被加入队列,等待连接恢复后发送
|
||||
const result = webSocketManager.sendMessage(args);
|
||||
console.log(`WebSocket消息已发送 [类型:${messageType}]:`, args);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error("发送WebSocket消息失败:", error);
|
||||
const maxRetries = typeof options.retries === 'number' ? options.retries : 3;
|
||||
const baseDelay = typeof options.baseDelay === 'number' ? options.baseDelay : 300; // ms
|
||||
const maxDelay = typeof options.maxDelay === 'number' ? options.maxDelay : 5000; // ms
|
||||
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
// 确保连接
|
||||
if (!isWsConnected()) {
|
||||
if (options.tryReconnect) {
|
||||
try {
|
||||
await initWebSocket();
|
||||
} catch (e) {
|
||||
console.error('reconnect failed in sendWebSocketMessage:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isWsConnected()) {
|
||||
if (!options.silent) console.warn('WebSocket 未连接,无法发送消息', args);
|
||||
// 如果还有重试机会,进行等待后重试
|
||||
if (attempt < maxRetries) {
|
||||
const delay = Math.min(maxDelay, baseDelay * Math.pow(2, attempt));
|
||||
await sleep(delay);
|
||||
continue;
|
||||
}
|
||||
isSessionActive.value = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = webSocketManager.sendMessage(args);
|
||||
// 兼容可能返回同步布尔或 Promise 的实现
|
||||
const result = await Promise.resolve(raw);
|
||||
if (result) {
|
||||
console.log(`WebSocket消息已发送 [类型:${messageType}]:`, args);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 若返回 false,消息可能已经被 manager 入队并触发连接流程。
|
||||
// 在这种情况下避免立即当作失败处理,而是等待短暂时间以观察连接是否建立并由 manager 发送队列。
|
||||
console.warn('webSocketManager.sendMessage 返回 false,等待连接或队列发送...', { attempt, args });
|
||||
const waitForConnectMs = typeof options.waitForConnectMs === 'number' ? options.waitForConnectMs : 5000;
|
||||
if (webSocketManager && typeof webSocketManager.isConnected === 'function' && !webSocketManager.isConnected()) {
|
||||
const startTs = Date.now();
|
||||
while (Date.now() - startTs < waitForConnectMs) {
|
||||
await sleep(200);
|
||||
if (webSocketManager.isConnected()) {
|
||||
// 给 manager 一点时间处理队列并发送
|
||||
await sleep(150);
|
||||
console.log('检测到 manager 已连接,假定队列消息已发送', args);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
console.warn('等待 manager 建连超时,进入重试逻辑', { waitForConnectMs, args });
|
||||
} else {
|
||||
console.warn('sendMessage 返回 false 但 manager 看起来已连接或不可用,继续重试', { args });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('发送WebSocket消息异常:', error, args);
|
||||
}
|
||||
|
||||
// 失败且还有重试机会,等待指数退避
|
||||
if (attempt < maxRetries) {
|
||||
const delay = Math.min(maxDelay, baseDelay * Math.pow(2, attempt));
|
||||
await sleep(delay + Math.floor(Math.random() * 100));
|
||||
continue;
|
||||
}
|
||||
|
||||
// 最后一次失败
|
||||
isSessionActive.value = false;
|
||||
return false;
|
||||
}
|
||||
// 不可达,但为了类型安全
|
||||
isSessionActive.value = false;
|
||||
return false;
|
||||
};
|
||||
|
||||
// 发送获取AI聊天消息
|
||||
const sendChat = (message, isInstruct = false) => {
|
||||
const sendChat = async (message, isInstruct = false) => {
|
||||
// 检查WebSocket管理器是否存在,如果不存在,尝试重新初始化
|
||||
if (!webSocketManager) {
|
||||
console.error("WebSocket管理器不存在,尝试重新初始化...");
|
||||
initWebSocket();
|
||||
// 短暂延迟后再次检查连接状态
|
||||
setTimeout(() => {
|
||||
if (webSocketManager && webSocketManager.isConnected()) {
|
||||
const connected = webSocketManager && webSocketManager.isConnected();
|
||||
isSessionActive.value = connected;
|
||||
// 更新AI消息状态
|
||||
const aiMsgIndex = chatMsgList.value.length - 1;
|
||||
if (aiMsgIndex >= 0 && chatMsgList.value[aiMsgIndex].msgType === MessageRole.AI) {
|
||||
chatMsgList.value[aiMsgIndex].msg = connected ? "" : "发送消息失败,请重试";
|
||||
chatMsgList.value[aiMsgIndex].isLoading = connected;
|
||||
}
|
||||
if (connected) {
|
||||
// 连接成功后重新发送消息
|
||||
sendChat(message, isInstruct);
|
||||
} else {
|
||||
console.error("WebSocket重新初始化失败");
|
||||
isSessionActive.value = false;
|
||||
// 更新AI消息状态为失败
|
||||
const aiMsgIndex = chatMsgList.value.length - 1;
|
||||
if (aiMsgIndex >= 0 && chatMsgList.value[aiMsgIndex].msgType === MessageRole.AI) {
|
||||
chatMsgList.value[aiMsgIndex].msg = "发送消息失败,请重试";
|
||||
chatMsgList.value[aiMsgIndex].isLoading = false;
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
return;
|
||||
@@ -600,12 +735,10 @@ const sendChat = (message, isInstruct = false) => {
|
||||
|
||||
const messageType = isInstruct ? 1 : 0;
|
||||
const messageContent = isInstruct ? commonType : message;
|
||||
// 生成 messageId 并保存到当前会话变量(stopRequest 可能使用)
|
||||
currentSessionMessageId = IdUtils.generateMessageId();
|
||||
|
||||
// 重置消息状态,为新消息做准备
|
||||
resetMessageState();
|
||||
|
||||
// 插入AI消息
|
||||
// 插入AI消息,并在 pendingMap 中记录
|
||||
const aiMsg = {
|
||||
msgId: `msg_${chatMsgList.value.length}`,
|
||||
msgType: MessageRole.AI,
|
||||
@@ -615,47 +748,88 @@ const sendChat = (message, isInstruct = false) => {
|
||||
type: MessageType.TEXT,
|
||||
url: "",
|
||||
},
|
||||
messageId: currentSessionMessageId,
|
||||
};
|
||||
chatMsgList.value.push(aiMsg);
|
||||
// 添加AI消息后滚动到底部
|
||||
setTimeoutScrollToBottom();
|
||||
const aiMsgIndex = chatMsgList.value.length - 1;
|
||||
|
||||
// 发送消息
|
||||
const success = sendWebSocketMessage(messageType, messageContent);
|
||||
// 记录 pendingMap
|
||||
pendingMap.set(currentSessionMessageId, aiMsgIndex);
|
||||
|
||||
// 启动超时回退
|
||||
const timeoutId = setTimeout(() => {
|
||||
const idx = pendingMap.get(currentSessionMessageId);
|
||||
if (idx != null && chatMsgList.value[idx] && chatMsgList.value[idx].isLoading) {
|
||||
chatMsgList.value[idx].msg = "请求超时,请重试";
|
||||
chatMsgList.value[idx].isLoading = false;
|
||||
pendingMap.delete(currentSessionMessageId);
|
||||
pendingTimeouts.delete(currentSessionMessageId);
|
||||
isSessionActive.value = false;
|
||||
setTimeoutScrollToBottom();
|
||||
}
|
||||
}, MESSAGE_TIMEOUT);
|
||||
pendingTimeouts.set(currentSessionMessageId, timeoutId);
|
||||
|
||||
// 发送消息,支持重连尝试
|
||||
const success = await sendWebSocketMessage(messageType, messageContent, { messageId: currentSessionMessageId, tryReconnect: true });
|
||||
if (!success) {
|
||||
chatMsgList.value[aiMsgIndex].msg = "发送消息失败,请重试";
|
||||
chatMsgList.value[aiMsgIndex].isLoading = false;
|
||||
const idx = pendingMap.get(currentSessionMessageId);
|
||||
if (idx != null && chatMsgList.value[idx]) {
|
||||
chatMsgList.value[idx].msg = "发送消息失败,请重试";
|
||||
chatMsgList.value[idx].isLoading = false;
|
||||
}
|
||||
// 清理 pending
|
||||
if (pendingTimeouts.has(currentSessionMessageId)) {
|
||||
clearTimeout(pendingTimeouts.get(currentSessionMessageId));
|
||||
pendingTimeouts.delete(currentSessionMessageId);
|
||||
}
|
||||
pendingMap.delete(currentSessionMessageId);
|
||||
isSessionActive.value = false;
|
||||
resetMessageState();
|
||||
}
|
||||
};
|
||||
|
||||
// 停止请求函数
|
||||
const stopRequest = () => {
|
||||
const stopRequest = async () => {
|
||||
console.log("停止请求");
|
||||
|
||||
// 发送中断消息给服务器 (messageType=2)
|
||||
sendWebSocketMessage(2, "stop_request", { silent: true });
|
||||
// 发送中断消息给服务器 (messageType=2),带上当前 messageId
|
||||
try {
|
||||
await sendWebSocketMessage(2, "stop_request", { messageId: currentSessionMessageId, silent: true });
|
||||
} catch (e) {
|
||||
console.warn("stopRequest send failed:", e);
|
||||
}
|
||||
|
||||
// 直接将AI消息状态设为停止
|
||||
const aiMsgIndex = chatMsgList.value.length - 1;
|
||||
if (
|
||||
chatMsgList.value[aiMsgIndex] &&
|
||||
chatMsgList.value[aiMsgIndex].msgType === MessageRole.AI
|
||||
) {
|
||||
// 直接将AI消息状态设为停止(优先使用 pendingMap 映射)
|
||||
let aiMsgIndex = -1;
|
||||
if (currentSessionMessageId && pendingMap.has(currentSessionMessageId)) {
|
||||
aiMsgIndex = pendingMap.get(currentSessionMessageId);
|
||||
} else {
|
||||
aiMsgIndex = chatMsgList.value.length - 1;
|
||||
}
|
||||
|
||||
if (chatMsgList.value[aiMsgIndex] &&
|
||||
chatMsgList.value[aiMsgIndex].msgType === MessageRole.AI) {
|
||||
chatMsgList.value[aiMsgIndex].isLoading = false;
|
||||
if (
|
||||
chatMsgList.value[aiMsgIndex].msg &&
|
||||
chatMsgList.value[aiMsgIndex].msg.trim() &&
|
||||
!chatMsgList.value[aiMsgIndex].msg.startsWith("加载中")
|
||||
) {
|
||||
if (chatMsgList.value[aiMsgIndex].msg &&
|
||||
chatMsgList.value[aiMsgIndex].msg.trim() &&
|
||||
!chatMsgList.value[aiMsgIndex].msg.startsWith("加载中")) {
|
||||
// 保留已显示内容
|
||||
} else {
|
||||
chatMsgList.value[aiMsgIndex].msg = "请求已停止";
|
||||
}
|
||||
}
|
||||
|
||||
// 清理 pending
|
||||
if (currentSessionMessageId) {
|
||||
if (pendingTimeouts.has(currentSessionMessageId)) {
|
||||
clearTimeout(pendingTimeouts.get(currentSessionMessageId));
|
||||
pendingTimeouts.delete(currentSessionMessageId);
|
||||
}
|
||||
pendingMap.delete(currentSessionMessageId);
|
||||
}
|
||||
|
||||
// 重置会话状态
|
||||
isSessionActive.value = false;
|
||||
setTimeoutScrollToBottom();
|
||||
@@ -677,13 +851,23 @@ const resetConfig = () => {
|
||||
if (webSocketManager) {
|
||||
webSocketManager.destroy();
|
||||
webSocketManager = null;
|
||||
webSocketConnectStatus = false;
|
||||
}
|
||||
|
||||
// 重置消息状态
|
||||
resetMessageState();
|
||||
isSessionActive.value = false;
|
||||
|
||||
// 清理 pendingMap / pendingTimeouts
|
||||
try {
|
||||
for (const t of pendingTimeouts.values()) {
|
||||
clearTimeout(t);
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
pendingTimeouts.clear();
|
||||
pendingMap.clear();
|
||||
|
||||
// 清理定时器
|
||||
if (holdKeyboardTimer.value) {
|
||||
clearTimeout(holdKeyboardTimer.value);
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
<template>
|
||||
<view
|
||||
class="quick-access flex flex-row ml-12 pt-8 pb-8 scroll-x whitespace-nowrap"
|
||||
>
|
||||
<view
|
||||
class="item border-box rounded-50 flex flex-row items-center"
|
||||
v-for="(item, index) in itemList"
|
||||
:key="index"
|
||||
@click="sendReply(item)"
|
||||
>
|
||||
<view class="quick-access flex flex-row ml-12 pt-8 pb-8 scroll-x whitespace-nowrap">
|
||||
<view class="item border-box rounded-50 flex flex-row items-center" v-for="(item, index) in itemList" :key="index"
|
||||
@click="sendReply(item)">
|
||||
<view class="flex items-center justify-center">
|
||||
<image v-if="item.icon" class="icon" :src="item.icon" />
|
||||
<text class="font-size-14 color-2D91FF line-height-20">
|
||||
@@ -22,6 +16,7 @@
|
||||
import { ref } from "vue";
|
||||
import { Command } from "@/model/ChatModel";
|
||||
import { SEND_MESSAGE_COMMAND_TYPE } from "@/constant/constant";
|
||||
import { checkToken } from "@/hooks/useGoLogin";
|
||||
|
||||
const itemList = ref([
|
||||
{
|
||||
@@ -55,7 +50,9 @@ const sendReply = (item) => {
|
||||
|
||||
// 快速预定
|
||||
if (item.type === Command.quickBooking) {
|
||||
uni.navigateTo({ url: "/pages-quick/list" });
|
||||
checkToken().then(() => {
|
||||
uni.navigateTo({ url: "/pages-quick/list" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,19 +2,12 @@
|
||||
<uni-popup ref="popup" type="bottom" :safe-area="false">
|
||||
<view class="popup-content border-box pt-12 pl-12 pr-12">
|
||||
<view class="header flex flex-items-center pb-12">
|
||||
<view
|
||||
class="title flex-full text-center font-size-17 color-000 font-500 ml-24"
|
||||
>更多服务</view
|
||||
>
|
||||
<view class="title flex-full text-center font-size-17 color-000 font-500 ml-24">更多服务</view>
|
||||
<uni-icons type="close" size="24" color="#CACFD8" @click="close" />
|
||||
</view>
|
||||
|
||||
<view class="list bg-white border-box pl-20 pr-20">
|
||||
<view
|
||||
class="item border-box border-bottom pt-20 pb-20"
|
||||
v-for="(item, index) in list"
|
||||
:key="index"
|
||||
>
|
||||
<view class="item border-box border-bottom pt-20 pb-20" v-for="(item, index) in list" :key="index">
|
||||
<view class="flex flex-items-center flex-justify-center">
|
||||
<image v-if="item.icon" class="left" :src="item.icon" />
|
||||
<view class="center flex-full">
|
||||
@@ -25,10 +18,7 @@
|
||||
{{ item.content }}
|
||||
</view>
|
||||
</view>
|
||||
<view
|
||||
class="right border-box font-size-12 color-white line-height-16"
|
||||
@click="handleClick(item)"
|
||||
>
|
||||
<view class="right border-box font-size-12 color-white line-height-16" @click="handleClick(item)">
|
||||
{{ item.btnText }}
|
||||
</view>
|
||||
</view>
|
||||
@@ -42,6 +32,7 @@
|
||||
import { ref } from "vue";
|
||||
import { Command } from "@/model/ChatModel";
|
||||
import { SEND_MESSAGE_COMMAND_TYPE } from "@/constant/constant";
|
||||
import { checkToken } from "@/hooks/useGoLogin";
|
||||
|
||||
const popup = ref(null);
|
||||
|
||||
@@ -100,7 +91,10 @@ const handleClick = (item) => {
|
||||
close();
|
||||
|
||||
if (item.path) {
|
||||
uni.navigateTo({ url: item.path });
|
||||
checkToken().then(() => {
|
||||
uni.navigateTo({ url: item.path });
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,9 +28,10 @@
|
||||
<!-- 按钮区域 -->
|
||||
<view class="login-btn-area">
|
||||
<!-- 同意隐私协议并获取手机号按钮 -->
|
||||
|
||||
<button class="login-btn" type="primary" :open-type="needWxLogin ? 'getPhoneNumber' : ''"
|
||||
@getphonenumber="getPhoneNumber" @click="handleAgreeAndGetPhone">
|
||||
<button v-if="needWxAuthLogin" class="login-btn" type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
|
||||
手机号快捷登录
|
||||
</button>
|
||||
<button v-else class="login-btn" type="primary" @click="handleAgreeAndGetPhone">
|
||||
手机号快捷登录
|
||||
</button>
|
||||
</view>
|
||||
@@ -52,7 +53,8 @@ import AgreePopup from "./components/AgreePopup/index.vue";
|
||||
import { zniconsMap } from "@/static/fonts/znicons";
|
||||
import { getCurrentConfig } from "@/constant/base";
|
||||
|
||||
const needWxLogin = ref(false);
|
||||
// 是否需要微信手机号授权登录
|
||||
const needWxAuthLogin = ref(false);
|
||||
const isAgree = ref(false);
|
||||
const visible = ref(false);
|
||||
const serviceAgreement = ref("");
|
||||
@@ -64,7 +66,7 @@ const logo = computed(() => getCurrentConfig().logo);
|
||||
// 同意隐私协议并获取手机号
|
||||
const handleAgreeAndGetPhone = () => {
|
||||
// 如果需要微信登录,直接返回
|
||||
if (needWxLogin.value) {
|
||||
if (needWxAuthLogin.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -76,19 +78,36 @@ const handleAgreeAndGetPhone = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
refreshToken(true).then(() => goBack());
|
||||
refreshToken().then(() => loginSuccess());
|
||||
};
|
||||
|
||||
/// 获取授权后绑定手机号登录
|
||||
const getPhoneNumber = (e) => {
|
||||
onLogin(e)
|
||||
.then(() => {
|
||||
if (!isAgree.value) {
|
||||
uni.showToast({
|
||||
title: "请先同意服务协议和隐私协议",
|
||||
icon: "none",
|
||||
});
|
||||
return;
|
||||
}
|
||||
onLogin(e).then(() => loginSuccess())
|
||||
.catch(() => {
|
||||
uni.showToast({
|
||||
title: "登录成功",
|
||||
icon: "success",
|
||||
title: "获取登录手机号失败",
|
||||
icon: "none",
|
||||
});
|
||||
goBack();
|
||||
})
|
||||
.catch(() => { });
|
||||
});
|
||||
};
|
||||
|
||||
/// 登录成功返回上一页
|
||||
const loginSuccess = () => {
|
||||
uni.showToast({
|
||||
title: "登录成功",
|
||||
icon: "success",
|
||||
});
|
||||
setTimeout(() => {
|
||||
goBack();
|
||||
}, 500);
|
||||
};
|
||||
|
||||
// 处理同意协议点击事件
|
||||
@@ -111,7 +130,6 @@ const getServiceAgreementData = async () => {
|
||||
const { data } = await getServiceAgreement();
|
||||
serviceAgreement.value = data;
|
||||
};
|
||||
|
||||
getServiceAgreementData();
|
||||
|
||||
// 获取隐私协议数据
|
||||
@@ -119,15 +137,15 @@ const getPrivacyAgreementData = async () => {
|
||||
const { data } = await getPrivacyAgreement();
|
||||
privacyAgreement.value = data;
|
||||
};
|
||||
|
||||
getPrivacyAgreementData();
|
||||
|
||||
// 页面显示时刷新token
|
||||
onShow(async () => {
|
||||
const res = await refreshToken();
|
||||
|
||||
needWxLogin.value = res;
|
||||
needWxAuthLogin.value = res;
|
||||
});
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import { removeAccessToken } from "@/constant/token";
|
||||
import request from "../base/request";
|
||||
|
||||
const wxLogin = (args) => {
|
||||
const oauthToken = (args) => {
|
||||
const config = {
|
||||
header: {
|
||||
Authorization: "Basic Y3VzdG9tOmN1c3RvbQ==", // 可在此动态设置 token
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
};
|
||||
|
||||
removeAccessToken();
|
||||
|
||||
return request.post("/auth/oauth2/token", args, config);
|
||||
};
|
||||
|
||||
@@ -40,7 +38,7 @@ const getPrivacyAgreement = (args) => {
|
||||
};
|
||||
|
||||
export {
|
||||
wxLogin,
|
||||
oauthToken,
|
||||
bindUserPhone,
|
||||
checkUserPhone,
|
||||
getLoginUserPhone,
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
import request from "../base/request";
|
||||
import { isProd } from "@/constant/base";
|
||||
import { isZhiNian } from "@/constant/base";
|
||||
import { useAppStore } from "@/store";
|
||||
import { devUrl, proUrl, wssDevUrl } from "../base/baseUrl";
|
||||
|
||||
/// 版本号, 每次发版本前增加
|
||||
const versionValue = "1.0.3";
|
||||
|
||||
// 获取服务地址
|
||||
const getEvnUrl = async (args) => {
|
||||
const res = await request.post("https://biz.nianxx.cn/hotelBiz/mainScene/getServiceUrl", args)
|
||||
const getEvnUrl = async () => {
|
||||
/// 智念客户端不需要获取环境地址
|
||||
if (isZhiNian) {
|
||||
const appStore = useAppStore();
|
||||
appStore.setServerConfig({
|
||||
baseUrl: devUrl, // 服务器基础地址
|
||||
wssUrl: wssDevUrl, // 服务器wss地址
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const apiUrl = proUrl + "/hotelBiz/mainScene/getServiceUrl";
|
||||
const res = await request.post(apiUrl, { versionValue: versionValue });
|
||||
if (res && res.code == 0 && res.data) {
|
||||
const appStore = useAppStore();
|
||||
appStore.setServerConfig(res.data);
|
||||
|
||||
@@ -1 +1,12 @@
|
||||
/// 生产环境基础地址
|
||||
export const proUrl = "https://biz.nianxx.cn";
|
||||
|
||||
/// 生产环境服务器wss地址
|
||||
export const wssProUrl = "wss://biz.nianxx.cn/ingress/agent/ws/chat";
|
||||
|
||||
/// 服务器基础地址
|
||||
export const devUrl = "https://onefeel.brother7.cn/ingress";
|
||||
|
||||
/// 测试服务器wss地址
|
||||
export const wssDevUrl = "wss://onefeel.brother7.cn/ingress/agent/ws/chat";
|
||||
|
||||
|
||||
@@ -59,9 +59,8 @@ function request(url, args = {}, method = "POST", customConfig = {}) {
|
||||
resolve(res.data);
|
||||
if (res.statusCode && res.statusCode === 424) {
|
||||
console.log("424错误,重新登录");
|
||||
// removeAccessToken();
|
||||
removeAccessToken();
|
||||
uni.$emit(NOTICE_EVENT_LOGOUT);
|
||||
// goLogin();
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { devUrl, wssDevUrl } from "../../request/base/baseUrl";
|
||||
|
||||
export const useAppStore = defineStore("app", {
|
||||
state() {
|
||||
@@ -6,10 +7,10 @@ export const useAppStore = defineStore("app", {
|
||||
title: "",
|
||||
sceneId: "", // 分身场景id
|
||||
previewImageData: [], // 预览图片数据
|
||||
serverConfig: {
|
||||
baseUrl: "https://onefeel.brother7.cn/ingress", // 服务器基础地址
|
||||
wssUrl: "wss://onefeel.brother7.cn/ingress/agent/ws/chat", // 服务器ws地址
|
||||
}, // 服务器配置
|
||||
serverConfig: { // 服务器配置
|
||||
baseUrl: devUrl, // 服务器基础地址
|
||||
wssUrl: wssDevUrl, // 服务器ws地址
|
||||
},
|
||||
};
|
||||
},
|
||||
getters: {},
|
||||
|
||||
@@ -28,10 +28,11 @@ export class WebSocketManager {
|
||||
|
||||
// 回调函数
|
||||
this.callbacks = {
|
||||
onConnect: options.onConnect || (() => {}),
|
||||
onDisconnect: options.onDisconnect || (() => {}),
|
||||
onError: options.onError || (() => {}),
|
||||
onMessage: options.onMessage || (() => {}),
|
||||
// 支持两套回调命名:onConnect/onDisconnect 与 onOpen/onClose(兼容调用方)
|
||||
onConnect: options.onConnect || options.onOpen || (() => { }),
|
||||
onDisconnect: options.onDisconnect || options.onClose || (() => { }),
|
||||
onError: options.onError || (() => { }),
|
||||
onMessage: options.onMessage || (() => { }),
|
||||
getConversationId: options.getConversationId || (() => ""),
|
||||
getAgentId: options.getAgentId || (() => ""),
|
||||
};
|
||||
@@ -327,7 +328,7 @@ export class WebSocketManager {
|
||||
const messageData = {
|
||||
...message,
|
||||
timestamp: Date.now(),
|
||||
retryCount: 0,
|
||||
retryCount: typeof message.retryCount === 'number' ? message.retryCount : 0,
|
||||
};
|
||||
|
||||
if (this.connectionState) {
|
||||
@@ -392,7 +393,7 @@ export class WebSocketManager {
|
||||
agentId: this.callbacks.getAgentId
|
||||
? this.callbacks.getAgentId()
|
||||
: "",
|
||||
messageType: 3, // 心跳检测
|
||||
messageType: '3', // 心跳检测
|
||||
messageContent: "heartbeat",
|
||||
messageId: IdUtils.generateMessageId(),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user