"use strict";
const common_vendor = require("../../common/vendor.js");
const config_user = require("../../config/user.js");
const config_url = require("../../config/url.js");
const common_assets = require("../../common/assets.js");
const _sfc_main = {
  data() {
    return {
      deviceId: "",
      orderInfo: {
        orderId: "",
        startTime: "",
        _rawStartTime: "",
        // 用于调试
        usedTime: "0分钟",
        currentFee: "0.00",
        orderStatus: "in_used",
        // 默认状态为使用中
        payWay: "",
        // 新增支付方式字段
        orderNo: ""
      },
      timer: null,
      statusCheckTimer: null,
      maxStatusChecks: 30,
      // 最多检查30次
      currentStatusChecks: 0,
      statusCheckInterval: 5e3,
      // 5秒检查一次
      isPageActive: false
      // 跟踪页面是否活跃
    };
  },
  onLoad(options) {
    common_vendor.index.__f__("log", "at pages/return/index.vue:120", "Return page loaded with options:", JSON.stringify(options));
    this.isPageActive = true;
    this.orderInfo.orderId = options.orderId || "";
    this.deviceId = options.deviceNo || options.deviceId || "";
    common_vendor.index.__f__("log", "at pages/return/index.vue:130", `初始化参数: orderId=${this.orderInfo.orderId}, deviceId=${this.deviceId}`);
    if (!this.orderInfo.orderId && this.deviceId) {
      this.getOrderByDevice();
    } else if (this.orderInfo.orderId) {
      this.getOrderDetails();
      this.startTimer();
      this.startStatusCheckTimer();
      common_vendor.index.setStorageSync("activeOrderId", this.orderInfo.orderId);
      try {
        if (this.$orderMonitor) {
          this.$orderMonitor.removeOrder({
            orderId: this.orderInfo.orderId
          });
          this.$orderMonitor.addOrder({
            orderId: this.orderInfo.orderId
          }, "return");
          common_vendor.index.__f__("log", "at pages/return/index.vue:157", "订单已添加到监控队列:", this.orderInfo.orderId);
        } else {
          common_vendor.index.__f__("warn", "at pages/return/index.vue:159", "$orderMonitor 未定义，无法添加订单到监控队列");
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/return/index.vue:162", "添加订单到监控队列失败:", error);
      }
    } else {
      common_vendor.index.showToast({
        title: "缺少订单信息",
        icon: "none"
      });
      setTimeout(() => {
        this.goToHome();
      }, 1500);
    }
    common_vendor.index.$on("orderCompleted", this.handleOrderCompleted);
  },
  // 添加onHide生命周期，处理页面隐藏时的清理工作
  onHide() {
    common_vendor.index.__f__("log", "at pages/return/index.vue:182", "归还页面隐藏，清理计时器资源和监控服务");
    this.isPageActive = false;
    this.clearTimer();
    this.clearStatusCheckTimer();
    this.removeFromOrderMonitor();
  },
  onUnload() {
    common_vendor.index.__f__("log", "at pages/return/index.vue:194", "归还页面卸载，清理所有资源");
    this.isPageActive = false;
    this.clearTimer();
    this.clearStatusCheckTimer();
    this.removeFromOrderMonitor();
    common_vendor.index.$off("orderCompleted", this.handleOrderCompleted);
  },
  methods: {
    // 从订单监控服务中移除当前订单
    removeFromOrderMonitor() {
      if (this.orderInfo.orderId && this.$orderMonitor) {
        try {
          this.$orderMonitor.removeOrder({
            orderId: this.orderInfo.orderId
          });
          common_vendor.index.__f__("log", "at pages/return/index.vue:216", "订单已从监控队列移除:", this.orderInfo.orderId);
        } catch (error) {
          common_vendor.index.__f__("error", "at pages/return/index.vue:218", "从监控队列移除订单失败:", error);
        }
      }
    },
    // 处理订单完成事件（可由任何地方触发）
    handleOrderCompleted(orderData) {
      common_vendor.index.__f__("log", "at pages/return/index.vue:224", "收到订单完成事件:", orderData);
      if (orderData.orderId === this.orderInfo.orderId || orderData.orderNo === this.orderInfo.orderNo) {
        this.showReturnSuccessModal(orderData);
      }
    },
    // 显示归还成功弹窗
    showReturnSuccessModal(orderData) {
      this.clearTimer();
      this.clearStatusCheckTimer();
      common_vendor.index.showModal({
        title: "归还成功",
        content: "风扇已归还成功，剩余押金将退还到您的账户",
        confirmText: "查看详情",
        success: (res) => {
          if (res.confirm) {
            common_vendor.index.redirectTo({
              url: `/pages/order/return-success?orderId=${orderData.orderId || this.orderInfo.orderId}`
            });
          } else {
            common_vendor.index.reLaunch({
              url: "/pages/index/index"
            });
          }
        }
      });
    },
    // 根据订单状态获取对应的文字显示
    getOrderStatusText() {
      const statusMap = {
        "waiting_for_payment": "待支付",
        "payment_in_progress": "支付中",
        "payment_successful": "支付成功",
        "in_used": "使用中",
        "payment_failed": "支付失败",
        "order_cancelled": "订单取消",
        "used_done": "订单完成",
        "used_down": "订单完成"
      };
      return statusMap[this.orderInfo.orderStatus] || "使用中";
    },
    // 获取订单详情
    async getOrderDetails() {
      if (!this.isPageActive) {
        common_vendor.index.__f__("log", "at pages/return/index.vue:280", "页面已不活跃，跳过订单详情请求");
        return;
      }
      try {
        if (!this.orderInfo.orderId) {
          throw new Error("订单ID不能为空");
        }
        const result = await config_user.queryById(this.orderInfo.orderId);
        if (result.code === 200 && result.data) {
          const orderData = result.data;
          common_vendor.index.__f__("log", "at pages/return/index.vue:295", "订单原始数据:", orderData);
          common_vendor.index.__f__("log", "at pages/return/index.vue:296", "开始时间字段:", orderData.startTime, typeof orderData.startTime);
          if (orderData.orderStatus) {
            this.orderInfo.orderStatus = orderData.orderStatus;
          }
          if (orderData.payWay) {
            this.orderInfo.payWay = orderData.payWay;
          }
          if (orderData.orderStatus && (orderData.orderStatus === "used_done" || orderData.orderStatus === "used_down")) {
            common_vendor.index.$emit("orderCompleted", orderData);
            this.showReturnSuccessModal(orderData);
            return;
          }
          this.updateOrderInfo(orderData);
          common_vendor.index.__f__("log", "at pages/return/index.vue:323", "更新后的开始时间:", this.orderInfo.startTime);
        } else {
          throw new Error(result.msg || "获取订单详情失败");
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/return/index.vue:328", "获取订单详情错误:", error);
        common_vendor.index.showToast({
          title: error.message || "获取订单信息失败",
          icon: "none"
        });
        setTimeout(() => {
          this.goToHome();
        }, 1500);
      } finally {
        common_vendor.index.hideLoading();
      }
    },
    // 格式化时间
    formatTime(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hour = date.getHours().toString().padStart(2, "0");
      const minute = date.getMinutes().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },
    // 使用后端返回的使用时长和费用数据
    updateOrderInfo(orderData) {
      this.orderInfo.usedTime = orderData.usedTime || "0分钟";
      this.orderInfo.currentFee = orderData.currentFee || orderData.actualDeviceAmount || orderData.payAmount || "0.00";
      if (orderData.orderStatus) {
        this.orderInfo.orderStatus = orderData.orderStatus;
      }
      if (orderData.payWay) {
        this.orderInfo.payWay = orderData.payWay;
      }
      this.orderInfo._rawStartTime = orderData.startTime;
      if (orderData.startTime) {
        try {
          common_vendor.index.__f__("log", "at pages/return/index.vue:379", "API返回的开始时间:", orderData.startTime);
          this.orderInfo.startTime = orderData.startTime;
        } catch (e) {
          common_vendor.index.__f__("error", "at pages/return/index.vue:383", "更新开始时间错误:", e);
          this.orderInfo.startTime = "未知";
        }
      } else {
        common_vendor.index.__f__("warn", "at pages/return/index.vue:387", "API返回的订单数据中没有startTime字段");
        if (orderData.createTime) {
          common_vendor.index.__f__("log", "at pages/return/index.vue:390", "使用createTime作为备选:", orderData.createTime);
          this.orderInfo.startTime = orderData.createTime;
        } else {
          this.orderInfo.startTime = "未知";
        }
      }
      if (orderData.orderNo) {
        this.orderInfo.orderNo = orderData.orderNo;
      }
      if (orderData.deviceNo && !this.deviceId) {
        this.deviceId = orderData.deviceNo;
      }
    },
    // 更新使用时长的定时器
    startTimer() {
      this.clearTimer();
      this.timer = setInterval(() => {
        if (this.isPageActive) {
          common_vendor.index.__f__("log", "at pages/return/index.vue:415", "执行定时更新订单信息");
          this.getOrderDetails();
        } else {
          common_vendor.index.__f__("log", "at pages/return/index.vue:418", "页面已不活跃，停止计时器");
          this.clearTimer();
        }
      }, 6e4);
      common_vendor.index.__f__("log", "at pages/return/index.vue:423", "已启动使用时长更新计时器");
    },
    // 清除定时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
        common_vendor.index.__f__("log", "at pages/return/index.vue:431", "已清除使用时长更新计时器");
      }
    },
    // 清除状态检查定时器
    clearStatusCheckTimer() {
      if (this.statusCheckTimer) {
        clearInterval(this.statusCheckTimer);
        this.statusCheckTimer = null;
        common_vendor.index.__f__("log", "at pages/return/index.vue:440", "已清除归还状态检查计时器");
      }
    },
    // 开始状态检查定时器
    startStatusCheckTimer() {
      this.currentStatusChecks = 0;
      this.clearStatusCheckTimer();
      this.statusCheckTimer = setInterval(() => {
        if (this.isPageActive) {
          this.currentStatusChecks++;
          common_vendor.index.__f__("log", "at pages/return/index.vue:454", `执行归还状态检查 (${this.currentStatusChecks}/${this.maxStatusChecks})`);
          this.checkReturnStatus();
          if (this.currentStatusChecks >= this.maxStatusChecks) {
            this.clearStatusCheckTimer();
            common_vendor.index.showToast({
              title: "请手动刷新查看归还状态",
              icon: "none",
              duration: 3e3
            });
          }
        } else {
          common_vendor.index.__f__("log", "at pages/return/index.vue:469", "页面已不活跃，停止状态检查计时器");
          this.clearStatusCheckTimer();
        }
      }, this.statusCheckInterval);
      common_vendor.index.__f__("log", "at pages/return/index.vue:474", "已启动归还状态检查计时器");
    },
    // 通过设备号查询使用中的订单
    async getOrderByDevice() {
      try {
        if (!this.deviceId) {
          throw new Error("设备号不能为空");
        }
        const inUseRes = await common_vendor.index.request({
          url: `${config_url.URL || "http://127.0.0.1:8080"}/app/order/inUse`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          }
        });
        common_vendor.index.__f__("log", "at pages/return/index.vue:496", "通过设备号查询订单结果:", JSON.stringify(inUseRes));
        if (inUseRes.statusCode === 200 && inUseRes.data.code === 200 && inUseRes.data.data) {
          const inUseOrder = inUseRes.data.data;
          common_vendor.index.__f__("log", "at pages/return/index.vue:500", "使用中的订单:", inUseOrder);
          this.orderInfo.orderId = inUseOrder.orderId;
          if (inUseOrder.orderStatus) {
            this.orderInfo.orderStatus = inUseOrder.orderStatus;
          }
          if (inUseOrder.payWay) {
            this.orderInfo.payWay = inUseOrder.payWay;
          }
          if (inUseOrder.startTime) {
            common_vendor.index.__f__("log", "at pages/return/index.vue:517", "inUse API返回的开始时间:", inUseOrder.startTime);
            this.orderInfo.startTime = inUseOrder.startTime;
          }
          this.getOrderDetails();
          this.startTimer();
          this.startStatusCheckTimer();
        } else {
          throw new Error("未找到使用中的订单");
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/return/index.vue:531", "通过设备号查询订单失败:", error);
        common_vendor.index.showToast({
          title: error.message || "获取订单信息失败",
          icon: "none"
        });
        setTimeout(() => {
          this.goToHome();
        }, 1500);
      } finally {
        common_vendor.index.hideLoading();
      }
    },
    // 检查归还状态
    async checkReturnStatus() {
      try {
        if (this.isPageActive) {
          await this.getOrderDetails();
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/return/index.vue:554", "检查归还状态失败:", error);
      }
    },
    // 返回首页
    goToHome() {
      common_vendor.index.reLaunch({
        url: "/pages/index/index"
      });
    }
  }
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: common_vendor.t($options.getOrderStatusText()),
    b: common_vendor.t($data.orderInfo.orderNo),
    c: common_vendor.t($data.deviceId),
    d: $data.orderInfo.payWay == "wx_score_pay"
  }, $data.orderInfo.payWay == "wx_score_pay" ? {
    e: common_assets._imports_0$3
  } : {}, {
    f: common_vendor.t($data.orderInfo.startTime),
    g: common_vendor.t($data.orderInfo.usedTime),
    h: common_vendor.t($data.orderInfo.currentFee)
  }, {}, {
    l: common_vendor.o((...args) => $options.checkReturnStatus && $options.checkReturnStatus(...args)),
    m: common_vendor.o((...args) => $options.goToHome && $options.goToHome(...args))
  });
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-6d22bdf8"]]);
wx.createPage(MiniProgramPage);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/return/index.js.map
