优化:请求接口全局处理loading和错误提示

This commit is contained in:
2025-11-26 16:37:47 +08:00
24 changed files with 568 additions and 771 deletions

View File

@@ -34,7 +34,7 @@ export function responseInterceptor(res: UniApp.RequestSuccessCallbackResult) {
} }
// 可能为字符串,尝试解析(原项目也做了类似处理) // 可能为字符串,尝试解析(原项目也做了类似处理)
let httpData: IApiResponse | string = res.data as any; let httpData: IApiResponse | string = res.data;
if (typeof httpData === 'string') { if (typeof httpData === 'string') {
try { try {
httpData = JSON.parse(httpData); httpData = JSON.parse(httpData);
@@ -44,19 +44,20 @@ export function responseInterceptor(res: UniApp.RequestSuccessCallbackResult) {
} }
// 规范化 message 字段 // 规范化 message 字段
const message = (httpData as any).msg || (httpData as any).message || (httpData as any).errMsg || ''; const message = (httpData as IApiResponse).msg || (httpData as IApiResponse).message || (httpData as IApiResponse).errMsg || '';
// 成功判断:与原项目一致的条件 const code = (httpData as IApiResponse).code;
const successFlag = (httpData as any).success === true || (httpData as any).code === 0;
// 成功判断
const successFlag = (httpData as IApiResponse).success === true || code === 0;
if (successFlag) { if (successFlag) {
// 返回原始 httpData(与原项目 dataFactory 返回 Promise.resolve(httpData) 保持一致) // 返回原始 httpData
// 但大多数调用者更关心 data 字段,这里返回整个 httpData调用者可取 .data // 实际数据每个接口不同,调用者需根据实际情况取 .data 字段
return Promise.resolve(httpData); return Promise.resolve(httpData);
} }
// 登录失效或需要强制登录的一些 code(与原项目一致) // 登录失效或需要强制登录的一些 code
const code = (httpData as any).code;
if (code === '401' || code === 401) { if (code === '401' || code === 401) {
// 触发登出流程 // 触发登出流程
handleAuthExpired(); handleAuthExpired();
@@ -64,7 +65,7 @@ export function responseInterceptor(res: UniApp.RequestSuccessCallbackResult) {
} }
// 原项目还将 1000,1001,1100,402 等视作需要强制登录 // 原项目还将 1000,1001,1100,402 等视作需要强制登录
if (code === '1000' || code === '1001' || code === 1000 || code === 1001 || code === 1100 || code === '402' || code === 402) { if (code == 1000 || code == 1001 || code === 1100 || code === 402) {
handleAuthExpired(); handleAuthExpired();
return Promise.reject({ statusCode: 0, errMsg: message || t('global.loginExpired'), data: httpData }); return Promise.reject({ statusCode: 0, errMsg: message || t('global.loginExpired'), data: httpData });
} }

View File

@@ -253,4 +253,16 @@ export async function getActivityDescription() {
method: 'POST' method: 'POST'
}) })
return res return res
}
/**
* 获取充值列表
*/
export async function getTransactionDetailsList(current: number, limit: number, userId: string,) {
const res = await mainClient.request<IApiResponse>({
url: 'common/transactionDetails/getTransactionDetailsList',
method: 'POST',
data: { current, limit, userId, }
})
return res
} }

View File

@@ -8,6 +8,7 @@ import { t } from '@/utils/i18n'
export function createRequestClient(cfg: ICreateClientConfig) { export function createRequestClient(cfg: ICreateClientConfig) {
const baseURL = cfg.baseURL; const baseURL = cfg.baseURL;
const timeout = cfg.timeout ?? REQUEST_TIMEOUT; const timeout = cfg.timeout ?? REQUEST_TIMEOUT;
let reqCount= 0
async function request<T = any>(options: IRequestOptions): Promise<T> { async function request<T = any>(options: IRequestOptions): Promise<T> {
// 组装 final options // 组装 final options
@@ -23,14 +24,18 @@ export function createRequestClient(cfg: ICreateClientConfig) {
// 全局处理请求 loading // 全局处理请求 loading
const loading = !cfg.loading ? true : cfg.loading // 接口请求参数不传loading默认显示loading const loading = !cfg.loading ? true : cfg.loading // 接口请求参数不传loading默认显示loading
loading && uni.showLoading() if (loading) {
uni.showLoading({ mask: true })
reqCount++
}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.request({ uni.request({
...intercepted, ...intercepted,
complete() { complete() {
// 请求完成关闭 loading // 请求完成关闭 loading
loading && uni.hideLoading() loading && reqCount--
reqCount <= 0 && uni.hideLoading()
}, },
success(res: any) { success(res: any) {
// 委托给响应拦截器处理 // 委托给响应拦截器处理

View File

@@ -90,7 +90,7 @@
<text class="label">{{ $t('order.total') }}</text> <text class="label">{{ $t('order.total') }}</text>
<text class="amount">{{ finalAmount }} {{ t('global.coin') }}</text> <text class="amount">{{ finalAmount }} {{ t('global.coin') }}</text>
</view> </view>
<wd-button type="primary" :loading="submitting" @click="handleSubmit"> <wd-button type="primary" @click="handleSubmit">
{{ $t('order.submit') }} {{ $t('order.submit') }}
</wd-button> </wd-button>
</view> </view>
@@ -170,12 +170,7 @@ const getDiscountParams = (goodsList: IGoods[]) => {
})) }))
} }
// 监听商品列表变化,更新价格
// 支付相关
// UI状态
const submitting = ref(false)
watch(() => props.goodsList, () => { watch(() => props.goodsList, () => {
getDiscountParams(props.goodsList) getDiscountParams(props.goodsList)
// 初始化价格 // 初始化价格
@@ -222,24 +217,16 @@ const calculateTotalPrice = () => {
* 计算VIP优惠 * 计算VIP优惠
*/ */
const calculateVipDiscounted = async () => { const calculateVipDiscounted = async () => {
try { const res = await orderApi.getVipDiscountAmount(goodsListParams.value)
const res = await orderApi.getVipDiscountAmount(goodsListParams.value) vipDiscounted.value = res.discountAmount
vipDiscounted.value = res.discountAmount
} catch (error) {
console.error('获取VIP优惠失败:', error)
}
} }
/** /**
* 计算活动优惠 * 计算活动优惠
*/ */
const calculatePromotionDiscounted = async () => { const calculatePromotionDiscounted = async () => {
try { const res = await orderApi.getDistrictAmount(goodsListParams.value)
const res = await orderApi.getDistrictAmount(goodsListParams.value) promotionDiscounted.value = res.districtAmount
promotionDiscounted.value = res.districtAmount
} catch (error) {
console.error('获取地区优惠失败:', error)
}
} }
/** /**
@@ -363,71 +350,45 @@ const validateOrder = (): boolean => {
/** /**
* 提交订单 * 提交订单
*/ */
const handleSubmit = async () => { const handleSubmit = async () => {
if (submitting.value) {
uni.showToast({
title: t('order.tooFrequent'),
icon: 'none'
})
return
}
// 验证订单 // 验证订单
if (!validateOrder()) return if (!validateOrder()) return
try {
submitting.value = true
// 创建订单 此app用天医币支付创建订单成功即支付成功
await createOrder()
uni.showToast({ // 创建订单 此app用天医币支付创建订单成功即支付成功
title: t('order.orderSuccess'), await createOrder()
icon: 'success'
}) uni.showToast({
title: t('order.orderSuccess'),
} catch (error) { icon: 'success'
console.error('提交订单失败:', error) })
uni.showToast({
title: t('order.orderFailed'),
icon: 'none'
})
} finally {
submitting.value = false
}
} }
/** /**
* 创建订单 * 创建订单
*/ */
const createOrder = async (): Promise<string | null> => { const createOrder = async (): Promise<string | null> => {
try { const orderParams = {
const orderParams = { userId: props.userInfo.id,
userId: props.userInfo.id, paymentMethod: 4, // 天医币
paymentMethod: 4, // 天医币 orderMoney: totalAmount.value,
orderMoney: totalAmount.value, realMoney: finalAmount.value,
realMoney: finalAmount.value, pointsDeduction: pointsDiscounted.value,
pointsDeduction: pointsDiscounted.value, // couponId: selectedCoupon.value?.id,
// couponId: selectedCoupon.value?.id, // couponName: selectedCoupon.value?.couponEntity.couponName,
// couponName: selectedCoupon.value?.couponEntity.couponName, vipDiscountAmount: vipDiscounted.value,
vipDiscountAmount: vipDiscounted.value, districtMoney: promotionDiscounted.value,
districtMoney: promotionDiscounted.value, remark: remark.value,
remark: remark.value, productList: goodsListParams.value,
productList: goodsListParams.value, orderType: props.orderType,
orderType: props.orderType, come: 10
come: 10
}
const res = await orderApi.placeCourseOrder(orderParams)
if (res.orderSn) {
return res.orderSn
}
return null
} catch (error) {
console.error('下单失败:', error)
throw error
} }
const res = await orderApi.placeCourseOrder(orderParams)
if (res.orderSn) {
return res.orderSn
}
return null
} }
</script> </script>

View File

@@ -208,7 +208,8 @@
"seasonCard": "Quarterly", "seasonCard": "Quarterly",
"yearCard": "Yearly", "yearCard": "Yearly",
"days": "days", "days": "days",
"selectPackage": "Please select a package" "selectPackage": "Please select a package",
"consumptionRecord": "Consumption record"
}, },
"book": { "book": {
"title": "My Books", "title": "My Books",
@@ -467,6 +468,11 @@
"couponType0": "All Products", "couponType0": "All Products",
"couponType1": "Specific Courses", "couponType1": "Specific Courses",
"couponType2": "Course Categories", "couponType2": "Course Categories",
"couponCount": "{count} coupons" "couponCount": "{count} coupons",
"rechargeConsumptionList": "Recharge and consumption records",
"rechargeAmount": "Recharge amount",
"valueAddedServices": "Value-added services",
"readAgree": "I have read and agreed",
"readAgreeServices": "Please read and agree to the value-added services first"
} }
} }

View File

@@ -209,7 +209,8 @@
"seasonCard": "季卡", "seasonCard": "季卡",
"yearCard": "年卡", "yearCard": "年卡",
"days": "天", "days": "天",
"selectPackage": "请选择套餐" "selectPackage": "请选择套餐",
"consumptionRecord": "消费记录"
}, },
"book": { "book": {
"title": "我的书单", "title": "我的书单",
@@ -468,6 +469,11 @@
"couponType0": "全场通用", "couponType0": "全场通用",
"couponType1": "指定课程可用", "couponType1": "指定课程可用",
"couponType2": "指定课程品类可用", "couponType2": "指定课程品类可用",
"couponCount": "共 {count} 张" "couponCount": "共 {count} 张",
"rechargeConsumptionList": "充值消费记录",
"rechargeAmount": "充值金额",
"valueAddedServices": "增值服务",
"readAgree": "我已阅读并同意",
"readAgreeServices": "请先阅读并同意增值服务"
} }
} }

View File

@@ -230,70 +230,43 @@ function initScrollHeight() {
// 加载书籍详情 // 加载书籍详情
async function loadBookInfo() { async function loadBookInfo() {
try { const res = await bookApi.getBookInfo(bookId.value)
const res = await bookApi.getBookInfo(bookId.value) bookInfo.value = res.bookInfo
if (res.bookInfo) {
bookInfo.value = res.bookInfo
}
} catch (error) {
console.error('Failed to load book info:', error)
}
} }
// 加载购买商品信息 // 加载购买商品信息
async function loadGoodsInfo() { async function loadGoodsInfo() {
try { const res = await bookApi.getBookGoods(bookId.value)
const res = await bookApi.getBookGoods(bookId.value) goodsList.value = res.productList || []
if (res.code === 0) {
goodsList.value = res.productList || []
}
} catch (error) {
console.error('Failed to load goods info:', error)
}
} }
// 加载统计数据 // 加载统计数据
async function loadBookCount() { async function loadBookCount() {
try { const res = await bookApi.getBookReadCount(bookId.value)
const res = await bookApi.getBookReadCount(bookId.value) if (res.code === 0) {
if (res.code === 0) { readCount.value = res.readCount || 0
readCount.value = res.readCount || 0 listenCount.value = res.listenCount || 0
listenCount.value = res.listenCount || 0 buyCount.value = res.buyCount || 0
buyCount.value = res.buyCount || 0
}
} catch (error) {
console.error('Failed to load book count:', error)
} }
} }
// 加载评论 // 加载评论
async function loadComments() { async function loadComments() {
try { const res = await bookApi.getBookComments(bookId.value, 1, 10)
const res = await bookApi.getBookComments(bookId.value, 1, 10) if (res.commentsTree && res.commentsTree.length > 0) {
if (res.commentsTree && res.commentsTree.length > 0) { commentList.value = res.commentsTree
commentList.value = res.commentsTree } else {
} else {
nullText.value = t('common.data_null')
}
} catch (error) {
nullText.value = t('common.data_null') nullText.value = t('common.data_null')
console.error('Failed to load comments:', error)
} }
} }
// 加载推荐书籍 // 加载推荐书籍
async function loadRecommendBooks() { async function loadRecommendBooks() {
try { const res = await bookApi.getRecommendBook(bookId.value)
const res = await bookApi.getRecommendBook(bookId.value) if (res.bookList && res.bookList.length > 0) {
if (res.bookList && res.bookList.length > 0) { relatedBooks.value = res.bookList
relatedBooks.value = res.bookList } else {
} else {
nullBookText.value = t('common.data_null')
}
} catch (error) {
nullBookText.value = t('common.data_null') nullBookText.value = t('common.data_null')
console.error('Failed to load recommend books:', error)
} }
} }

View File

@@ -219,13 +219,9 @@ const vipInfo = ref<IVipInfo | null>(null)
* 获取VIP信息 * 获取VIP信息
*/ */
const getVipInfo = async () => { const getVipInfo = async () => {
try { const res = await homeApi.getVipInfo()
const res = await homeApi.getVipInfo() if (res.vipInfo) {
if (res.vipInfo) { vipInfo.value = res.vipInfo
vipInfo.value = res.vipInfo
}
} catch (error) {
console.error('获取VIP信息失败:', error)
} }
} }
@@ -233,21 +229,17 @@ const getVipInfo = async () => {
* 获取我的书单 * 获取我的书单
*/ */
const getMyBooks = async () => { const getMyBooks = async () => {
try { const res = await homeApi.getMyBooks(1, 10)
const res = await homeApi.getMyBooks(1, 10) if (res && res.code === 0) {
if (res && res.code === 0) { showMyBooks.value = true
showMyBooks.value = true if (res.page.records && res.page.records.length > 0) {
if (res.page.records && res.page.records.length > 0) { myBooksList.value = res.page.records
myBooksList.value = res.page.records
}
} else {
// 未登录,跳转到登录页
uni.navigateTo({
url: '/pages/login/login'
})
} }
} catch (error) { } else {
console.error('获取我的书单失败:', error) // 未登录,跳转到登录页
uni.navigateTo({
url: '/pages/login/login'
})
} }
} }
@@ -255,13 +247,9 @@ const getMyBooks = async () => {
* 获取推荐图书 * 获取推荐图书
*/ */
const getRecommendBooks = async () => { const getRecommendBooks = async () => {
try { const res = await homeApi.getRecommendBooks()
const res = await homeApi.getRecommendBooks() if (res.books && res.books.length > 0) {
if (res.books && res.books.length > 0) { recommendBooksList.value = res.books
recommendBooksList.value = res.books
}
} catch (error) {
console.error('获取推荐图书失败:', error)
} }
} }
@@ -269,16 +257,12 @@ const getRecommendBooks = async () => {
* 获取活动标签列表 * 获取活动标签列表
*/ */
const getActivityLabels = async () => { const getActivityLabels = async () => {
try { const res = await homeApi.getBookLabelList(1)
const res = await homeApi.getBookLabelList(1) showActivity.value = true
showActivity.value = true if (res.lableList && res.lableList.length > 0) {
if (res.lableList && res.lableList.length > 0) { activityLabelList.value = res.lableList
activityLabelList.value = res.lableList // 默认加载第一个标签的图书列表
// 默认加载第一个标签的图书列表 await getBooksByLabel(res.lableList[0].id, 'activity')
await getBooksByLabel(res.lableList[0].id, 'activity')
}
} catch (error) {
console.error('获取活动标签失败:', error)
} }
} }
@@ -286,16 +270,12 @@ const getActivityLabels = async () => {
* 获取分类标签列表 * 获取分类标签列表
*/ */
const getCategoryLabels = async () => { const getCategoryLabels = async () => {
try { const res = await homeApi.getBookLabelList(0)
const res = await homeApi.getBookLabelList(0) showCategory.value = true
showCategory.value = true if (res.lableList && res.lableList.length > 0) {
if (res.lableList && res.lableList.length > 0) { categoryLevel1List.value = res.lableList
categoryLevel1List.value = res.lableList // 默认加载第一个标签的二级标签
// 默认加载第一个标签的二级标签 await getSubLabels(res.lableList[0].id, 0)
await getSubLabels(res.lableList[0].id, 0)
}
} catch (error) {
console.error('获取分类标签失败:', error)
} }
} }
@@ -303,21 +283,17 @@ const getCategoryLabels = async () => {
* 获取二级标签列表 * 获取二级标签列表
*/ */
const getSubLabels = async (pid: number, index: number) => { const getSubLabels = async (pid: number, index: number) => {
try { const res = await homeApi.getSubLabelList(pid)
const res = await homeApi.getSubLabelList(pid) currentLevel1Index.value = index
currentLevel1Index.value = index if (res.lableList && res.lableList.length > 0) {
if (res.lableList && res.lableList.length > 0) { categoryLevel2List.value = res.lableList
categoryLevel2List.value = res.lableList currentLevel2Index.value = 0
currentLevel2Index.value = 0 // 加载第一个二级标签的图书列表
// 加载第一个二级标签的图书列表 await getBooksByLabel(res.lableList[0].id, 'category')
await getBooksByLabel(res.lableList[0].id, 'category') } else {
} else { // 没有二级标签,直接加载一级标签的图书列表
// 没有二级标签,直接加载一级标签的图书列表 categoryLevel2List.value = []
categoryLevel2List.value = [] await getBooksByLabel(pid, 'category')
await getBooksByLabel(pid, 'category')
}
} catch (error) {
console.error('获取二级标签失败:', error)
} }
} }
@@ -328,23 +304,19 @@ const getBooksByLabel = async (
labelId: number, labelId: number,
type: 'activity' | 'category' type: 'activity' | 'category'
) => { ) => {
try { const res = await homeApi.getBooksByLabel(labelId)
const res = await homeApi.getBooksByLabel(labelId) if (type === 'activity') {
if (type === 'activity') { if (res.bookList && res.bookList.length > 0) {
if (res.bookList && res.bookList.length > 0) { activityList.value = res.bookList
activityList.value = res.bookList
} else {
activityList.value = []
}
} else { } else {
if (res.bookList && res.bookList.length > 0) { activityList.value = []
categoryBookList.value = res.bookList }
} else { } else {
categoryBookList.value = [] if (res.bookList && res.bookList.length > 0) {
} categoryBookList.value = res.bookList
} else {
categoryBookList.value = []
} }
} catch (error) {
console.error('获取图书列表失败:', error)
} }
} }

View File

@@ -117,31 +117,20 @@ function initScrollHeight() {
// 加载书籍信息 // 加载书籍信息
async function loadBookInfo() { async function loadBookInfo() {
try { const res = await bookApi.getBookInfo(bookId.value)
const res = await bookApi.getBookInfo(bookId.value) bookInfo.value = res.bookInfo
if (res.bookInfo) {
bookInfo.value = res.bookInfo
}
} catch (error) {
console.error('Failed to load book info:', error)
}
} }
// 加载章节列表 // 加载章节列表
async function loadChapterList() { async function loadChapterList() {
try { const res = await bookApi.getBookChapter({
const res = await bookApi.getBookChapter({ bookId: bookId.value
bookId: bookId.value })
})
if (res.chapterList && res.chapterList.length > 0) {
if (res.chapterList && res.chapterList.length > 0) { chapterList.value = res.chapterList
chapterList.value = res.chapterList } else {
} else {
nullText.value = t('common.data_null')
}
} catch (error) {
nullText.value = t('common.data_null') nullText.value = t('common.data_null')
console.error('Failed to load chapter list:', error)
} }
} }

View File

@@ -245,14 +245,8 @@ function initAudioContext() {
// 加载书籍信息 // 加载书籍信息
async function loadBookInfo() { async function loadBookInfo() {
try { const res = await bookApi.getBookInfo(bookId.value)
const res = await bookApi.getBookInfo(bookId.value) bookInfo.value = res.bookInfo
if (res.bookInfo) {
bookInfo.value = res.bookInfo
}
} catch (error) {
console.error('Failed to load book info:', error)
}
} }
// 加载章节列表 // 加载章节列表

View File

@@ -164,13 +164,9 @@ function initScrollHeight() {
// 加载书籍信息 // 加载书籍信息
async function loadBookInfo() { async function loadBookInfo() {
try { const res = await bookApi.getBookInfo(bookId.value)
const res = await bookApi.getBookInfo(bookId.value) if (res.bookInfo) {
if (res.bookInfo) { bookInfo.value = res.bookInfo
bookInfo.value = res.bookInfo
}
} catch (error) {
console.error('Failed to load book info:', error)
} }
} }
@@ -180,20 +176,15 @@ async function loadComments() {
return return
} }
try { const res = await bookApi.getBookComments(bookId.value, page.value.current, page.value.limit)
const res = await bookApi.getBookComments(bookId.value, page.value.current, page.value.limit)
commentsCount.value = res.commentsCount || 0 commentsCount.value = res.commentsCount || 0
if (res.commentsTree && res.commentsTree.length > 0) { if (res.commentsTree && res.commentsTree.length > 0) {
commentList.value = [...commentList.value, ...res.commentsTree] commentList.value = [...commentList.value, ...res.commentsTree]
page.value.current += 1 page.value.current += 1
} else if (commentList.value.length === 0) { } else if (commentList.value.length === 0) {
nullText.value = t('common.data_null')
}
} catch (error) {
nullText.value = t('common.data_null') nullText.value = t('common.data_null')
console.error('Failed to load comments:', error)
} }
} }
@@ -275,33 +266,29 @@ function handleEmj(i: any) {
// 提交评论 // 提交评论
async function submitComment() { async function submitComment() {
try { const content = await getEditorContent()
const content = await getEditorContent()
if (!content || content === '<p><br></p>') {
uni.showToast({
title: t('bookDetails.enterText'),
icon: 'none'
})
return
}
const pid = replyTarget.value?.id || 0
await bookApi.insertComment(bookId.value, content, pid)
if (!content || content === '<p><br></p>') {
uni.showToast({ uni.showToast({
title: t('workOrder.submit_success'), title: t('bookDetails.enterText'),
icon: 'success', icon: 'none'
duration: 500
}) })
return
setTimeout(() => {
editorCtx.value?.clear()
resetComments()
}, 500)
} catch (error) {
console.error('Failed to submit comment:', error)
} }
const pid = replyTarget.value?.id || 0
await bookApi.insertComment(bookId.value, content, pid)
uni.showToast({
title: t('workOrder.submit_success'),
icon: 'success',
duration: 500
})
setTimeout(() => {
editorCtx.value?.clear()
resetComments()
}, 500)
} }
// 点赞/取消点赞 // 点赞/取消点赞
@@ -314,29 +301,25 @@ async function handleLike(comment: IComment) {
return return
} }
try { if (comment.isLike === 0) {
if (comment.isLike === 0) { await bookApi.likeComment(comment.id)
await bookApi.likeComment(comment.id) uni.showToast({
uni.showToast({ title: t('bookDetails.supportSuccess'),
title: t('bookDetails.supportSuccess'), icon: 'success',
icon: 'success', duration: 1000
duration: 1000 })
}) } else {
} else { await bookApi.unlikeComment(comment.id)
await bookApi.unlikeComment(comment.id) uni.showToast({
uni.showToast({ title: t('bookDetails.supportCancel'),
title: t('bookDetails.supportCancel'), icon: 'success',
icon: 'success', duration: 1000
duration: 1000 })
})
}
setTimeout(() => {
resetComments()
}, 200)
} catch (error) {
console.error('Failed to like comment:', error)
} }
setTimeout(() => {
resetComments()
}, 200)
} }
// 删除评论 // 删除评论
@@ -348,20 +331,16 @@ function handleDelete(comment: IComment) {
confirmText: t('common.confirm_text'), confirmText: t('common.confirm_text'),
success: async (res) => { success: async (res) => {
if (res.confirm) { if (res.confirm) {
try { await bookApi.deleteComment(comment.id)
await bookApi.deleteComment(comment.id) uni.showToast({
uni.showToast({ title: t('bookDetails.deleteSuccess'),
title: t('bookDetails.deleteSuccess'), icon: 'success',
icon: 'success', duration: 500
duration: 500 })
})
setTimeout(() => {
setTimeout(() => { resetComments()
resetComments() }, 500)
}, 500)
} catch (error) {
console.error('Failed to delete comment:', error)
}
} }
} }
}) })

View File

@@ -70,14 +70,8 @@ onLoad((options: any) => {
* 获取VIP信息 * 获取VIP信息
*/ */
const getVipInfo = async () => { const getVipInfo = async () => {
try { const res = await homeApi.getVipInfo()
const res = await homeApi.getVipInfo() vipInfo.value = res.vipInfo
if (res.vipInfo) {
vipInfo.value = res.vipInfo
}
} catch (error) {
console.error('获取VIP信息失败:', error)
}
} }
/** /**
@@ -91,26 +85,19 @@ const handleSearch = async () => {
loading.value = true loading.value = true
isEmpty.value = false isEmpty.value = false
try { const res = await homeApi.searchBooks({
const res = await homeApi.searchBooks({ title: keyword.value.trim(),
title: keyword.value.trim(), page: 1,
page: 1, limit: 10,
limit: 10, })
}) if (res.bookList && res.bookList.length > 0) {
if (res.bookList && res.bookList.length > 0) { searchResults.value = res.bookList
searchResults.value = res.bookList isEmpty.value = false
isEmpty.value = false } else {
} else {
searchResults.value = []
isEmpty.value = true
}
} catch (error) {
console.error('搜索失败:', error)
searchResults.value = [] searchResults.value = []
isEmpty.value = true isEmpty.value = true
} finally {
loading.value = false
} }
loading.value = false
} }
/** /**

View File

@@ -164,23 +164,19 @@ onLoad((options: any) => {
* 加载章节详情 * 加载章节详情
*/ */
const loadChapterDetail = async () => { const loadChapterDetail = async () => {
try { const res = await courseApi.getChapterDetail(chapterId.value)
const res = await courseApi.getChapterDetail(chapterId.value) if (res.code === 0 && res.data) {
if (res.code === 0 && res.data) { chapterDetail.value = res.data.detail
chapterDetail.value = res.data.detail videoList.value = res.data.videos || []
videoList.value = res.data.videos || []
// 如果有历史播放记录,定位到对应视频 // 如果有历史播放记录,定位到对应视频
if (res.data.current) { if (res.data.current) {
const index = videoList.value.findIndex(v => v.id === res.data.current) const index = videoList.value.findIndex(v => v.id === res.data.current)
if (index !== -1) { if (index !== -1) {
currentVideoIndex.value = index currentVideoIndex.value = index
activeVideoIndex.value = index activeVideoIndex.value = index
}
} }
} }
} catch (error) {
console.error('加载章节详情失败:', error)
} }
} }

View File

@@ -259,60 +259,47 @@ onLoad(async (options: any) => {
* 加载页面数据 * 加载页面数据
*/ */
const loadPageData = async () => { const loadPageData = async () => {
try { // 获取课程详情
uni.showLoading({ title: '加载中...' }) const res = await courseApi.getCourseDetail(courseId.value)
if (res.code === 0 && res.data) {
courseDetail.value = res.data.course
catalogueList.value = res.data.catalogues || []
relatedBooks.value = res.data.shopProductList || []
// 获取课程详情 // 计算学习进度
const res = await courseApi.getCourseDetail(courseId.value) if (catalogueList.value.length > 0) {
if (res.code === 0 && res.data) { const totalProgress = catalogueList.value.reduce((sum, cat) => sum + cat.completion, 0)
courseDetail.value = res.data.course learningProgress.value = Number((totalProgress / catalogueList.value.length).toFixed(2))
catalogueList.value = res.data.catalogues || []
relatedBooks.value = res.data.shopProductList || []
// 计算学习进度
if (catalogueList.value.length > 0) {
const totalProgress = catalogueList.value.reduce((sum, cat) => sum + cat.completion, 0)
learningProgress.value = Number((totalProgress / catalogueList.value.length).toFixed(2))
}
// 默认选择第一个目录
if (catalogueList.value.length > 0) {
await switchCatalogue(0)
}
} }
// 检查VIP权益 // 默认选择第一个目录
await checkVipStatus() if (catalogueList.value.length > 0) {
await switchCatalogue(0)
// 加载评论 }
await loadComments()
} catch (error) {
console.error('加载页面数据失败:', error)
} finally {
uni.hideLoading()
} }
// 检查VIP权益
await checkVipStatus()
// 加载评论
await loadComments()
} }
/** /**
* 检查VIP状态 * 检查VIP状态
*/ */
const checkVipStatus = async () => { const checkVipStatus = async () => {
try { const res = await courseApi.checkCourseVip(courseId.value)
const res = await courseApi.checkCourseVip(courseId.value) if (res.code === 0) {
if (res.code === 0) { userVip.value = res.userVip || null
userVip.value = res.userVip || null
// 如果不是VIP获取需要的VIP类型
// 如果不是VIP获取需要的VIP类型 if (!userVip.value) {
if (!userVip.value) { const moduleRes = await courseApi.getCourseVipModule(courseId.value)
const moduleRes = await courseApi.getCourseVipModule(courseId.value) if (moduleRes.code === 0) {
if (moduleRes.code === 0) { vipModuleList.value = moduleRes.list || []
vipModuleList.value = moduleRes.list || []
}
} }
} }
} catch (error) {
console.error('检查VIP状态失败:', error)
} }
} }
@@ -324,21 +311,17 @@ const switchCatalogue = async (index: number) => {
const catalogue = catalogueList.value[index] const catalogue = catalogueList.value[index]
// 获取章节列表 // 获取章节列表
try { const res = await courseApi.getCatalogueChapterList(catalogue.id)
const res = await courseApi.getCatalogueChapterList(catalogue.id) if (res.code === 0) {
if (res.code === 0) { chapterList.value = res.chapterList || []
chapterList.value = res.chapterList || [] }
}
// 检查是否支持复读
// 检查是否支持复读 if (catalogue.isBuy === 0 && !userVip.value) {
if (catalogue.isBuy === 0 && !userVip.value) { const renewRes = await courseApi.checkRenewPayment(catalogue.id)
const renewRes = await courseApi.checkRenewPayment(catalogue.id) showRenewBtn.value = renewRes.canRelearn || false
showRenewBtn.value = renewRes.canRelearn || false } else {
} else { showRenewBtn.value = false
showRenewBtn.value = false
}
} catch (error) {
console.error('切换目录失败:', error)
} }
} }
@@ -366,18 +349,12 @@ const handleChapterClick = (chapter: IChapter) => {
const handleGetFreeCourse = async () => { const handleGetFreeCourse = async () => {
if (!currentCatalogue.value) return if (!currentCatalogue.value) return
try { uni.showLoading({ title: '领取中...' })
uni.showLoading({ title: '领取中...' }) const res = await courseApi.startStudyForMF(currentCatalogue.value.id)
const res = await courseApi.startStudyForMF(currentCatalogue.value.id) if (res.code === 0) {
if (res.code === 0) { uni.showToast({ title: '领取成功', icon: 'success' })
uni.showToast({ title: '领取成功', icon: 'success' }) // 刷新页面数据
// 刷新页面数据 await loadPageData()
await loadPageData()
}
} catch (error) {
console.error('领取免费课程失败:', error)
} finally {
uni.hideLoading()
} }
} }
@@ -387,17 +364,13 @@ const handleGetFreeCourse = async () => {
const handlePurchase = async () => { const handlePurchase = async () => {
if (!currentCatalogue.value) return if (!currentCatalogue.value) return
try { isFudu.value = false
isFudu.value = false const res = await courseApi.getProductListForCourse(currentCatalogue.value.id)
const res = await courseApi.getProductListForCourse(currentCatalogue.value.id) if (res.code === 0 && res.productList.length > 0) {
if (res.code === 0 && res.productList.length > 0) { goodsList.value = res.productList
goodsList.value = res.productList showGoodsSelector.value = true
showGoodsSelector.value = true } else {
} else { uni.showToast({ title: '此课程暂无购买方式', icon: 'none' })
uni.showToast({ title: '此课程暂无购买方式', icon: 'none' })
}
} catch (error) {
console.error('获取商品列表失败:', error)
} }
} }
@@ -407,18 +380,14 @@ const handlePurchase = async () => {
const handleRenew = async () => { const handleRenew = async () => {
if (!currentCatalogue.value) return if (!currentCatalogue.value) return
try { isFudu.value = true
isFudu.value = true fuduCatalogueId.value = currentCatalogue.value.id
fuduCatalogueId.value = currentCatalogue.value.id const res = await courseApi.getRenewProductList(currentCatalogue.value.id)
const res = await courseApi.getRenewProductList(currentCatalogue.value.id) if (res.code === 0 && res.productList.length > 0) {
if (res.code === 0 && res.productList.length > 0) { goodsList.value = res.productList
goodsList.value = res.productList showGoodsSelector.value = true
showGoodsSelector.value = true } else {
} else { uni.showToast({ title: '暂无复读方案', icon: 'none' })
uni.showToast({ title: '暂无复读方案', icon: 'none' })
}
} catch (error) {
console.error('获取复读商品列表失败:', error)
} }
} }

View File

@@ -257,29 +257,25 @@ const handleFirstLevelClick = (item: string) => {
* 获取课程分类数据 * 获取课程分类数据
*/ */
const getMedicalTags = async () => { const getMedicalTags = async () => {
try { const res = await courseSubjectClassificationApi.getCourseMedicalTree()
const res = await courseSubjectClassificationApi.getCourseMedicalTree() if (res && res.code === 0) {
if (res && res.code === 0) { if (res.labels && res.labels.length > 0) {
if (res.labels && res.labels.length > 0) { curseTagList.value = res.labels
curseTagList.value = res.labels // 根据 currentIndex 设置初始选中的分类
// 根据 currentIndex 设置初始选中的分类 if (res.labels[currentIndex.value]) {
if (res.labels[currentIndex.value]) { const selectedTag = res.labels[currentIndex.value]
const selectedTag = res.labels[currentIndex.value] if (selectedTag.isLast === 0) {
if (selectedTag.isLast === 0) { // 非终极分类,显示子分类
// 非终极分类,显示子分类 if (selectedTag.children && selectedTag.children.length > 0) {
if (selectedTag.children && selectedTag.children.length > 0) { sbuMedicalTagsList.value = selectedTag.children
sbuMedicalTagsList.value = selectedTag.children } else {
} else { sbuMedicalTagsList.value = []
sbuMedicalTagsList.value = []
}
} }
} }
} else {
curseTagList.value = []
} }
} else {
curseTagList.value = []
} }
} catch (error) {
console.error('获取医学课程分类失败:', error)
} }
} }
/** /**
@@ -309,13 +305,9 @@ const curseClick = (item: IMedicalTag, index: number) => {
*/ */
const soulCateList = ref<IMedicalTag[]>([]) const soulCateList = ref<IMedicalTag[]>([])
const getSoulCateList = async () => { const getSoulCateList = async () => {
try { const res = await courseSubjectClassificationApi.getCourseSoulTree()
const res = await courseSubjectClassificationApi.getCourseSoulTree() if (res.labels&&res.labels.length>0) {
if (res.labels&&res.labels.length>0) { soulCateList.value = res.labels;
soulCateList.value = res.labels;
}
} catch (error) {
console.error('获取心理学课程分类失败:', error)
} }
} }
@@ -325,13 +317,9 @@ const getSoulCateList = async () => {
*/ */
const sociologyCateList = ref<IMedicalTag[]>([]) const sociologyCateList = ref<IMedicalTag[]>([])
const getSociologyCateList = async () => { const getSociologyCateList = async () => {
try { const res = await courseSubjectClassificationApi.getCourseSociologyTree()
const res = await courseSubjectClassificationApi.getCourseSociologyTree() if (res.labels&&res.labels.length>0) {
if (res.labels&&res.labels.length>0) { sociologyCateList.value = res.labels;
sociologyCateList.value = res.labels;
}
} catch (error) {
console.error('获取国学课程分类失败:', error)
} }
} }
@@ -369,17 +357,13 @@ const learnList = ref<ICourse[]>([]) // 观看记录列表
* 获取观看记录 * 获取观看记录
*/ */
const getLearnCourse = async () => { const getLearnCourse = async () => {
try { const res = await courseApi.getUserLateCourseList()
const res = await courseApi.getUserLateCourseList() if (res && res.code === 0) {
if (res && res.code === 0) { if (res.page && res.page.length > 0) {
if (res.page && res.page.length > 0) { learnList.value = res.page
learnList.value = res.page } else {
} else { learnList.value = []
learnList.value = []
}
} }
} catch (error) {
console.error('获取观看记录失败:', error)
} }
} }
@@ -389,17 +373,13 @@ const newsList = ref<INews[]>([]) // 新闻列表
* 获取新闻列表 * 获取新闻列表
*/ */
const getNewsList = async () => { const getNewsList = async () => {
try { const res = await commonApi.getMessageList(0, 1, 0)
const res = await commonApi.getMessageList(0, 1, 0) if (res && res.code === 0) {
if (res && res.code === 0) { if (res.messages && res.messages.length > 0) {
if (res.messages && res.messages.length > 0) { newsList.value = res.messages
newsList.value = res.messages } else {
} else { newsList.value = []
newsList.value = []
}
} }
} catch (error) {
console.error('获取新闻列表失败:', error)
} }
} }
/** /**
@@ -423,21 +403,17 @@ const tryListenList = ref<ICourse[]>([]) // 试听课程列表
* 获取试听课程列表 * 获取试听课程列表
*/ */
const getTryListenList = async () => { const getTryListenList = async () => {
try { const res = await courseApi.getMarketCourseList({
const res = await courseApi.getMarketCourseList({ page: 1,
page: 1, limit: 6,
limit: 6, id: 1
id: 1 })
}) if (res && res.code === 0) {
if (res && res.code === 0) { if (res.courseList && res.courseList.records && res.courseList.records.length > 0) {
if (res.courseList && res.courseList.records && res.courseList.records.length > 0) { tryListenList.value = res.courseList.records
tryListenList.value = res.courseList.records } else {
} else { tryListenList.value = []
tryListenList.value = []
}
} }
} catch (error) {
console.error('获取试听课程失败:', error)
} }
} }

View File

@@ -52,30 +52,26 @@ const subCategoryList = ref<ICategory[]>([]) // 子级分类列表
* 获取分类下的子级分类 * 获取分类下的子级分类
*/ */
const getSubCategoryList = async () => { const getSubCategoryList = async () => {
try { let res: any = null
let res: any = null switch (subject.value) {
switch (subject.value) { case '医学':
case '医学': res = await courseSubjectClassificationApi.getCourseMedicalChildLabels(categoryId.value)
res = await courseSubjectClassificationApi.getCourseMedicalChildLabels(categoryId.value) break
break case '心理学':
case '心理学': res = await courseSubjectClassificationApi.getCourseSoulChildLabels(categoryId.value)
res = await courseSubjectClassificationApi.getCourseSoulChildLabels(categoryId.value) break
break }
if (res && res.code === 0) {
if (res.labels && res.labels.length > 0) {
subCategoryList.value = res.labels
// 默认选中第一个tab
tab_category_id.value = res.labels[0].id
radio_category_id.value = res.labels[0].children[0] && res.labels[0].children[0].id || 0
} else {
subCategoryList.value = []
tab_category_id.value = 0
radio_category_id.value = 0
} }
if (res && res.code === 0) {
if (res.labels && res.labels.length > 0) {
subCategoryList.value = res.labels
// 默认选中第一个tab
tab_category_id.value = res.labels[0].id
radio_category_id.value = res.labels[0].children[0] && res.labels[0].children[0].id || 0
} else {
subCategoryList.value = []
tab_category_id.value = 0
radio_category_id.value = 0
}
}
} catch (error) {
console.error('获取分类下的子级分类失败:', error)
} }
} }

View File

@@ -191,16 +191,12 @@ const getCode = async () => {
if (!isEmailEmpty()) return if (!isEmailEmpty()) return
if (!isEmailVerified(email.value)) return if (!isEmailVerified(email.value)) return
try { await commonApi.sendMailCaptcha(email.value)
await commonApi.sendMailCaptcha(email.value) uni.showToast({
uni.showToast({ title: t('login.sendCodeSuccess'),
title: t('login.sendCodeSuccess'), icon: 'none'
icon: 'none' })
}) getCodeState()
getCodeState()
} catch (error) {
console.error('Send code error:', error)
}
} }
/** /**
@@ -264,20 +260,16 @@ const onSubmit = async () => {
if (!isConfirmPasswordEmpty()) return if (!isConfirmPasswordEmpty()) return
if (!isPasswordMatch()) return if (!isPasswordMatch()) return
try { await resetPassword(email.value, code.value, password.value)
await resetPassword(email.value, code.value, password.value)
uni.showModal({ uni.showModal({
title: t('global.tips'), title: t('global.tips'),
content: t('forget.passwordChanged'), content: t('forget.passwordChanged'),
showCancel: false, showCancel: false,
success: () => { success: () => {
uni.navigateBack() uni.navigateBack()
} }
}) })
} catch (error) {
console.error('Reset password error:', error)
}
} }
</script> </script>

View File

@@ -285,13 +285,8 @@ const verifyCodeLogin = async () => {
if (!isCodeEmpty()) return false if (!isCodeEmpty()) return false
try { const res = await loginWithCode(email.value, code.value)
const res = await loginWithCode(email.value, code.value) return res || null
return res
} catch (error) {
console.error('验证码登录失败:', error)
return null
}
} }
// 密码登录 // 密码登录
const passwordLogin = async () => { const passwordLogin = async () => {
@@ -301,13 +296,8 @@ const passwordLogin = async () => {
if (!isPasswordEmpty()) return false if (!isPasswordEmpty()) return false
try { const res = await loginWithPassword(phoneEmail.value, password.value)
const res = await loginWithPassword(phoneEmail.value, password.value) return res || null
return res
} catch (error) {
console.error('密码登录失败:', error)
return null
}
} }
// 提交登录 // 提交登录
const onSubmit = async () => { const onSubmit = async () => {

View File

@@ -61,14 +61,8 @@ import GoodsPrice from '@/components/order/GoodsPrice.vue';
*/ */
const userInfo = ref({}) const userInfo = ref({})
const getUserInfo = async () => { const getUserInfo = async () => {
try { const res = await orderApi.getUserInfo()
const res = await orderApi.getUserInfo() userInfo.value = res.result || {}
if (res.code === 0) {
userInfo.value = res.result || {}
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
} }
/** /**
@@ -77,15 +71,11 @@ const getUserInfo = async () => {
const goodsIds = ref<string>('') const goodsIds = ref<string>('')
const goodsList = ref<IOrderGoods[]>([]) const goodsList = ref<IOrderGoods[]>([])
const getGoodsList = async () => { const getGoodsList = async () => {
try { // 获取商品详情
// 获取商品详情 const res = await orderApi.getShopProductListByIds(goodsIds.value)
const res = await orderApi.getShopProductListByIds(goodsIds.value)
if (res.shopProductList?.length > 0) {
if (res.code === 0 && res.shopProductList?.length > 0) { goodsList.value = res.shopProductList
goodsList.value = res.shopProductList
}
} catch (error) {
console.error('获取商品列表失败:', error)
} }
} }

View File

@@ -147,21 +147,17 @@
* 获取数据 * 获取数据
*/ */
const getData = async () => { const getData = async () => {
try { // 获取用户信息
// 获取用户信息 const userRes = await getUserInfo()
const userRes = await getUserInfo() console.log(userRes);
console.log(userRes); if (userRes.user) {
if (userRes.user) { userStore.setUserInfo(userRes.user)
userStore.setUserInfo(userRes.user) }
}
// 获取VIP信息 // 获取VIP信息
const vipRes = await getVipInfo() const vipRes = await getVipInfo()
if (vipRes.vipInfo) { if (vipRes.vipInfo) {
vipInfo.value = vipRes.vipInfo vipInfo.value = vipRes.vipInfo
}
} catch (error) {
console.error('获取数据失败:', error)
} }
} }

View File

@@ -199,14 +199,10 @@ const avatarUrl = ref('')
*/ */
const userInfo = ref<any>({}) // 用户信息 const userInfo = ref<any>({}) // 用户信息
const getData = async () => { const getData = async () => {
try { const res = await getUserInfo()
const res = await getUserInfo() if (res.result) {
if (res.result) { userStore.setUserInfo(res.result)
userStore.setUserInfo(res.result) userInfo.value = res.result
userInfo.value = res.result
}
} catch (error) {
console.error('获取用户信息失败:', error)
} }
} }
@@ -324,16 +320,12 @@ const sendCode = async () => {
return return
} }
try { await sendEmailCode(editForm.value.email)
await sendEmailCode(editForm.value.email) uni.showToast({
uni.showToast({ title: t('user.sendCodeSuccess'),
title: t('user.sendCodeSuccess'), icon: 'none'
icon: 'none' })
}) startCountdown()
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
}
} }
/** /**
@@ -398,92 +390,88 @@ const checkPasswordStrength = () => {
const handleSubmit = async () => { const handleSubmit = async () => {
const key = currentField.value?.key const key = currentField.value?.key
try { // 构建更新数据对象
// 构建更新数据对象 let updateData: any = Object.assign({}, userInfo.value)
let updateData: any = Object.assign({}, userInfo.value)
switch (key) { switch (key) {
case 'email': case 'email':
// 更新邮箱 // 更新邮箱
if (!editForm.value.email || !editForm.value.code) { if (!editForm.value.email || !editForm.value.code) {
uni.showToast({ uni.showToast({
title: t('user.pleaseInputCode'), title: t('user.pleaseInputCode'),
icon: 'none' icon: 'none'
}) })
return return
} }
await updateEmail(userInfo.value.id, editForm.value.email, editForm.value.code) await updateEmail(userInfo.value.id, editForm.value.email, editForm.value.code)
break break
case 'password': case 'password':
// 更新密码 // 更新密码
if (!passwordOk.value) { if (!passwordOk.value) {
uni.showToast({ uni.showToast({
title: passwordNote.value, title: passwordNote.value,
icon: 'none' icon: 'none'
}) })
return return
} }
if (editForm.value.password !== editForm.value.confirmPassword) { if (editForm.value.password !== editForm.value.confirmPassword) {
uni.showToast({ uni.showToast({
title: t('user.passwordNotMatch'), title: t('user.passwordNotMatch'),
icon: 'none' icon: 'none'
}) })
return return
} }
await updatePassword(userInfo.value.id, editForm.value.password) await updatePassword(userInfo.value.id, editForm.value.password)
break break
case 'avatar': case 'avatar':
// 更新头像 // 更新头像
console.log('avatarUrl.value:', avatarUrl.value) console.log('avatarUrl.value:', avatarUrl.value)
if (!avatarUrl.value) { if (!avatarUrl.value) {
uni.showToast({ uni.showToast({
title: t('common.pleaseSelect') + t('user.avatar'), title: t('common.pleaseSelect') + t('user.avatar'),
icon: 'none' icon: 'none'
}) })
return return
} }
// 如果是新上传的图片,需要先上传 // 如果是新上传的图片,需要先上传
updateData.avatar = avatarUrl.value updateData.avatar = avatarUrl.value
await updateUserInfo(updateData) await updateUserInfo(updateData)
break break
case 'sex': case 'sex':
// 更新性别 // 更新性别
updateData.sex = editValue.value updateData.sex = editValue.value
await updateUserInfo(updateData) await updateUserInfo(updateData)
break break
default: default:
// 更新其他字段 // 更新其他字段
if (!editValue.value) { if (!editValue.value) {
uni.showToast({ uni.showToast({
title: getPlaceholder(key), title: getPlaceholder(key),
icon: 'none' icon: 'none'
}) })
return return
} }
updateData[key] = editValue.value updateData[key] = editValue.value
await updateUserInfo(updateData) await updateUserInfo(updateData)
break break
}
uni.showToast({
title: t('user.updateSuccess'),
icon: 'success'
})
closeModal()
// 刷新数据
setTimeout(() => {
getData()
}, 500)
} catch (error) {
console.error('更新失败:', error)
} }
uni.showToast({
title: t('user.updateSuccess'),
icon: 'success'
})
closeModal()
// 刷新数据
setTimeout(() => {
getData()
}, 500)
} }
/** /**

View File

@@ -1,9 +1,9 @@
<template> <template>
<view class="recharge-page"> <view class="recharge-page">
<!-- 自定义导航栏 --> <!-- 自定义导航栏 -->
<nav-bar :title="$t('user.recharge')"></nav-bar> <nav-bar :title="$t('order.recharge')"></nav-bar>
<view class="block"> <view class="block">
<view class="text">充值金额</view> <view class="text">{{$t('order.rechargeAmount')}}</view>
<view class="recharge"> <view class="recharge">
<view class="recharge_block" @click="chosPric(item)" <view class="recharge_block" @click="chosPric(item)"
:class="aloneItem.priceTypeId === item.priceTypeId ? 'selected' : ''" :class="aloneItem.priceTypeId === item.priceTypeId ? 'selected' : ''"
@@ -21,30 +21,30 @@
<view v-html="remark.remark"></view> <view v-html="remark.remark"></view>
</view> </view>
<view class="cha_fangsh"> <view class="cha_fangsh">
<view class="cf_title PM_font">支付方式</view> <view class="cf_title PM_font">{{$t('user.paymentMethod')}}</view>
<view class="cf_radio"> <view class="cf_radio">
<radio-group v-for="item in iosPaylist" @change="choseType(item.id)"> <radio-group v-for="item in iosPaylist" @click="choseType(item.id)">
<view style="width: 100%"> <view style="width: 100%">
<view :class="payType == item.id ? 'Tab_xf cf_xuanx' : 'cf_xuanx'"> <view :class="payType == item.id ? 'Tab_xf cf_xuanx' : 'cf_xuanx'">
<!-- <image class="pay_item_img" :src="item.imgUrl" mode="aspectFil"> <!-- <image class="pay_item_img" :src="item.imgUrl" mode="aspectFil">
</image> --> </image> -->
<text>{{ item.title }}</text> <text>{{ item.title }}</text>
<radio :checked="payType === item.id" style="float: right"></radio> <radio :checked="payType === item.id"></radio>
</view> </view>
</view> </view>
</radio-group> </radio-group>
</view> </view>
</view> </view>
<view class="agree_wo flexbox"> <view class="agree_wo flexbox">
<radio-group class="agree" v-for="(item, index) in argee" :key="index" @change="radioCheck"> <radio-group class="agree" v-for="(item, index) in argee" :key="index" @click="radioCheck">
<view> <view>
<radio class="agreeRadio" :value="item.id" :checked="state" color="#007bff"></radio> <radio class="agreeRadio" :value="item.id" :checked="state" color="#007bff"></radio>
</view> </view>
</radio-group> </radio-group>
<view>我已阅读并同意<span class="highlight" @click="showAgreement">增值服务协议</span></view> <view>{{$t('order.readAgree')}}<span class="highlight" @click="showAgreement">{{$t('order.valueAddedServices')}}</span></view>
</view> </view>
<view class="bottom-button-container"> <view class="bottom-button-container">
<button class="recharge-button" @click="handleRecharge">立即充值</button> <button class="recharge-button" @click="handleRecharge">{{$t('order.recharge')}}</button>
</view> </view>
<wd-popup v-model="agreemenState" position="bottom" :closeable="true"> <wd-popup v-model="agreemenState" position="bottom" :closeable="true">
<view class="agreement"> <view class="agreement">
@@ -61,10 +61,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, toRefs, reactive } from 'vue' import { ref, computed, onMounted, toRefs, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/uni_modules/wot-design-uni' import { useMessage } from '@/uni_modules/wot-design-uni'
import { getBookBuyConfigList, getAgreement, getActivityDescription } from '@/api/modules/user' import { getBookBuyConfigList, getAgreement, getActivityDescription } from '@/api/modules/user'
const googlePay = uni.requireNativePlugin("sn-googlepay5"); // const googlePay = uni.requireNativePlugin("sn-googlepay5");
const { t } = useI18n()
const message = useMessage() const message = useMessage()
const payType = ref('1') const payType = ref('1')
const iosPaylist = ref([ const iosPaylist = ref([
@@ -108,9 +109,11 @@
const isConnected = ref(false) const isConnected = ref(false)
/**
* 获取使用环境
*/
const getDevName = () => { const getDevName = () => {
// 获取使用环境
if (uni.getSystemInfoSync().platform === "android") { if (uni.getSystemInfoSync().platform === "android") {
qudao.value = 'Google' qudao.value = 'Google'
isAndroid.value = true; isAndroid.value = true;
@@ -132,8 +135,8 @@
* 勾选协议 * 勾选协议
*/ */
const radioCheck = () => { const radioCheck = () => {
console.log('点击了', state.value);
state.value = !state.value state.value = !state.value
console.log('点击了', state.value);
} }
/** /**
@@ -151,7 +154,6 @@
console.log(rechargeList.value.bookBuyConfigList, '充值列表'); console.log(rechargeList.value.bookBuyConfigList, '充值列表');
// 默认选择第一个金额 // 默认选择第一个金额
aloneItem.value = rechargeList.value.bookBuyConfigList[0] aloneItem.value = rechargeList.value.bookBuyConfigList[0]
getGooglePay()
} catch (error) { } catch (error) {
console.error('获取订单列表失败:', error) console.error('获取订单列表失败:', error)
} }
@@ -194,7 +196,16 @@
} }
const handleRecharge = () => { const handleRecharge = () => {
if(!state.value){
uni.showToast({
title: t('order.readAgreeServices'),
icon: 'none'
})
return
}
uni.showLoading({ title: '加载中...' })
console.log('立即充值'); console.log('立即充值');
getGooglePay()
} }
/** /**
@@ -202,8 +213,6 @@
*/ */
const getGooglePay = () => { const getGooglePay = () => {
googlePay.init({ googlePay.init({
// autoReconnect: true, // 是否自动重连(插件实现)
// enableAutoServiceReconnection: true, //是否自动重连8.0+支持)
}, (e:any) => { }, (e:any) => {
console.log('init', e); console.log('init', e);
if (e.code == 0) { if (e.code == 0) {
@@ -262,9 +271,6 @@
getDevName(); getDevName();
getActivityDescriptionData() getActivityDescriptionData()
getAgreementData() getAgreementData()
}) })
</script> </script>
@@ -300,7 +306,7 @@
.recharge_money { .recharge_money {
font-size: 30rpx; font-size: 30rpx;
margin-bottom: 30rpx; margin-bottom: 10rpx;
} }
@@ -376,9 +382,12 @@
.cf_xuanx { .cf_xuanx {
font-size: 24rpx; font-size: 24rpx;
padding: 20rpx 0; padding: 10rpx 0;
margin-bottom: 20rpx; margin-bottom: 20rpx;
border-bottom: 1px solid #ededed; border-bottom: 1px solid #ededed;
display: flex;
justify-content: space-between;
align-items:center;
image { image {
width: 40rpx; width: 40rpx;

View File

@@ -1,65 +1,46 @@
<template> <template>
<z-paging ref="paging" v-model="bookList" auto-show-back-to-top class="my-book-page" @query="loadBookList"> <z-paging ref="paging" v-model="bookList" auto-show-back-to-top class="my-book-page" @query="rechargeList" :default-page-size="10">
<template #top> <template #top>
<!-- 自定义导航栏 --> <!-- 自定义导航栏 -->
<nav-bar :title="$t('book.myBook')"></nav-bar> <nav-bar :title="$t('user.consumptionRecord')"></nav-bar>
</template> </template>
<view class="recharge-record" v-if="(bookList && bookList.length > 0)">
<!-- 充值列表 --> <view class="go-gecharge" @click="goRecharge">
<!-- <uni-icons fontFamily="CustomFont" :size="26">{{'\uebc6'}}</uni-icons> --> <view>{{$t('order.recharge')}}</view>
<view><wd-icon name="arrow-right" size="16px" color="#fff"/></view>
<view class="recharge-record">
<view><uni-icons type="right" size="30"></uni-icons></view>
<view class="go-gecharge">
立即充值
<uni-icons type="contact" size="30"></uni-icons>
</view> </view>
<view class="title">充值消费记录</view> <view class="title">{{$t('order.rechargeConsumptionList')}}</view>
<view class="recharge-record-block" v-for="(item) in 5"> <view class="recharge-record-block" v-for="(item, index) in bookList" :key="index">
<view class="recharge-record-block-row">购买商品<text class="text">90</text></view> <view class="recharge-record-block-row">{{item.orderType}}<text class="text">{{item.changeAmount}}</text></view>
<view class="time">2025-10-20</view> <view class="time">{{item.createTime}}</view>
</view> </view>
</view> </view>
<!-- <view v-if="(bookList && bookList.length > 0)" class="book-list">
<BookCard
v-for="item in bookList"
:key="item.id"
:book="item"
/>
</view> -->
<!-- 空状态 -->
<!-- <view v-else-if="!loading && !firstLoad" class="empty-state">
<image src="@/static/null_img.png" mode="aspectFit" />
<text class="empty-text">{{ $t('book.nullText') }}</text>
<wd-button type="primary" @click="goToBuy">
{{ $t('book.choose') }}
</wd-button>
</view> -->
</z-paging> </z-paging>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { bookApi } from '@/api/modules/book' import { useUserStore } from '@/stores/user'
import type { IBook } from '@/types/book' import { getTransactionDetailsList } from '@/api/modules/user'
import BookCard from '@/components/book/BookCard.vue'
const { t } = useI18n() const { t } = useI18n()
const paging = ref<any>() const paging = ref<any>()
const userStore = useUserStore()
// 数据状态 // 数据状态
const bookList = ref<IBook[]>([]) const bookList = ref([])
const loading = ref(false) const loading = ref(false)
const firstLoad = ref(true) const firstLoad = ref(true)
// 加载书单列表 // 充值记录列表
async function loadBookList(pageNo : number, pageSize : number) { async function rechargeList(pageNo : number, pageSize : number) {
const userId = userStore.userInfo.id
loading.value = true loading.value = true
try { try {
const res = await bookApi.getMyBooks(pageNo, pageSize) const res = await getTransactionDetailsList(pageNo, pageSize, userId)
paging.value.complete(res.page.records) console.log(res, 'res');
paging.value.complete(res.transactionDetailsList.records)
} catch (error) { } catch (error) {
paging.value.complete(false) paging.value.complete(false)
console.error('Failed to load book list:', error) console.error('Failed to load book list:', error)
@@ -68,6 +49,15 @@
loading.value = false loading.value = false
} }
} }
/**
* 跳转充值页面
*/
const goRecharge = () => {
uni.navigateTo({
url: '/pages/user/recharge/index'
})
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@@ -86,15 +76,16 @@
.go-gecharge{ .go-gecharge{
//height: 100rpx; //height: 100rpx;
background: linear-gradient(to right, #007bff, #17a2b8); background: linear-gradient(to right, #007bff, #17a2b8);
font-size: 40rpx; font-size: 30rpx;
font-weight: bold; font-weight: bold;
color: #fff; color: #fff;
padding: 20rpx; padding: 20rpx;
margin-bottom: 20rpx; margin-bottom: 20rpx;
display: flex;justify-content:space-between;align-items:center
} }
.title { .title {
font-size: 40rpx; font-size: 30rpx;
padding-left:20rpx; padding-left:20rpx;
margin-bottom: 30rpx; margin-bottom: 30rpx;
color: #007bff; color: #007bff;
@@ -120,6 +111,25 @@
} }
} }
} }
} }
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding-top: 200rpx;
image {
width: 400rpx;
height: 300rpx;
margin-bottom: 40rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
margin-bottom: 50rpx;
}
}
</style> </style>

0
pages/vip/course.vue Normal file
View File