order.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // import { models, db, _ } from '../../utils/cloudbase.js'
  2. import { getDB, getModels, getCommand, getTempFileURLs } from '../../utils/cloudbase.js'
  3. Page({
  4. data: {
  5. categoriesindex: 1,
  6. categories: [
  7. {
  8. title: '全部',
  9. type: 1,
  10. },
  11. {
  12. title: '待支付',
  13. type: 2,
  14. },
  15. {
  16. title: '待收货',
  17. type: 3,
  18. },
  19. {
  20. title: '已完成',
  21. type: 4,
  22. }
  23. ],
  24. searchText: '', // 搜索关键词
  25. orders: [],
  26. souimg: '',
  27. pageNumber: 1,
  28. pageSize: 10,
  29. hasMore: true, // 是否还有更多数据
  30. isLoading: false, // 防止多次触发
  31. },
  32. onShow() {
  33. this.setData({
  34. pageNumber: 1,
  35. hasMore: true,
  36. orders: []
  37. }, () => {
  38. this.getdatalist(false);
  39. });
  40. console.log('123123');
  41. },
  42. async onLoad(options) {
  43. const type = Number(options.type) || 1;
  44. console.log('收到的 type 参数:', type);
  45. // 根据 type 加载数据
  46. this.setData({
  47. categoriesindex: type
  48. }, () => {
  49. this.getdatalist(); // 确保 this 指向正确
  50. });
  51. const fileIDs = [
  52. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/sou.png',
  53. ];
  54. const fileList = await getTempFileURLs(fileIDs)
  55. this.setData({
  56. souimg: fileList[0].tempFileURL,
  57. })
  58. // // 并发下载多个 fileID
  59. // Promise.all(
  60. // fileIDs.map(fileID => wx.cloud.downloadFile({ fileID }))
  61. // ).then(results => {
  62. // // 每个 result 对应一个下载结果
  63. // const tempFilePaths = results.map(r => r.tempFilePath);
  64. // console.log('全部下载成功:', tempFilePaths);
  65. // this.setData({
  66. // souimg: tempFilePaths[0]
  67. // });
  68. // }).catch(err => {
  69. // console.error('有文件下载失败:', err);
  70. // });
  71. },
  72. onReachBottom() {
  73. // 上拉触底事件的处理函数
  74. this.loadMore();
  75. },
  76. loadMore() {
  77. // 加载更多数据的逻辑
  78. console.log('加载更多');
  79. // this.getdatalist(true);
  80. if (this.data.isLoading || !this.data.hasMore) return;
  81. this.setData({ isLoading: true });
  82. this.getdatalist(true);
  83. },
  84. // 模糊搜索
  85. onSearchInput(e) {
  86. const value = e.detail.value.trim();
  87. this.setData({
  88. searchText: value,
  89. pageNumber: 1,
  90. hasMore: true,
  91. orders: []
  92. }, () => {
  93. this.getdatalist();
  94. });
  95. },
  96. async getdatalist(isLoadMore = false) {
  97. const db = await getDB()
  98. const models = await getModels()
  99. const _ = await getCommand()
  100. if (this.data.isLoading || !this.data.hasMore) return;
  101. this.setData({ isLoading: true });
  102. const { pageNumber, pageSize, categoriesindex, searchText, orders } = this.data;
  103. let dbRegExp = null;
  104. let jsRegExp = null;
  105. if (searchText) {
  106. dbRegExp = db.RegExp({
  107. regexp: searchText,
  108. options: 'i'
  109. });
  110. jsRegExp = new RegExp(searchText, 'i');
  111. }
  112. // 构造订单表的筛选条件
  113. // 获取本地存储的用户信息
  114. const userInfo = wx.getStorageSync('userInfo');
  115. const userId = userInfo && userInfo._id ? userInfo._id : ''; // 根据你的userInfo结构取ID
  116. const schoolId = userInfo && userInfo.school_id ? userInfo.school_id : ''; // 根据你的userInfo结构取ID
  117. let orderWhere = {
  118. user_id: userId, // 每次必传
  119. school_id: schoolId
  120. };
  121. if (categoriesindex !== 1) {
  122. orderWhere.status = categoriesindex - 2;
  123. }
  124. if (dbRegExp) {
  125. orderWhere = _.and([
  126. orderWhere,
  127. { order_id: dbRegExp }
  128. ]);
  129. }
  130. try {
  131. // 第一步:查订单表
  132. const { data } = await models.orders.list({
  133. filter: { where: orderWhere },
  134. pageSize,
  135. pageNumber,
  136. getCount: true,
  137. envType: 'prod'
  138. });
  139. const orderList = data.records || [];
  140. if (orderList.length === 0) {
  141. this.setData({ hasMore: false, isLoading: false });
  142. return;
  143. }
  144. // 第二步:查商品表
  145. const fileManagerIds = orderList.map(item => item.merchandise_id);
  146. const fileDetailPromises = fileManagerIds.map(id => {
  147. return models.wx_merchandise.list({
  148. filter: { where: { _id: id } },
  149. envType: 'prod'
  150. }).then(res => res.data?.records?.[0] || null)
  151. .catch(err => {
  152. console.error(`商品获取失败: ${id}`, err);
  153. return null;
  154. });
  155. });
  156. const fileDetails = await Promise.all(fileDetailPromises);
  157. // 第三步:合并数据,并进行模糊搜索筛选(匹配一个就保留)
  158. const mergedOrders = [];
  159. for (let i = 0; i < orderList.length; i++) {
  160. const order = orderList[i];
  161. const merch = fileDetails[i];
  162. if (!merch) continue;
  163. if (jsRegExp) {
  164. const matchOrderId = jsRegExp.test(order._id || '');
  165. const matchName = jsRegExp.test(merch.name || '');
  166. if (!matchOrderId && !matchName) {
  167. continue; // 都没匹配上,跳过
  168. }
  169. }
  170. // 先把 _id 改名为 order_id
  171. const { _id, school_id, createdAt, ...restOrder } = order;
  172. const orderRenamed = {
  173. ...restOrder,
  174. orders_id: _id,
  175. schools_id: school_id,
  176. createdAt: this.formatTime(createdAt)
  177. };
  178. mergedOrders.push({
  179. ...orderRenamed,
  180. ...merch,
  181. createdAt: orderRenamed.createdAt // 覆盖掉可能的 merch.createdAt
  182. });
  183. }
  184. // 循环去查 groupbuy 表
  185. for (let item of mergedOrders) {
  186. try {
  187. const res = await models.wx_groupbuy_groupbuy.list({
  188. filter: { where: { groupbuy_id: item._id } },
  189. envType: "prod",
  190. });
  191. // 把查到的记录存入 specList,保证是数组
  192. item.specList = res.data.records || [];
  193. } catch (err) {
  194. console.error(`获取 groupbuy 失败,商品ID: ${item._id}`, err);
  195. item.specList = [];
  196. }
  197. }
  198. console.log(mergedOrders, '+++++++++++++++++++++++++++++');
  199. // 第五步:循环处理 specList 和商品主图
  200. for (let item of mergedOrders) {
  201. // 处理 groupbuy 里的 detail_images
  202. if (item.specList && item.specList.length > 0) {
  203. for (let i = 0; i < item.specList.length; i++) {
  204. const images = item.specList[i].detail_images || [];
  205. if (images.length > 0) {
  206. const tempFiles = await getTempFileURLs(images);
  207. item.specList[i].detail_images = tempFiles.map(f => f.tempFileURL);
  208. }
  209. }
  210. }
  211. // 处理商品主图 item.img
  212. if (item.img) {
  213. const tempFiles = await getTempFileURLs([item.img]);
  214. item.img = tempFiles[0].tempFileURL;
  215. }
  216. }
  217. // 第四步:更新数据
  218. this.setData({
  219. orders: isLoadMore ? orders.concat(mergedOrders) : mergedOrders,
  220. pageNumber: pageNumber + 1,
  221. hasMore: orderList.length === pageSize,
  222. isLoading: false
  223. });
  224. } catch (err) {
  225. console.error('获取数据失败:', err);
  226. this.setData({ isLoading: false });
  227. }
  228. },
  229. tabcategories(e) {
  230. const type = e.currentTarget.dataset.type;
  231. console.log('type:', type);
  232. this.setData({
  233. categoriesindex: type,
  234. searchText: '', // ✅ 清空搜索关键词
  235. pageNumber: 1, // 重置页码
  236. hasMore: true, // 重置是否有更多数据
  237. orders: [], // 清空旧数据
  238. }, () => {
  239. console.log('categoriesindex:', this.data.categoriesindex);
  240. this.getdatalist(false);
  241. });
  242. },
  243. formatTime(ts) {
  244. if (!ts) return '';
  245. const date = new Date(ts);
  246. const y = date.getFullYear();
  247. const m = String(date.getMonth() + 1).padStart(2, '0');
  248. const d = String(date.getDate()).padStart(2, '0');
  249. const hh = String(date.getHours()).padStart(2, '0');
  250. const mm = String(date.getMinutes()).padStart(2, '0');
  251. const ss = String(date.getSeconds()).padStart(2, '0');
  252. return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
  253. },
  254. // 处理第一个按钮的点击事件
  255. handleAction1: async function (event) {
  256. const models = await getModels()
  257. const index = event.currentTarget.dataset.index; // 获取点击的订单索引
  258. const status = this.data.orders[index].status; // 获取订单状态
  259. switch (status) {
  260. case 1:
  261. console.log("查看详情", index);
  262. const item = this.data.orders[index];
  263. wx.navigateTo({
  264. url: '/subpackages/orderdetails/orderdetails?data=' + encodeURIComponent(JSON.stringify(item))
  265. });
  266. // 执行查看详情的逻辑
  267. break;
  268. case 0:
  269. console.log("取消订单", index);
  270. // 执行取消订单的逻辑
  271. const items2 = this.data.orders[index];
  272. console.log(items2, 'itemsitemsitemsitems');
  273. const { data } = await models.orders.update({
  274. data: {
  275. status: 3, // 状态
  276. },
  277. filter: {
  278. where: {
  279. $and: [
  280. {
  281. _id: {
  282. $eq: items2.orders_id, // 推荐传入_id数据标识进行操作
  283. },
  284. },
  285. ]
  286. }
  287. },
  288. // envType: pre 体验环境, prod 正式环境
  289. envType: "prod",
  290. });
  291. // 返回更新成功的条数
  292. console.log(data);
  293. // { count: 1}
  294. if( data.count > 0) {
  295. this.setData({
  296. pageNumber: 1,
  297. hasMore: true,
  298. orders: []
  299. });
  300. await this.getdatalist(false); // 确保异步接口执行完毕后数据刷新
  301. wx.showToast({ title: '订单取消成功', icon: 'success' });
  302. } else {
  303. wx.showToast({ title: '订单取消失败', icon: 'none' });
  304. }
  305. break;
  306. case 2:
  307. console.log("申请售后", index);
  308. // 执行申请售后的逻辑
  309. const items = this.data.orders[index];
  310. console.log(items, 'itemsitemsitemsitems');
  311. wx.navigateTo({
  312. url: '/subpackages/afterservice/afterservice?data=' + encodeURIComponent(JSON.stringify(items))
  313. });
  314. break;
  315. case 3: // ✅ 新增
  316. console.log("查看详情", index);
  317. const itemm = this.data.orders[index];
  318. wx.navigateTo({
  319. url: '/subpackages/orderdetails/orderdetails?data=' + encodeURIComponent(JSON.stringify(itemm))
  320. });
  321. break;
  322. default:
  323. console.log("未知状态");
  324. }
  325. },
  326. // 处理第二个按钮的点击事件
  327. handleAction2: function (event) {
  328. const index = event.currentTarget.dataset.index; // 获取点击的订单索引
  329. const status = this.data.orders[index].status; // 获取订单状态
  330. switch (status) {
  331. case 1:
  332. console.log("确认收货", index);
  333. this.getyesordels(this.data.orders[index])
  334. break;
  335. case 0:
  336. console.log("立即支付", index);
  337. const selectedItems = [
  338. this.data.orders[index]
  339. ];
  340. console.log(selectedItems,'selectedItems');
  341. // 执行立即支付的逻辑
  342. wx.setStorageSync('checkoutItems', selectedItems);
  343. wx.navigateTo({
  344. url: '/subpackages/submitorder/submitorder'
  345. });
  346. break;
  347. case 2:
  348. console.log("再来一单", index);
  349. const rawItemm = this.data.orders[index];
  350. // 定义要排除的字段
  351. const excludeKeyss = [
  352. "adresses_id",
  353. "delete",
  354. "merchandise_id",
  355. "num_index",
  356. "order_id",
  357. "orders_id",
  358. "real_money",
  359. "schools_id",
  360. "specs_index",
  361. "status",
  362. "user_id",
  363. "groupbuy_id"
  364. ];
  365. // 过滤掉不需要的字段
  366. const item = Object.fromEntries(
  367. Object.entries(rawItemm).filter(([key]) => !excludeKeyss.includes(key))
  368. );
  369. wx.navigateTo({
  370. url: '/subpackages/productdetails/productdetails?data=' + encodeURIComponent(JSON.stringify(item))
  371. });
  372. break;
  373. case 3: // ✅ 新增
  374. console.log("再来一单", index);
  375. const rawItem = this.data.orders[index];
  376. const excludeKeys = [
  377. "adresses_id","delete","merchandise_id","num_index","order_id",
  378. "orders_id","real_money","schools_id","specs_index","status",
  379. "user_id","groupbuy_id"
  380. ];
  381. const itemms = Object.fromEntries(
  382. Object.entries(rawItem).filter(([key]) => !excludeKeys.includes(key))
  383. );
  384. wx.navigateTo({
  385. url: '/subpackages/productdetails/productdetails?data=' + encodeURIComponent(JSON.stringify(itemms))
  386. });
  387. break;
  388. default:
  389. console.log("未知状态");
  390. }
  391. },
  392. // 确认收货
  393. async getyesordels (list) {
  394. console.log(list, 'list');
  395. const userInfo = wx.getStorageSync('userInfo');
  396. const userId = userInfo && userInfo._id ? userInfo._id : ''; // 根据你的userInfo结构取ID
  397. const schoolId = userInfo && userInfo.school_id ? userInfo.school_id : ''; // 根据你的userInfo结构取ID
  398. const models = await getModels()
  399. const { data } = await models.orders.update({
  400. data: {
  401. status: 2, // 状态
  402. },
  403. filter: {
  404. where: {
  405. $and: [
  406. {
  407. _id: {
  408. $eq: list.orders_id, // 推荐传入_id数据标识进行操作
  409. },
  410. },
  411. {
  412. merchandise_id: {
  413. $eq: list.merchandise_id, // 推荐传入_id数据标识进行操作
  414. },
  415. },
  416. {
  417. user_id: {
  418. $eq: userId, // 推荐传入_id数据标识进行操作
  419. },
  420. },
  421. {
  422. school_id: {
  423. $eq: schoolId, // 推荐传入_id数据标识进行操作
  424. },
  425. },
  426. ]
  427. }
  428. },
  429. envType: "prod",
  430. });
  431. console.log(data.count, 'data.count');
  432. if (Number(data.count) > 0) {
  433. wx.showToast({
  434. title: '确认收货成功',
  435. icon: 'success',
  436. duration: 1500
  437. });
  438. // ✅ 重新获取数据
  439. this.setData({
  440. pageNumber: 1,
  441. hasMore: true,
  442. orders: []
  443. }, () => {
  444. this.getdatalist(false);
  445. });
  446. } else {
  447. wx.showToast({
  448. title: '确认收货失败',
  449. icon: 'error',
  450. duration: 1500
  451. });
  452. }
  453. },
  454. goToGoodsList (e) {
  455. const index = e.currentTarget.dataset.type;
  456. const item = this.data.orders[index];
  457. // console.log(e.currentTarget, 'item');
  458. wx.navigateTo({
  459. url: '/subpackages/orderdetails/orderdetails?data=' + encodeURIComponent(JSON.stringify(item))
  460. });
  461. },
  462. // async adds () {
  463. // const { data } = await models.orders.create({
  464. // data: {
  465. // adresses_id: "BWSLJAGVZA", // 地址id
  466. // sys_updateby_id: "", // 更新人
  467. // merchandise_id: "BULGAD2DA8", // 商品id
  468. // real_money: 223.12, // 实际付款金额
  469. // updat_adress: "", // 修改后地址
  470. // update_phone: "", // 修改后电话
  471. // delete: 0, // 逻辑删除
  472. // way: 1, // 收货方式
  473. // update_name: "", // 修改后收货人
  474. // school_id: "BU5N9CFX2Q", // 学校_id
  475. // user_id: "BWYRRKQVNY", // 用户_id
  476. // num_index: 1, // 商品数据
  477. // tracking_number: "物流单号888", // 物流单号
  478. // order_id: "订单号888", // 订单号
  479. // status: 2, // 状态
  480. // },
  481. // // envType: pre 体验环境, prod 正式环境
  482. // envType: "prod",
  483. // });
  484. // // 返回创建的数据 id
  485. // console.log(data);
  486. // }
  487. });