Files
ai_wht_wechat/miniprogram/miniprogram/pages/profile/profile.ts
2026-01-06 19:37:06 +08:00

389 lines
9.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// pages/profile/profile.ts
import { EmployeeService } from '../../services/employee';
import { API, isDevOrTrial } from '../../config/api';
import { getImageUrl } from '../../utils/util';
Page({
data: {
username: '管理员',
enterpriseName: '',
avatar: '',
publishedCount: 0,
userInfo: null as any,
isBoundXHS: false,
xhsAccount: '',
publishRecords: [] as any[], // 发布记录列表
currentPage: 1, // 当前页码
pageSize: 10, // 每页数量
hasMore: true, // 是否还有更多数据
loading: false, // 是否正在加载
showLogoutBtn: false, // 是否显示退出登录按钮(开发版和体验版)
showUnbindDialog: false // 是否显示解绑确认弹窗
},
onLoad() {
// 检查登录状态
const token = wx.getStorageSync('token');
if (!token) {
wx.redirectTo({
url: '/pages/login/login'
});
return;
}
// 设置是否显示退出登录按钮(开发版和体验版显示)
this.setData({
showLogoutBtn: isDevOrTrial()
});
// 加载用户信息
this.loadUserInfo();
// 加载发布记录
this.loadPublishRecords();
},
onShow() {
// 每次显示页面时刷新数据
this.loadUserInfo();
this.loadPublishRecords(true); // 重置加载
},
// 加载用户信息
async loadUserInfo() {
try {
const response = await EmployeeService.getProfile();
if (response.code === 200 && response.data) {
const userInfo = response.data;
this.setData({
username: userInfo.name,
enterpriseName: userInfo.enterprise_name || '',
avatar: getImageUrl(userInfo.avatar),
userInfo,
isBoundXHS: userInfo.is_bound_xhs === 1,
xhsAccount: userInfo.xhs_account || ''
});
}
} catch (error) {
console.error('加载用户信息失败:', error);
// 使用本地存储的备用数据
const username = wx.getStorageSync('username');
if (username) {
this.setData({ username });
}
}
},
// 加载发布记录
async loadPublishRecords(reset: boolean = false) {
// 如果正在加载或没有更多数据,直接返回
if (this.data.loading || (!reset && !this.data.hasMore)) {
return;
}
this.setData({ loading: true });
try {
const page = reset ? 1 : this.data.currentPage;
const response = await EmployeeService.getMyPublishRecords(page, this.data.pageSize);
if (response.code === 200 && response.data) {
const records = response.data.list || [];
// 提取封面图片(使用第一张图片)
const processedRecords = records.map((record: any) => ({
...record,
cover_image: record.images && record.images.length > 0
? getImageUrl(record.images[0].image_url)
: '/images/default-cover.png'
}));
// 如果是重置,替换数据;否则追加数据
const newRecords = reset ? processedRecords : [...this.data.publishRecords, ...processedRecords];
this.setData({
publishedCount: response.data.total || 0,
publishRecords: newRecords,
currentPage: page + 1,
hasMore: newRecords.length < (response.data.total || 0),
loading: false
});
}
} catch (error) {
console.error('加载发布记录失败:', error);
this.setData({
publishedCount: 0,
publishRecords: [],
loading: false,
hasMore: false
});
}
},
// 滚动到底部加载更多
onReachBottom() {
this.loadPublishRecords(false);
},
// 下拉刷新
onPullDownRefresh() {
this.loadUserInfo();
this.loadPublishRecords(true);
setTimeout(() => {
wx.stopPullDownRefresh();
}, 1000);
},
// 选择头像
chooseAvatar() {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFiles[0].tempFilePath;
await this.uploadAvatar(tempFilePath);
},
fail: (err) => {
console.error('选择图片失败:', err);
if (err.errMsg !== 'chooseMedia:fail cancel') {
wx.showToast({
title: '选择图片失败',
icon: 'none'
});
}
}
});
},
// 上传头像
async uploadAvatar(filePath: string) {
wx.showLoading({ title: '上传中...', mask: true });
try {
// 获取 token
const token = wx.getStorageSync('token');
if (!token) {
throw new Error('未登录');
}
// 上传到 OSS
const uploadResult = await this.uploadToOSS(filePath);
if (!uploadResult.url) {
throw new Error('上传失败');
}
// 更新用户资料
const response = await EmployeeService.updateProfile({
avatar: uploadResult.url
});
wx.hideLoading();
if (response.code === 200) {
wx.showToast({
title: '更换成功',
icon: 'success'
});
// 更新本地头像
this.setData({
avatar: getImageUrl(uploadResult.url)
});
} else {
throw new Error(response.message || '更新失败');
}
} catch (error: any) {
console.error('上传头像失败:', error);
wx.hideLoading();
wx.showToast({
title: error.message || '上传失败',
icon: 'none'
});
}
},
// 上传文件到 OSS
async uploadToOSS(filePath: string): Promise<{ url: string }> {
return new Promise((resolve, reject) => {
const token = wx.getStorageSync('token');
wx.uploadFile({
url: `${API.baseURL}/api/employee/upload-avatar`,
filePath: filePath,
name: 'file',
header: {
'Authorization': `Bearer ${token}`
},
success: (res) => {
try {
const data = JSON.parse(res.data);
if (data.code === 200 && data.data && data.data.url) {
resolve({ url: data.data.url });
} else {
reject(new Error(data.message || '上传失败'));
}
} catch (err) {
reject(new Error('解析响应失败'));
}
},
fail: (err) => {
reject(err);
}
});
});
},
// 处理小红书账号点击
handleAccountClick() {
if (this.data.isBoundXHS) {
// 已绑定,显示自定义解绑确认弹窗
this.setData({
showUnbindDialog: true
});
} else {
// 未绑定,跳转绑定页
wx.navigateTo({
url: '/pages/profile/platform-bind/platform-bind'
});
}
},
// 隐藏弹窗
hideDialog() {
this.setData({
showUnbindDialog: false
});
},
// 阻止事件冒泡
stopPropagation() {
// 空函数,用于阻止事件冒泡
},
// 确认解绑
async confirmUnbind() {
// 先隐藏弹窗
this.setData({
showUnbindDialog: false
});
// 执行解绑操作
await this.handleUnbind();
},
// 执行解绑操作
async handleUnbind() {
wx.showLoading({ title: '解绑中...', mask: true });
try {
const response = await EmployeeService.unbindXHS();
if (response.code === 200) {
wx.hideLoading();
wx.showToast({
title: '解绑成功',
icon: 'success'
});
// 更新绑定状态
this.setData({
isBoundXHS: false,
xhsAccount: ''
});
} else {
throw new Error(response.message || '解绑失败');
}
} catch (error: any) {
console.error('解绑失败:', error);
wx.hideLoading();
wx.showToast({
title: error.message || '解绑失败',
icon: 'none'
});
}
},
// 跳转到发布记录详情
viewRecordDetail(e: any) {
const { id } = e.currentTarget.dataset;
wx.navigateTo({
url: `/pages/profile/article-detail/article-detail?id=${id}`
});
},
// 跳转到发布记录详情(旧方法,保留兼容)
goToRecordDetail(e: any) {
const { id } = e.currentTarget.dataset;
wx.navigateTo({
url: `/pages/profile/article-detail/article-detail?id=${id}`
});
},
// 返回首页
goToHome() {
wx.redirectTo({
url: '/pages/home/home'
});
},
// 已发布文章
goToPublished() {
wx.navigateTo({
url: '/pages/profile/published/published'
});
},
// 意见反馈
goToFeedback() {
wx.navigateTo({
url: '/pages/profile/feedback/feedback'
});
},
// 关于我们
goToAbout() {
wx.navigateTo({
url: '/pages/profile/about/about'
});
},
// 退出登录
handleLogout() {
wx.showModal({
title: '提示',
content: '确定要退出登录吗?',
success: async (res) => {
if (res.confirm) {
try {
// 调用后端退出登录接口删除Redis中token
const token = wx.getStorageSync('token');
if (token) {
await wx.request({
url: `${API.baseURL}/api/logout`,
method: 'POST',
header: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
}
} catch (error) {
console.error('退出登录接口调用失败:', error);
// 即使接口失败也继续清理本地状态
}
// 清除本地存储
wx.clearStorageSync();
// 使用 reLaunch 跳转到登录页,清空页面栈,防止返回
wx.reLaunch({
url: '/pages/login/login'
});
}
}
});
}
});