소스 검색

fix: 修复预约页省电模式跨天判断失效、启动确认轮询风暴与异常提示失效,倒计时纳入生命周期管理

skyline 3 주 전
부모
커밋
7ec4086f6a
1개의 변경된 파일과 59개의 추가작업 그리고 66개의 파일을 삭제
  1. 59 66
      charge-front/src/pages-charge/appointment/appointment.vue

+ 59 - 66
charge-front/src/pages-charge/appointment/appointment.vue

@@ -141,7 +141,7 @@
           </block>
           <block v-else-if="checkedUserRightsOrCoupon&&checkedUserRightsOrCoupon.couponId">
             <view class="fs-28 lh-28 ml-auto" style="color: #f43636" v-if="checkedUserRightsOrCoupon.userCoupon.couponType=='FullDiscount'">
-              {{ ((checkedUserRightsOrCoupon?.userCoupon?.discount || 0) / 100).toFixed(2) }}元
+              {{ fenToYuan(checkedUserRightsOrCoupon?.userCoupon?.discount) }}元
             </view>
             <view class="fs-28 lh-28 ml-auto" style="color: #f43636" v-else>
               {{ ((checkedUserRightsOrCoupon?.userCoupon?.discount || 0) / 10).toFixed(1) }}折
@@ -313,19 +313,19 @@ import {
 } from "@/api/charge";
 
 import {fetchProfile, listStationAvailableRightsAndCoupons} from "@/api/user";
-import {onLoad, onShow} from "@dcloudio/uni-app";
+import {onLoad, onShow, onUnload} from "@dcloudio/uni-app";
 import {computed, ref} from "vue";
 import ChargeMachine from "../machines/charge-machine/charge-machine.vue";
 import PriceDesc from "../machines/price-desc/price-desc.vue";
 import StationChargeCoupon from "@/components/station-charge-coupon/station-charge-coupon.vue";
-import {format} from "../utils/date";
+import {format, parseDate} from "@/utils/date";
 import {redirect, to} from "../../utils/navigate";
 import { requireAuth } from "@/utils/auth";
+import { fenToYuan } from "@/utils/money";
 
 
 const DAY = 24 * 60 * 60 * 1000;
 const options = ref<any>();
-const data = ref<any>();
 const equipment = ref<any>(null);
 const station = ref<any>();
 const stationId = ref<any>();
@@ -367,10 +367,6 @@ const chargeTime = ref({
 const appointmentData = ref();
 const appointmentCountDown = ref();
 
-const discountIndex = ref(-1);
-const discountList = ref<any[]>([]);
-const activity = ref();
-
 const balance = ref(0);
 
 // 低余额提醒阈值(元),余额低于该值时在页面提示用户充值
@@ -384,7 +380,6 @@ const balanceText = computed(() => `${Number(balance.value).toFixed(2)}元`);
 
 const refreshUserBalance = () => {
   let user = getApp<any>().globalData.user
-  console.log(user)
   balance.value = user?.balance || 0;
 }
 
@@ -394,7 +389,6 @@ const handleShowStationChargeCoupon = () => {
 }
 
 const handleCheckedUserRightsAndCoupon = (data: any) => {
-  // console.log("handleCheckedUserRightsAndCoupon", data);
   checkedUserRightsOrCoupon.value = data;
 }
 
@@ -514,9 +508,7 @@ const selectTime = () => {
   let dayIdx = 0;
   let timeIdx = 0;
   if (appointmentData.value) {
-    const start = new Date(
-        appointmentData.value.startTime.replace(/-/g, "/")
-    ).getTime();
+    const start = parseDate(appointmentData.value.startTime).getTime();
     const aligned = Math.ceil(start / STEP) * STEP;
     timesInfo.value.groups.forEach((g: any, gi: number) => {
       const idx = g.options.findIndex((o: any) => o.ts === aligned);
@@ -679,7 +671,7 @@ const startAppointmentCountDown = () => {
 
 const formatAppointmentCountDown = (time: string) => {
   const now = new Date();
-  const date = new Date(time.replace(/-/g, "/"));
+  const date = parseDate(time);
   let secondTime = parseInt(`${(date.getTime() - now.getTime()) / 1000}`);
   if (secondTime <= 0) {
     return "";
@@ -714,14 +706,13 @@ const submit = () => {
   const now = new Date();
   let startTime = chargeTime.value.time;
   if (chargeTime.value.isPowerSaving) {
-    startTime = now.getTime();
-    // 省电模式
-    if (
-        now.getHours() >= 8 &&
-        now.getDate() === Number(format("d", chargeTime.value.time))
-    ) {
-      startTime += DAY;
+    // 省电模式:8 点后预约次日 00:00-08:00 时段,8 点前视为当天时段进行中
+    const start = new Date(now);
+    if (now.getHours() >= 8) {
+      start.setDate(start.getDate() + 1);
     }
+    start.setHours(0, 0, 0, 0);
+    startTime = start.getTime();
   }
   let query = "";
   if (chargeType.value === 0) {
@@ -739,14 +730,12 @@ const submit = () => {
     query += "isBooking=false";
   }
   let {userRechargeRightsId, userCouponId} = checkedUserRightsOrCoupon.value;
-  console.log("userRechargeRightsId")
   if (userRechargeRightsId && userRechargeRightsId >= 0) {
     query += `&userRechargeRightsId=${userRechargeRightsId}`;
   }
   if (userCouponId && userCouponId >= 0) {
     query += `&userCouponId=${userCouponId}`;
   }
-  console.log(query)
   uni.showLoading({
     title: "提交中",
     mask: true,
@@ -771,7 +760,7 @@ const submit = () => {
               });
         }
         if (chargeType.value === 1) {
-          redirect(`/pages-charge/ordering/ordering?connectorId=${options.value.connectorId}&start=1`)
+          redirect(`/pages-charge/ordering/ordering?connectorId=${options.value.connectorId}`)
         }
       })
       .catch((err) => {
@@ -801,15 +790,33 @@ const submitNow = () => {
       });
 };
 
-const _checkStartCharge = () => {
-  fetchChargeStatus().then((res) => {
-    if (res && [2].includes(res.chargeStatus)) {
-      uni.hideLoading();
-      redirect(`/pages-charge/ordering/ordering?connectorId=${options.value.connectorId}&start=1`)
-    } else {
-      _checkStartCharge();
-    }
-  });
+const CHECK_START_CHARGE_INTERVAL = 2000;
+const CHECK_START_CHARGE_MAX = 30; // 最多轮询 30 次(约 1 分钟)
+let checkStartChargeTimer: ReturnType<typeof setTimeout> | null = null;
+
+const _checkStartCharge = (count = 0) => {
+  if (count >= CHECK_START_CHARGE_MAX) {
+    uni.hideLoading();
+    uni.showToast({
+      title: "启动确认超时,请稍后在充电订单中查看",
+      icon: "none",
+    });
+    return;
+  }
+  checkStartChargeTimer = setTimeout(() => {
+    fetchChargeStatus()
+        .then((res) => {
+          if (res && [2].includes(res.chargeStatus)) {
+            uni.hideLoading();
+            redirect(`/pages-charge/ordering/ordering?connectorId=${options.value.connectorId}`)
+          } else {
+            _checkStartCharge(count + 1);
+          }
+        })
+        .catch(() => {
+          _checkStartCharge(count + 1);
+        });
+  }, CHECK_START_CHARGE_INTERVAL);
 };
 
 /**
@@ -830,7 +837,6 @@ const fetchUserStationDefaultRightsAndCoupon = () => {
       checkedUserRightsOrCoupon.value.couponId = couponList[0].couponId;
       checkedUserRightsOrCoupon.value.userCouponId = couponList[0].id;
     }
-    console.log(res)
   });
 }
 
@@ -839,7 +845,6 @@ onLoad((_options: any) => {
     return;
   }
   // sn=SN100523042860091 测试环境
-  console.log("options", _options);
   let {sn, connectorId, equipmentId} = _options
   let _sn = _options.sn;
   let _stationId = _options.stationId;
@@ -852,7 +857,6 @@ onLoad((_options: any) => {
   });
   fetchStationDetailByShortIdOrConnectorIdOrEquipmentId(sn, connectorId, equipmentId)
       .then((res) => {
-        console.log("1111111111", res);
         //充电桩需要再次过滤
         stationId.value = res.stationId;
         fetchUserStationDefaultRightsAndCoupon();
@@ -883,12 +887,11 @@ onLoad((_options: any) => {
         //   _options.sn = equipment.connectorInfos[0].connectorId;
         // }
         // options.value = _options;
-        // data.value = res;
         station.value = res;
         if(!equipment.value){
           uni.showToast({
-            titile:'none',
-            content:"服务异常,请稍后再试。"
+            title: "服务异常,请稍后再试",
+            icon: "none",
           })
           // return Promise.resolve({});
           throw Error;
@@ -896,57 +899,47 @@ onLoad((_options: any) => {
         return fetchStationPriceDesc(equipment.value.connectorId, res.stationId)
       })
       .then((res) => {
-        console.log("xxxx price", res);
         uni.hideLoading();
         priceInfo.value = res;
         return fetchChargeStatus(false, true);
       })
       .then((res) => {
-        console.log("charge status", res)
         if (res && res.isAppointment) {
           appointmentData.value = res;
           startAppointmentCountDown();
         }
       })
       .catch((err) => {
-        console.log(err);
         uni.hideLoading();
       });
 
 
-  fetchProfile().then((res) => {
-    if (res.userRechargeRightsList.length) {
-      res.userRechargeRightsList.forEach((item: any) => {
-        item.discountFormat = Number((Number(item.discount) / 10).toFixed(2));
-      });
-      discountList.value = res.userRechargeRightsList;
-      discountIndex.value = 0;
-    }
-
-    if (res.activityList && res.activityList.length) {
-      res.activityList[0].rechargeRightsList.sort((a: any, b: any) => {
-        return a.discount - b.discount;
-      });
-      activity.value = res.activityList[0];
-      activity.value.minDiscount = Number(
-          (
-              Number(res.activityList[0].rechargeRightsList[0]?.discount) / 10
-          ).toFixed(1)
-      );
-    }
-
+  fetchProfile().then(() => {
     refreshUserBalance();
   });
   refreshUserBalance();
 });
 
 onShow(() => {
-  if (getApp<any>().globalData.lastData.discount) {
-    discountIndex.value = getApp<any>().globalData.lastData.discount.index;
-    getApp<any>().globalData.lastData.discount = undefined;
+  // 恢复预约倒计时(onHide 时被暂停)
+  if (appointmentData.value) {
+    startAppointmentCountDown();
   }
   refreshUserBalance();
 });
+
+onHide(() => {
+  appointmentCountDownTimer && clearTimeout(appointmentCountDownTimer);
+});
+
+onUnload(() => {
+  appointmentCountDownTimer && clearTimeout(appointmentCountDownTimer);
+  if (checkStartChargeTimer) {
+    clearTimeout(checkStartChargeTimer);
+    checkStartChargeTimer = null;
+  }
+});
+
 </script>
 
 <style lang="scss" scoped>