merge.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const WXAPI = require('apifm-wxapi')
  2. const AUTH = require('../../utils/auth')
  3. Page({
  4. data: {
  5. },
  6. onLoad: function (options) {
  7. this.mergeCouponsRules();
  8. },
  9. onShow: function () {
  10. },
  11. async mergeCouponsRules() {
  12. const res = await WXAPI.mergeCouponsRules()
  13. if (res.code == 0) {
  14. this.setData({
  15. mergeCouponsRules: res.data
  16. })
  17. }
  18. },
  19. onPullDownRefresh() {
  20. this.mergeCouponsRules()
  21. wx.stopPullDownRefresh()
  22. },
  23. async merge(e) {
  24. const idx = e.currentTarget.dataset.idx
  25. const mergeCouponsRule = this.data.mergeCouponsRules[idx]
  26. this.setData({loading: true})
  27. let res = await WXAPI.myCoupons({
  28. token: wx.getStorageSync('token'),
  29. status: 0
  30. })
  31. if (res.code == 700) {
  32. wx.showToast({
  33. title: '您暂无可用的优惠券',
  34. icon: 'none'
  35. })
  36. this.setData({loading: false})
  37. return
  38. }
  39. if (res.code != 0) {
  40. wx.showToast({
  41. title: res.msg,
  42. icon: 'none'
  43. })
  44. this.setData({loading: false})
  45. return
  46. }
  47. const myCoupons = res.data.reverse()
  48. const couponIds = [] // 用来合成的优惠券id
  49. let ok = true
  50. let msg = ''
  51. mergeCouponsRule.rules.filter(rule => {
  52. return rule.type == 0
  53. }).forEach(rule => {
  54. for (let i = 0; i < rule.number; i++) {
  55. const couponIndex = myCoupons.findIndex(ele => { return ele.pid == rule.couponId})
  56. if (couponIndex == -1) {
  57. ok = false
  58. msg = rule.couponName
  59. return
  60. }
  61. const coupon = myCoupons[couponIndex]
  62. couponIds.push(coupon.id)
  63. myCoupons.splice(couponIndex, 1)
  64. }
  65. })
  66. if (!ok) {
  67. wx.showToast({
  68. title: '缺少优惠券:' + msg,
  69. icon: 'none'
  70. })
  71. this.setData({loading: false})
  72. return
  73. }
  74. res = await WXAPI.mergeCoupons({
  75. token: wx.getStorageSync('token'),
  76. mergeId: mergeCouponsRule.id,
  77. couponIds: couponIds.join()
  78. })
  79. if (res.code != 0) {
  80. wx.showToast({
  81. title: res.msg,
  82. icon: 'none'
  83. })
  84. this.setData({loading: false})
  85. return
  86. }
  87. wx.showToast({
  88. title: '兑换成功'
  89. })
  90. this.setData({loading: false})
  91. setTimeout(() => {
  92. wx.navigateBack({
  93. delta: 0,
  94. })
  95. }, 1000);
  96. }
  97. })