couponDetail.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 = setInterval(() => {
  48. this.checkCouponStatus('check');
  49. }, 10000);
  50. },
  51. stopPolling() {
  52. if (this.data.timer) {
  53. clearInterval(this.data.timer);
  54. this.data.timer = null;
  55. }
  56. },
  57. async checkCouponStatus() {
  58. const res = await queryCouponDetail(this.data.id, 1);
  59. if (res.code === 200) {
  60. const { verify_status } = res.data;
  61. if (verify_status !== 0) {
  62. this.updateCouponInfo(res.data);
  63. this.stopPolling();
  64. }
  65. }
  66. },
  67. updateCouponInfo(data) {
  68. let item = {
  69. ...data,
  70. verify_status_text:
  71. data.verify_status == 0
  72. ? '未核销'
  73. : data.verify_status == 1
  74. ? '已核销'
  75. : '已过期'
  76. };
  77. this.setData({ couponInfo: item, status: data.verify_status });
  78. },
  79. handleBack() {
  80. this.checkCouponStatus();
  81. },
  82. toggleCode() {
  83. this.setData({
  84. codeType: this.data.codeType === 'qr' ? 'bar' : 'qr'
  85. });
  86. },
  87. onChange() {
  88. this.getCouponDetail();
  89. }
  90. });