couponDetail.js 2.1 KB

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