me.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // pages/me/me.js
  2. import { models, db, _ } from '../../utils/cloudbase.js'
  3. Page({
  4. data: {
  5. userInfo: {},
  6. displayPhone: '',
  7. xxdata: {},
  8. collectFiles: [],
  9. historyItems: [],
  10. xiugaiimg: '',
  11. xiangjiimg: '',
  12. xiazi: '',
  13. souchangs: '',
  14. },
  15. onShow() {
  16. if (typeof this.getTabBar === 'function' && this.getTabBar()) {
  17. this.getTabBar().setSelected(3); // 比如首页就是 0
  18. }
  19. // 每次进入页面都会触发
  20. this.getUserInfo();
  21. this.getcollect();
  22. this.getpurchasehistory();
  23. },
  24. onLoad(options) {
  25. const fileIDs = [
  26. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiugai.png',
  27. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiangji.png',
  28. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiazi.png',
  29. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/soucangs.png'
  30. ];
  31. // 并发下载多个 fileID
  32. Promise.all(
  33. fileIDs.map(fileID => wx.cloud.downloadFile({ fileID }))
  34. ).then(results => {
  35. // 每个 result 对应一个下载结果
  36. const tempFilePaths = results.map(r => r.tempFilePath);
  37. console.log('全部下载成功:', tempFilePaths);
  38. this.setData({
  39. xiugaiimg: tempFilePaths[0],
  40. xiangjiimg: tempFilePaths[1],
  41. xiazi: tempFilePaths[2],
  42. souchangs: tempFilePaths[3],
  43. });
  44. }).catch(err => {
  45. console.error('有文件下载失败:', err);
  46. });
  47. },
  48. // 手机号加密
  49. hidePhone(phone) {
  50. if (!phone || phone.length !== 11) return phone || '未绑定';
  51. return phone.substr(0, 3) + '****' + phone.substr(7, 4);
  52. },
  53. // 用户信息
  54. async getUserInfo() {
  55. // 获取用户信息
  56. const userInfo = wx.getStorageSync('userInfo');
  57. this.setData({ userInfo }, () => {
  58. const phone = this.data.userInfo.phone;
  59. this.setData({
  60. displayPhone: this.hidePhone(phone)
  61. });
  62. });
  63. try {
  64. const { data } = await models.wx_school.get({
  65. filter: {
  66. where: {
  67. school_id: userInfo.school_id
  68. }
  69. },
  70. envType: "prod"
  71. });
  72. this.setData({
  73. xxdata: data
  74. });
  75. } catch (err) {
  76. console.error('获取学校数据失败:', err);
  77. }
  78. },
  79. // 下载历史
  80. async getpurchasehistory() {
  81. const { data } = await models.download_history.list({
  82. filter: {
  83. where: {
  84. user_id: this.data.userInfo._id
  85. }
  86. },
  87. pageSize: 2, // 分页大小,建议指定,如需设置为其它值,需要和 pageNumber 配合使用,两者同时指定才会生效
  88. pageNumber: 1, // 第几页
  89. getCount: true, // 开启用来获取总数
  90. envType: "prod",
  91. });
  92. // 返回查询到的数据列表 records 和 总数 total
  93. console.log(data);
  94. const collectList = data.records || [];
  95. if (collectList.length === 0) {
  96. console.log('没有收藏记录');
  97. this.setData({ historyItems: [] });
  98. return;
  99. }
  100. // 第二步:提取 file_manage_id 列表
  101. const fileManagerIds = collectList.map(item => item.file_manage_id);
  102. // 第三步:逐个查询 file_manage 表详情
  103. const fileDetailPromises = fileManagerIds.map(id => {
  104. return models.file_manage.list({
  105. filter: {
  106. where: {
  107. _id: id
  108. }
  109. },
  110. envType: "prod"
  111. })
  112. .then(res => {
  113. const record = res.data?.records?.[0];
  114. if (!record) {
  115. console.warn(`未找到 _id 为 ${id} 的文件`);
  116. }
  117. return record || null;
  118. })
  119. .catch(err => {
  120. console.error(`获取文件 ${id} 失败`, err);
  121. return null;
  122. });
  123. });
  124. console.log(await Promise.all(fileDetailPromises), 'fileDetailPromises');
  125. // 等待所有查询完成
  126. const fileDetails = await Promise.all(fileDetailPromises);
  127. // 第四步:更新页面数据(过滤掉失败项)
  128. this.setData({
  129. // historyItems: fileDetails.filter(Boolean)
  130. historyItems: fileDetails.filter(Boolean).map(item => ({
  131. ...item,
  132. createdAt: this.formatTime(item.createdAt) // 格式化时间
  133. }))
  134. });
  135. },
  136. // 收藏列表
  137. async getcollect() {
  138. const { data } = await models.wx_collect.list({
  139. filter: {
  140. where: {
  141. wx_user_id: this.data.userInfo._id
  142. }
  143. },
  144. pageSize: 2, // 分页大小,建议指定,如需设置为其它值,需要和 pageNumber 配合使用,两者同时指定才会生效
  145. pageNumber: 1, // 第几页
  146. getCount: true, // 开启用来获取总数
  147. envType: "prod",
  148. });
  149. // 返回查询到的数据列表 records 和 总数 total
  150. console.log(data);
  151. const collectList = data.records || [];
  152. if (collectList.length === 0) {
  153. console.log('没有收藏记录');
  154. this.setData({ collectFiles: [] });
  155. return;
  156. }
  157. // 第二步:提取 file_manager_id 列表
  158. const fileManagerIds = collectList.map(item => item.file_manager_id);
  159. // 第三步:批量查询 file_manage 表中对应的文件数据
  160. const fileRes = await models.file_manage.list({
  161. filter: {
  162. where: {
  163. _id: { $in: fileManagerIds } // 关键点:使用 $in 批量查询
  164. }
  165. },
  166. envType: "prod",
  167. });
  168. // 第四步:更新页面数据
  169. this.setData({
  170. // collectFiles: fileRes.data.records || []
  171. collectFiles: (fileRes.data.records || []).map(item => ({
  172. ...item,
  173. createdAt: this.formatTime(item.createdAt)
  174. }))
  175. });
  176. console.log('收藏的文件数据:', fileRes.data.records);
  177. },
  178. formatTime(ts) {
  179. const date = new Date(ts);
  180. const y = date.getFullYear();
  181. const m = String(date.getMonth() + 1).padStart(2, '0');
  182. const d = String(date.getDate()).padStart(2, '0');
  183. const hh = String(date.getHours()).padStart(2, '0');
  184. const mm = String(date.getMinutes()).padStart(2, '0');
  185. const ss = String(date.getSeconds()).padStart(2, '0');
  186. return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
  187. },
  188. // 注销跳转
  189. handleLogout() {
  190. wx.navigateTo({
  191. url: `/subpackages/logoff/logoff`
  192. });
  193. },
  194. // 修改用户名跳转
  195. goToGoodsLists() {
  196. wx.navigateTo({
  197. url: '/subpackages/changename/changename?data=' + encodeURIComponent(JSON.stringify(this.data.userInfo))
  198. });
  199. },
  200. // 点击相机修改用户头像
  201. chooseAvatar() {
  202. wx.showActionSheet({
  203. itemList: ['拍照', '从相册选择'],
  204. success: (res) => {
  205. if (res.tapIndex === 0) {
  206. this.chooseImage('camera');
  207. } else if (res.tapIndex === 1) {
  208. this.chooseImage('album');
  209. }
  210. }
  211. });
  212. },
  213. chooseImage(sourceType) {
  214. wx.chooseMedia({
  215. count: 1,
  216. mediaType: ['image'],
  217. sourceType: [sourceType], // 'camera' or 'album'
  218. success: (res) => {
  219. const tempFilePath = res.tempFiles[0].tempFilePath;
  220. // 可选择上传到云存储,也可以直接更新 UI
  221. this.uploadAvatar(tempFilePath);
  222. },
  223. fail: (err) => {
  224. console.error('选择图片失败', err);
  225. }
  226. });
  227. },
  228. async uploadAvatar(filePath) {
  229. const cloudPath = 'avatar/' + Date.now() + '-' + Math.floor(Math.random() * 1000) + '.png';
  230. const uploadRes = await wx.cloud.uploadFile({
  231. cloudPath,
  232. filePath,
  233. });
  234. // 上传成功后更新用户头像
  235. const avatarUrl = uploadRes.fileID;
  236. console.log(avatarUrl, 'avatarUrl');
  237. // 更新头像显示
  238. this.setData({
  239. 'userInfo.img': avatarUrl
  240. });
  241. const cachedUserInfo = wx.getStorageSync('userInfo') || {};
  242. cachedUserInfo.img = avatarUrl;
  243. wx.setStorageSync('userInfo', cachedUserInfo);
  244. console.log('缓存更新成功:', cachedUserInfo);
  245. // TODO: 同步更新数据库中头像字段(可选)
  246. const { data } = await models.wx_teacher_user.update({
  247. data: {
  248. img: avatarUrl, // 头像
  249. },
  250. filter: {
  251. where: {
  252. _id: { $eq: this.data.userInfo._id }, // 推荐传入_id数据标识进行操作
  253. delete: { $eq: 1 },
  254. }
  255. },
  256. // envType: pre 体验环境, prod 正式环境
  257. envType: "prod",
  258. });
  259. if (data.count > 0) {
  260. wx.showToast({
  261. title: '头像修改成功',
  262. icon: 'success'
  263. });
  264. } else {
  265. wx.showToast({
  266. title: '头像修改失败',
  267. icon: 'none'
  268. });
  269. }
  270. }
  271. });