me.js 11 KB

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