404 lines
11 KiB
TypeScript
Executable File
404 lines
11 KiB
TypeScript
Executable File
// upload.ts - 主功能页面(拍照/相册选择)
|
||
import { IAppOption, IUserInfo } from 'miniprogram/types/app'
|
||
import apiManager from '../../utils/api'
|
||
import imageManager from '../../utils/image'
|
||
import ActionSheet, { ActionSheetTheme } from 'tdesign-miniprogram/action-sheet/index';
|
||
import { FILE_BASE_URL } from '../../utils/config'
|
||
|
||
const app = getApp<IAppOption>()
|
||
|
||
type IDayType = 'morning' | 'afternoon' | 'night'
|
||
const DayTypeMap: Record<IDayType, string> = {
|
||
morning: '早上好',
|
||
afternoon: '下午好',
|
||
night: '晚上好'
|
||
}
|
||
|
||
Page({
|
||
data: {
|
||
move_camera_pos_to: 'top' as 'top' | 'bottom',
|
||
DayTypeMap,
|
||
current_date: '',
|
||
day_type: 'morning' as IDayType,
|
||
isLoggedIn: false,
|
||
showLoginView: false,
|
||
userInfo: null as IUserInfo | null,
|
||
isProcessing: false, // 是否正在处理图片
|
||
// 移除模拟数据,改为从API获取
|
||
groupedHistory: [] as any[],
|
||
// 添加分页相关数据
|
||
page: 1,
|
||
size: 10,
|
||
total: 0,
|
||
hasMore: true,
|
||
// 添加加载状态
|
||
isLoading: true,
|
||
// 添加文件基础URL
|
||
fileBaseUrl: FILE_BASE_URL
|
||
},
|
||
|
||
onLoad() {
|
||
console.log('主功能页面加载')
|
||
this.checkLoginStatus().then(() => {
|
||
// 只有登录成功后才加载历史数据
|
||
if (this.data.isLoggedIn) {
|
||
this.loadDailySummary()
|
||
this.checkDayType()
|
||
}
|
||
}).catch((error) => {
|
||
console.error('登录检查失败:', error)
|
||
})
|
||
},
|
||
|
||
onShow() {
|
||
// 每次显示页面时检查登录状态和清理处理状态
|
||
this.updateLoginStatus()
|
||
this.setData({ isProcessing: false }) // 清理处理状态
|
||
},
|
||
|
||
|
||
checkDayType() {
|
||
const currentHour = new Date().getHours();
|
||
const currentDate = new Date().toLocaleDateString('zh-CN');
|
||
const dayType = currentHour >= 6 && currentHour < 12 ? 'morning' :
|
||
currentHour >= 12 && currentHour < 18 ? 'afternoon' : 'night';
|
||
this.setData({
|
||
current_date: currentDate,
|
||
day_type: dayType as IDayType
|
||
});
|
||
},
|
||
|
||
// 加载每日摘要数据
|
||
async loadDailySummary(page: number = 1) {
|
||
try {
|
||
// 只有在第一页时才显示加载状态(下拉刷新)
|
||
if (page === 1) {
|
||
this.setData({ isLoading: true });
|
||
}
|
||
|
||
const result = await apiManager.getDailySummary(page, this.data.size);
|
||
const todaySummary = await apiManager.getTodaySummary(page, this.data.size);
|
||
|
||
// 处理数据,按年份分组
|
||
const processedItems = [...result.items, ...todaySummary.items].map(item => ({
|
||
...item,
|
||
images: item.image_ids && item.thumbnail_ids ?
|
||
item.image_ids.map((imageId: string, index: number) => ({
|
||
image_id: imageId,
|
||
thumbnail_id: item.thumbnail_ids![index],
|
||
thumbnail_url: `${this.data.fileBaseUrl}/${item.thumbnail_ids![index]}`,
|
||
image_url: `${this.data.fileBaseUrl}/${imageId}`
|
||
})) : []
|
||
}));
|
||
|
||
// 如果是第一页,替换数据;否则追加数据
|
||
const newData = page === 1 ? processedItems : [...this.data.groupedHistory, ...processedItems];
|
||
|
||
// 按年份分组
|
||
const currentYear = new Date().getFullYear();
|
||
const grouped: any = {};
|
||
|
||
newData.forEach(item => {
|
||
const date = new Date(item.summary_time);
|
||
const year = date.getFullYear();
|
||
const month = date.getMonth() + 1;
|
||
const day = date.getDate();
|
||
|
||
if (!grouped[year]) {
|
||
grouped[year] = [];
|
||
}
|
||
|
||
grouped[year].push({
|
||
...item,
|
||
monthDay: `${month}-${day}`
|
||
});
|
||
});
|
||
|
||
// 转换为数组形式并按年份排序
|
||
const groupedArray = Object.keys(grouped)
|
||
.map(year => ({
|
||
year: parseInt(year),
|
||
isCurrentYear: parseInt(year) === currentYear,
|
||
items: grouped[year]
|
||
}))
|
||
.sort((a, b) => b.year - a.year);
|
||
|
||
this.setData({
|
||
groupedHistory: groupedArray,
|
||
page: result.page,
|
||
total: result.total,
|
||
hasMore: newData.length < result.total,
|
||
isLoading: false,
|
||
});
|
||
console.log('---lisa-groupedHistory', this.data.groupedHistory)
|
||
} catch (error) {
|
||
console.error('加载每日摘要失败:', error);
|
||
this.setData({ isLoading: false });
|
||
wx.showToast({
|
||
title: '加载失败',
|
||
icon: 'none'
|
||
});
|
||
}
|
||
},
|
||
|
||
// 触底加载更多数据
|
||
onReachBottom() {
|
||
if (this.data.hasMore && !this.data.isLoading) {
|
||
const nextPage = this.data.page + 1;
|
||
this.loadDailySummary(nextPage);
|
||
}
|
||
},
|
||
|
||
onPageScroll(e: any) {
|
||
const scrollTop = e.scrollTop;
|
||
if (scrollTop >= 30) {
|
||
this.setData({
|
||
move_camera_pos_to: 'top',
|
||
})
|
||
} else {
|
||
this.setData({
|
||
move_camera_pos_to: 'bottom',
|
||
})
|
||
}
|
||
},
|
||
|
||
// 下拉刷新
|
||
onPullDownRefresh() {
|
||
this.setData({
|
||
page: 1,
|
||
});
|
||
this.loadDailySummary(1).then(() => {
|
||
wx.stopPullDownRefresh();
|
||
});
|
||
},
|
||
|
||
// 图片点击事件
|
||
onImageTap(e: any) {
|
||
const { imageId } = e.currentTarget.dataset;
|
||
if (imageId) {
|
||
wx.navigateTo({
|
||
url: `/pages/result_show/result_show?imageId=${imageId}`
|
||
})
|
||
}
|
||
},
|
||
|
||
onImageCardTap(e: any) {
|
||
const { imageItems } = e.currentTarget.dataset;
|
||
if (!imageItems?.images?.length) return;
|
||
|
||
const items = imageItems.images.map((item: any) => ({
|
||
image_id: item.image_id,
|
||
image: item.thumbnail_url,
|
||
}));
|
||
ActionSheet.show({
|
||
theme: ActionSheetTheme.Grid,
|
||
selector: '#t-images-sheet',
|
||
context: this,
|
||
items,
|
||
cancelText: '取消'
|
||
});
|
||
},
|
||
|
||
// 检查登录状态
|
||
async checkLoginStatus() {
|
||
try {
|
||
// 使用智能登录检查和更新登录状态
|
||
const loginResult = await apiManager.smartLogin()
|
||
|
||
if (loginResult) {
|
||
// 登录成功,更新全局状态
|
||
app.globalData.isLoggedIn = true
|
||
app.globalData.token = loginResult.access_token
|
||
this.updateLoginStatus()
|
||
console.log('登录状态验证成功')
|
||
return true
|
||
} else {
|
||
// 登录失败,跳转到登录页
|
||
console.log('登录状态验证失败,跳转到登录页')
|
||
wx.reLaunch({
|
||
url: '/pages/index/index'
|
||
})
|
||
return false
|
||
}
|
||
} catch (error) {
|
||
console.error('检查登录状态失败:', error)
|
||
// 发生错误时跳转到登录页
|
||
wx.reLaunch({
|
||
url: '/pages/index/index'
|
||
})
|
||
return false
|
||
}
|
||
},
|
||
|
||
// 更新登录状态
|
||
updateLoginStatus() {
|
||
this.setData({
|
||
isLoggedIn: app.globalData.isLoggedIn,
|
||
showLoginView: !app.globalData.isLoggedIn,
|
||
userInfo: app.globalData.userInfo
|
||
})
|
||
},
|
||
|
||
// 处理图片选择(合并拍照和相册选择功能)
|
||
handleImageSelect() {
|
||
if (this.data.isProcessing) return;
|
||
|
||
ActionSheet.show({
|
||
theme: ActionSheetTheme.List,
|
||
selector: '#t-action-sheet',
|
||
items: [
|
||
{
|
||
label: '拍照识别',
|
||
icon: 'camera'
|
||
},
|
||
{
|
||
label: '相册选择',
|
||
icon: 'image'
|
||
}
|
||
],
|
||
cancelText: '取消',
|
||
align: 'center',
|
||
description: ''
|
||
})
|
||
},
|
||
|
||
handleSelected(e: any) {
|
||
const { index } = e.detail;
|
||
console.log('用户选择:', index)
|
||
if (index === 0) {
|
||
this.handleTakePhoto();
|
||
} else if (index === 1) {
|
||
this.handleChooseFromAlbum();
|
||
}
|
||
},
|
||
|
||
handleImageSelected(e: any) {
|
||
console.log('用户选择:', e)
|
||
if (e.detail.selected === 'cancel') return;
|
||
|
||
const { image_id } = e.detail.selected
|
||
if (image_id) {
|
||
wx.navigateTo({
|
||
url: `/pages/result_show/result_show?imageId=${image_id}`
|
||
})
|
||
}
|
||
},
|
||
|
||
// 拍照
|
||
async handleTakePhoto() {
|
||
try {
|
||
this.setData({ isProcessing: true })
|
||
wx.showLoading({ title: '准备拍照...' })
|
||
|
||
const imagePath = await imageManager.takePhoto({
|
||
quality: 80,
|
||
maxWidth: 1920,
|
||
maxHeight: 1920
|
||
})
|
||
|
||
wx.hideLoading()
|
||
console.log('拍照成功:', imagePath)
|
||
|
||
// 直接跳转到结果页面
|
||
this.navigateToResult(imagePath)
|
||
|
||
} catch (error: any) {
|
||
wx.hideLoading()
|
||
this.setData({ isProcessing: false })
|
||
console.error('拍照失败:', error)
|
||
|
||
if (error?.message !== '用户取消选择') {
|
||
wx.showToast({
|
||
title: '拍照失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
}
|
||
},
|
||
|
||
// 从相册选择
|
||
async handleChooseFromAlbum() {
|
||
try {
|
||
this.setData({ isProcessing: true })
|
||
wx.showLoading({ title: '准备选择图片...' })
|
||
|
||
const imagePath = await imageManager.chooseFromAlbum({
|
||
quality: 80,
|
||
maxWidth: 1920,
|
||
maxHeight: 1920
|
||
})
|
||
|
||
wx.hideLoading()
|
||
console.log('选择图片成功:', imagePath)
|
||
|
||
// 直接跳转到结果页面
|
||
this.navigateToResult(imagePath)
|
||
|
||
} catch (error: any) {
|
||
wx.hideLoading()
|
||
this.setData({ isProcessing: false })
|
||
console.error('选择图片失败:', error)
|
||
|
||
if (error?.message !== '用户取消选择') {
|
||
wx.showToast({
|
||
title: '选择图片失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
}
|
||
},
|
||
|
||
// 跳转到结果页面
|
||
navigateToResult(imagePath: string) {
|
||
try {
|
||
console.log('跳转到结果页面:', imagePath)
|
||
|
||
// 跳转到结果页面并传递图片路径
|
||
wx.navigateTo({
|
||
url: `/pages/result/result?imagePath=${encodeURIComponent(imagePath)}`
|
||
})
|
||
|
||
} catch (error) {
|
||
console.error('跳转结果页面失败:', error)
|
||
this.setData({ isProcessing: false })
|
||
wx.showToast({
|
||
title: '操作失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
// 退出登录
|
||
// handleLogout() {
|
||
// wx.showModal({
|
||
// title: '确认退出',
|
||
// content: '确定要退出登录吗?',
|
||
// success: (res) => {
|
||
// if (res.confirm) {
|
||
// // 清理登录状态
|
||
// app.globalData.isLoggedIn = false
|
||
// app.globalData.token = undefined
|
||
// app.globalData.userInfo = undefined
|
||
|
||
// wx.removeStorageSync('token')
|
||
// wx.removeStorageSync('userInfo')
|
||
// wx.removeStorageSync('tokenExpiry')
|
||
|
||
// this.updateLoginStatus()
|
||
|
||
// wx.showToast({
|
||
// title: '已退出登录',
|
||
// icon: 'success'
|
||
// })
|
||
|
||
// // 跳转到登录页
|
||
// setTimeout(() => {
|
||
// wx.reLaunch({
|
||
// url: '/pages/index/index'
|
||
// })
|
||
// }, 1500)
|
||
// }
|
||
// }
|
||
// })
|
||
// }
|
||
}) |