couponDetail.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { couponDetail, queryCouponDetail } from '../../api/other';
  2. import { BASE_URL } from '../../utils/request';
  3. Page({
  4. data: {
  5. baseUrl: BASE_URL,
  6. codeType: 'qr',
  7. status: 0,
  8. id: '',
  9. couponInfo: {},
  10. timer: null,
  11. loading: true // 增加 loading 状态
  12. },
  13. goPage(){
  14. wx.navigateTo({
  15. url: '/pages/storeIcon/storeIcon'
  16. })
  17. },
  18. onLoad(options) {
  19. this.setData({
  20. id: options.id
  21. });
  22. },
  23. onReady() {
  24. this.getCouponDetail();
  25. },
  26. onUnload() {
  27. this.stopPolling();
  28. },
  29. async getCouponDetail() {
  30. this.setData({ loading: true }); // 请求前显示加载
  31. try {
  32. const res = await couponDetail(this.data.id);
  33. if (res.code === 200) {
  34. this.updateCouponInfo(res.data);
  35. this.startPolling();
  36. } else {
  37. wx.showToast({
  38. title: res.message || '请求失败',
  39. icon: 'none',
  40. duration: 2000
  41. });
  42. }
  43. } catch (error) {
  44. console.log(error)
  45. } finally{
  46. this.setData({ loading: false });
  47. }
  48. },
  49. // 轮询接口
  50. startPolling() {
  51. this.stopPolling();
  52. this.data.timer = setTimeout(async () => {
  53. await this.checkCouponStatus('check');
  54. this.startPolling();
  55. }, 10000);
  56. },
  57. stopPolling() {
  58. if (this.data.timer) {
  59. clearTimeout(this.data.timer);
  60. this.data.timer = null;
  61. }
  62. },
  63. async checkCouponStatus(type) {
  64. const res = await queryCouponDetail(this.data.id, 1);
  65. if (res.code === 200 && type) {
  66. const { verify_status } = res.data;
  67. if (verify_status !== 0) {
  68. this.updateCouponInfo(res.data);
  69. this.stopPolling();
  70. }
  71. }
  72. },
  73. updateCouponInfo(data) {
  74. let item = {
  75. ...data,
  76. verify_status_text:
  77. data.verify_status == 0
  78. ? '未核销'
  79. : data.verify_status == 1
  80. ? '已核销'
  81. : '已过期'
  82. };
  83. this.setData({ couponInfo: item, status: data.verify_status });
  84. },
  85. handleBack() {
  86. this.checkCouponStatus();
  87. },
  88. toggleCode() {
  89. this.setData({
  90. codeType: this.data.codeType === 'qr' ? 'bar' : 'qr'
  91. });
  92. },
  93. onChange() {
  94. this.getCouponDetail();
  95. }
  96. });