123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385 |
- // pages/me/me.js
- // import { models, db, _ } from '../../utils/cloudbase.js'
- import { getDB, getModels, getCommand, getTempFileURLs, getClient } from '../../utils/cloudbase.js'
- Page({
- data: {
- // role: "teacher",
- userInfo: {},
- orderStatus: [],
- displayPhone: '',
- xxdata: {},
- historyItems: [],
- xiugaiimg: '',
- xiangjiimg: '',
- xiazi: '',
- // souchangs: '',
- },
- onShow() {
- if (typeof this.getTabBar === 'function' && this.getTabBar()) {
- this.getTabBar().setSelected(3); // 比如首页就是 0
- }
- // 每次进入页面都会触发
- this.getUserInfo();
- // this.getcollect();
- this.getpurchasehistory();
- },
- async onLoad(options) {
- this.getUserInfo();
- const orderStatus = [
- { text: '全部订单', type: 1 },
- { text: '待付款', type: 2 },
- { text: '待收货', type: 3 },
- { text: '已完成', type: 4 }
- ]
- const fileIDs = [
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/qvanbu.png',
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/daifukuan.png',
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/daishouhuo.png',
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/yiwancheng.png',
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiugai.png',
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiangji.png',
- 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiazi.png',
- ];
- const fileList = await getTempFileURLs(fileIDs)
- // 将 tempFilePaths.slice(0, 3) 分配到 orderStatus 中
- const updatedOrderStatus = orderStatus.map((item, index) => {
- return {
- ...item,
- url: fileList[index].tempFileURL // 为每个对象添加 url 属性
- };
- });
- this.setData({
- orderStatus: updatedOrderStatus,
- xiugaiimg: fileList[4].tempFileURL,
- xiangjiimg: fileList[5].tempFileURL,
- xiazi: fileList[6].tempFileURL,
- })
-
- // // 并发下载多个 fileID
- // Promise.all(
- // fileIDs.map(fileID => wx.cloud.downloadFile({ fileID }))
- // ).then(results => {
- // // 每个 result 对应一个下载结果
- // const tempFilePaths = results.map(r => r.tempFilePath);
- // console.log('全部下载成功:', tempFilePaths);
- // // 将 tempFilePaths.slice(0, 3) 分配到 orderStatus 中
- // const updatedOrderStatus = orderStatus.map((item, index) => {
- // return {
- // ...item,
- // url: tempFilePaths[index] // 为每个对象添加 url 属性
- // };
- // });
- // console.log(updatedOrderStatus, 'updatedOrderStatus');
- // this.setData({
- // orderStatus: updatedOrderStatus,
- // xiugaiimg: tempFilePaths[4],
- // xiangjiimg: tempFilePaths[5],
- // xiazi: tempFilePaths[6],
- // // souchangs: tempFilePaths[7],
- // });
- // }).catch(err => {
- // console.error('有文件下载失败:', err);
- // });
- },
- // 手机号加密
- hidePhone(phone) {
- if (!phone || phone.length !== 11) return phone || '未绑定';
- return phone.substr(0, 3) + '****' + phone.substr(7, 4);
- },
- // 用户信息
- async getUserInfo() {
- // 获取用户信息
- const userInfo = wx.getStorageSync('userInfo');
-
- // 设置默认头像为 fileID,如果有就转换临时链接
- if (userInfo.img) {
- const client = await getClient();
- try {
- const tempFile = await client.getTempFileURL({
- fileList: [userInfo.img]
- });
- if (tempFile.fileList && tempFile.fileList.length > 0) {
- userInfo.img = tempFile.fileList[0].tempFileURL; // 用于页面渲染
- }
- } catch (err) {
- console.error('获取头像临时链接失败', err);
- }
- }
- this.setData({ userInfo }, () => {
- const phone = this.data.userInfo.phone;
- this.setData({
- displayPhone: this.hidePhone(phone)
- });
- });
- try {
- const models = await getModels()
- const { data } = await models.wx_school.get({
- filter: {
- where: {
- school_id: userInfo.school_id
- }
- },
- envType: "prod"
- });
- this.setData({
- xxdata: data
- });
- } catch (err) {
- console.error('获取学校数据失败:', err);
- }
- },
- // 下载历史
- async getpurchasehistory() {
- const userInfo = wx.getStorageSync('userInfo');
- const models = await getModels();
- const { data } = await models.parent_download_history.list({
- filter: {
- where: {
- wx_user_id: userInfo._id
- }
- },
- pageSize: 2,
- pageNumber: 1,
- getCount: true,
- envType: "prod",
- });
- const collectList = data.records || [];
- if (collectList.length === 0) {
- console.log('没有收藏记录');
- this.setData({ historyItems: [] });
- return;
- }
- // 提取 file_manage_id 列表
- const fileManagerIds = collectList.map(item => item.file_manage_id);
- // 查询 file_manage 表详情
- const fileDetailPromises = fileManagerIds.map(id => {
- return models.file_manage.list({
- filter: { where: { _id: id } },
- envType: "prod"
- })
- .then(async res => {
- const record = res.data?.records?.[0];
- if (!record) {
- console.warn(`未找到 _id 为 ${id} 的文件`);
- return null;
- }
- // ✅ 如果有 cover 字段且是 cloud://,获取临时链接
- if (record.cover && record.cover.startsWith('cloud://')) {
- try {
- const fileList = await getTempFileURLs([record.cover]);
- if (fileList && fileList.length > 0) {
- record.coverTemp = fileList[0].tempFileURL;
- }
- } catch (err) {
- console.error('获取历史记录封面临时链接失败', err);
- }
- } else {
- record.coverTemp = record.cover; // 已经是 http 链接
- }
- return record;
- })
- .catch(err => {
- console.error(`获取文件 ${id} 失败`, err);
- return null;
- });
- });
- // 等待所有查询完成
- const fileDetails = await Promise.all(fileDetailPromises);
- // 更新页面数据(过滤掉失败项,同时格式化时间)
- this.setData({
- historyItems: fileDetails.filter(Boolean).map(item => ({
- ...item,
- createdAt: this.formatTime(item.createdAt)
- }))
- });
- },
- formatTime(ts) {
- const date = new Date(ts);
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, '0');
- const d = String(date.getDate()).padStart(2, '0');
- const hh = String(date.getHours()).padStart(2, '0');
- const mm = String(date.getMinutes()).padStart(2, '0');
- const ss = String(date.getSeconds()).padStart(2, '0');
- return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
- },
- // 收藏列表
- // async getcollect() {
- // const { data } = await models.wx_collect.list({
- // filter: {
- // where: {
- // wx_user_id: this.data.userInfo._id
- // }
- // },
- // pageSize: 2, // 分页大小,建议指定,如需设置为其它值,需要和 pageNumber 配合使用,两者同时指定才会生效
- // pageNumber: 1, // 第几页
- // getCount: true, // 开启用来获取总数
- // envType: "prod",
- // });
-
- // // 返回查询到的数据列表 records 和 总数 total
- // console.log(data);
- // const collectList = data.records || [];
- // if (collectList.length === 0) {
- // console.log('没有收藏记录');
- // this.setData({ collectFiles: [] });
- // return;
- // }
- // // 第二步:提取 file_manager_id 列表
- // const fileManagerIds = collectList.map(item => item.file_manager_id);
- // // 第三步:批量查询 file_manage 表中对应的文件数据
- // const fileRes = await models.file_manage.list({
- // filter: {
- // where: {
- // _id: { $in: fileManagerIds } // 关键点:使用 $in 批量查询
- // }
- // },
- // envType: "prod",
- // });
- // // 第四步:更新页面数据
- // this.setData({
- // collectFiles: fileRes.data.records || []
- // });
- // console.log('收藏的文件数据:', fileRes.data.records);
- // },
- // 注销跳转
- handleLogout() {
- wx.navigateTo({
- url: `/subpackages/logoff/logoff`
- });
- },
- // 修改用户名跳转
- goToGoodsLists() {
- wx.navigateTo({
- url: '/subpackages/changename/changename?data=' + encodeURIComponent(JSON.stringify(this.data.userInfo))
- });
- },
- goToGoodsList(e) {
- const types = e.currentTarget.dataset.type
- wx.navigateTo({
- url: '/subpackages/order/order?type=' + encodeURIComponent(types)
- });
- },
- // 点击相机修改用户头像
- chooseAvatar() {
- wx.showActionSheet({
- itemList: ['拍照', '从相册选择'],
- success: (res) => {
- if (res.tapIndex === 0) {
- this.chooseImage('camera');
- } else if (res.tapIndex === 1) {
- this.chooseImage('album');
- }
- }
- });
- },
- chooseImage(sourceType) {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- sourceType: [sourceType], // 'camera' or 'album'
- success: (res) => {
- const tempFilePath = res.tempFiles[0].tempFilePath;
- // 可选择上传到云存储,也可以直接更新 UI
- this.uploadAvatar(tempFilePath);
- },
- fail: (err) => {
- console.error('选择图片失败', err);
- }
- });
- },
- async uploadAvatar(filePath) {
- const client = await getClient(); // 获取跨小程序云实例
- const cloudPath = 'avatar/' + Date.now() + '-' + Math.floor(Math.random() * 1000) + '.png';
- const uploadRes = await client.uploadFile({
- cloudPath,
- filePath,
- });
- // 上传成功后更新用户头像
- const avatarUrl = uploadRes.fileID;
- console.log(avatarUrl, 'avatarUrl');
- // 获取临时 http 链接
- const tempRes = await client.getTempFileURL({
- fileList: [avatarUrl]
- });
- const tempURL = tempRes.fileList?.[0]?.tempFileURL || '';
- // 更新头像显示
- this.setData({
- 'userInfo.img': tempURL
- });
- const cachedUserInfo = wx.getStorageSync('userInfo') || {};
- cachedUserInfo.img = avatarUrl;
- wx.setStorageSync('userInfo', cachedUserInfo);
- console.log('缓存更新成功:', this.data.userInfo._id);
- // TODO: 同步更新数据库中头像字段(可选)
- const models = await getModels()
- const { data } = await models.wx_user.update({
- data: {
- img: avatarUrl, // 头像
- },
- filter: {
- where: {
- _id: { $eq: this.data.userInfo._id }, // 推荐传入_id数据标识进行操作
- delete: { $eq: 0 },
- }
- },
- // envType: pre 体验环境, prod 正式环境
- envType: "prod",
- });
-
- console.log(data,'datadatadata');
- if (data.count > 0) {
- wx.showToast({
- title: '头像修改成功',
- icon: 'success'
- });
- } else {
- wx.showToast({
- title: '头像修改失败',
- icon: 'none'
- });
- }
- }
- });
|