// components/parking-order.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    occupyOrder:{
      type: Array,
      value: [] 
    },
    showPopup:{
      type: Boolean,
      value: false 
    }
  },
  lifetimes:{
    attached(){
      console.log("加载占位中订单组件");
      // this.loadOccupyOrder();
      // 页面加载时显示弹窗
      let isLogin = wx.getStorageSync('isLogin');
      if (isLogin) {
        this.loadOccupyOrder().then(data => {
          this.startPolling();
        })
        .catch(error => {
          console.error("数据加载失败", error);
        });
        
      }
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
      this.stopPolling();
    },
  },
  pageLifetimes:{
    // 组件所在页面的生命周期函数
    show: function () {
  
     },
     hide: function() {
      // 页面被隐藏
      this.stopPolling();
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    showPopup: false,
    occupyFeeOrderList:[],
    pollingInterval: null, // 定时器,
    costCycleFee:0
  },

  /**
   * 组件的方法列表
   */
  methods: {
  // 第一版
  // startPolling: function() {
  //   let that = this
  //   // Set up interval for subsequent loads
  //   this.data.pollingInterval = setInterval(() => {
  //     let occupyFeeOrder = this.data.occupyFeeOrderList[0];
  //      // 如果 occupyFeeOrder 不存在，直接返回
  //       if (!occupyFeeOrder) {
  //         console.warn("occupyFeeOrder 不存在，跳过本次轮询");
  //         return;
  //       }
  //       wx.request({
  //         url: 'https://jqcs.pjnes.com/cloud/occupyfee/evcs/occupyfee/template',
  //         data: occupyFeeOrder.chargpileids,
  //         method: 'POST',
  //         success(res) {
  //           that.calculate(occupyFeeOrder,res.data)
  //         }})
  //   }, 30000);
  // },
  startPolling: function() {
    let that = this;

    function fetchData() {
        let occupyFeeOrder = that.data.occupyFeeOrderList[0];
        console.log("occupyFeeOrder",occupyFeeOrder);
        // 如果 occupyFeeOrder 不存在，直接返回
        if (!occupyFeeOrder) {
            console.warn("occupyFeeOrder 不存在，跳过本次轮询");
            return;
        }

        wx.request({
            url: 'https://jqcs.pjnes.com/cloud/occupyfee/evcs/occupyfee/template',
            data: occupyFeeOrder.orderId,
            method: 'POST',
            success(res) {
                that.calculate(occupyFeeOrder, res.data);
            }
        });
    }

    // **立即执行一次**
    fetchData();

    // **设置轮询**
    this.data.pollingInterval = setInterval(fetchData, 30000);
},
  calculate(occupyFeeOrder,data) {
    let { occupyBeginTime ="" ,occupyTime =""} = occupyFeeOrder;
      // 将时间字符串转换为 Date 对象
      occupyBeginTime = new Date(occupyBeginTime.replace(/-/g, "/")); // 替换为兼容 iOS 的格式
  
      let currentTime = new Date();

      // 计算时间差(分)
      // let minutesDifference = Math.floor((currentTime - occupyBeginTime) / (1000 * 60));
      let minutesDifference = data.params.occupyTime;
      let freeTime = Number(data.freeTime) || 0;
      console.log("免费时长：",freeTime);
      console.log("最大占位时长:", data.maxFeeTime);
      console.log("data:", data);
      console.log("分钟:", minutesDifference);
      if (minutesDifference >= freeTime +1) { 
        if (minutesDifference <= data.maxFeeTime) {
          console.log("未达到最大时长");
          let Nocycle = Math.floor(minutesDifference / data.costCycle)
          occupyFeeOrder.occupyFee = (Nocycle * data.costCycleFee).toFixed(2);
          occupyFeeOrder.occupyTime = minutesDifference;
        } else {
          console.log("达到最大时长");
          let cycle = Math.floor(data.maxFeeTime / data.costCycle)
          occupyFeeOrder.occupyFee = (cycle * data.costCycleFee).toFixed(2);
          occupyFeeOrder.occupyTime =minutesDifference;
        }
      } else {
        console.log("处于免费时长");
        occupyFeeOrder.occupyFee = 0.00;
        occupyFeeOrder.occupyTime = minutesDifference;
      }
      
      console.log("触发定时器",occupyFeeOrder);
      // 根据返回的结果去调用微服务查询模版信息接口，根据模版信息 重新动态计算占位费模版
      this.setData({
        "occupyFeeOrderList[0]": occupyFeeOrder 
      });
  },

  // Stop polling
  stopPolling: function() {
    if (this.data.pollingInterval) {
      console.log('清除占位中定时器');
      clearInterval(this.data.pollingInterval);
      this.data.pollingInterval = null;
    }
  },
  loadOccupyOrder() {
    let that = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/wechat/queryOccupyFeeOrder',
        data: {
          userId: wx.getStorageSync('userInfo').userId,
          searchIndex: 2,
          pagenum: this.data.pagenum++,
          pagesize: 10,
        },
        method: 'POST',
        success(res) {
          console.log("占位费", res);
          if (res.data.result) {
            let { rows: occupyFeeOrderList } = res.data.result;
            that.setData({
              occupyFeeOrderList: that.data.occupyFeeOrderList.concat(occupyFeeOrderList),
            });
            resolve(res.data.result);
          } 
          // else {
          //   reject(new Error("No result data"));
          // }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  },
    handleConfirm() {
      // 点击确认按钮
      this.setData({
        showPopup: false
      });
    },
  
    handleContact() {
      // 联系客服
      // wx.makePhoneCall({
      //   phoneNumber: '4009608068' // 替换为实际的客服电话
      // });
      wx.showModal({
        title: '提示',
        confirmColor: '#00AADD',
        content: '若对当前占位费订单有疑问，请拨打客服电话4009608068，工作时间：08:00-18:00',
        complete: (res) => {
          // 可以在这里添加回调逻辑
          if (res.confirm) {
            console.log('用户点击了确认按钮');
          }else{
            console.log('用户点击了取消按钮');
          }
        }
      });
    },
  }
})