"use strict";
const common_vendor = require("../../common/vendor.js");
const common_assets = require("../../common/assets.js");
const config_user = require("../../config/user.js");
const util_index = require("../../util/index.js");
const _sfc_main = {
  __name: "detail",
  setup(__props) {
    const deviceInfo = common_vendor.ref({});
    const deviceId = common_vendor.ref("");
    const deviceFeeConfig = common_vendor.ref({});
    const deviceLocation = common_vendor.ref("一号教学楼大厅");
    common_vendor.ref(95);
    const hasActiveOrder = common_vendor.ref(false);
    const deviceStatus = common_vendor.reactive({
      text: "可使用",
      class: "available"
    });
    const isLoggedIn = common_vendor.ref(true);
    const phoneNumber = common_vendor.ref("");
    const showPhoneAuthPopup = common_vendor.ref(false);
    common_vendor.onLoad((options) => {
      if (options.deviceNo != common_vendor.index.getStorageSync("deviceId") || !common_vendor.index.getStorageSync("deviceId")) {
        deviceId.value = options.deviceNo;
        common_vendor.index.setStorageSync("deviceId", options.deviceNo);
      } else {
        deviceId.value = common_vendor.index.getStorageSync("deviceId");
      }
      checkOrderStatus();
    });
    common_vendor.onMounted(async () => {
      await checkUserPhone();
    });
    common_vendor.onShow(async () => {
      await fetchDeviceInfo();
    });
    const checkUserPhone = async () => {
      try {
        const userInfoRes = await util_index.getUserInfo();
        common_vendor.index.__f__("log", "at pages/device/detail.vue:220", userInfoRes.data.phone, "getUserInfoPhone");
        if (userInfoRes.code == 200 && userInfoRes.data && userInfoRes.data.phone) {
          phoneNumber.value = userInfoRes.data.phone;
        } else {
          showPhoneAuthPopup.value = true;
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/device/detail.vue:229", "获取用户信息失败:", error);
      }
    };
    const onGetPhoneNumber = (e) => {
      common_vendor.index.__f__("log", "at pages/device/detail.vue:235", "getPhoneNumber event:", e.detail);
      if (e.detail.errMsg && e.detail.errMsg.includes("deny")) {
        common_vendor.index.showToast({
          title: "需要授权手机号才能使用设备",
          icon: "none"
        });
        return;
      }
      if (e.detail.code) {
        common_vendor.index.showLoading({
          title: "获取中..."
        });
        common_vendor.index.__f__("log", "at pages/device/detail.vue:252", "获取到的授权code:", e.detail.code);
        try {
          util_index.getUserPhoneNumber(e.detail.code).then((res) => {
            common_vendor.index.__f__("log", "at pages/device/detail.vue:258", "获取手机号API响应原始数据:", JSON.stringify(res));
            common_vendor.index.hideLoading();
            if (!res) {
              common_vendor.index.__f__("error", "at pages/device/detail.vue:263", "API返回数据为空");
              common_vendor.index.showModal({
                title: "数据异常",
                content: "API返回为空",
                showCancel: false
              });
              return;
            }
            common_vendor.index.__f__("log", "at pages/device/detail.vue:273", "响应code:", res.code, "响应类型:", typeof res.code);
            common_vendor.index.__f__("log", "at pages/device/detail.vue:274", "是否有data:", !!res.data, "是否有phone:", res.data && !!res.data.phone);
            if (res.code == 200 && res.data && res.data.phoneNumber) {
              phoneNumber.value = res.data.phoneNumber;
              showPhoneAuthPopup.value = false;
              common_vendor.index.showToast({
                title: "手机号获取成功",
                icon: "success"
              });
            } else {
              common_vendor.index.__f__("warn", "at pages/device/detail.vue:286", "获取手机号响应异常:", res.msg || "未知错误");
              common_vendor.index.showModal({
                title: "获取手机号异常",
                content: `状态码: ${res.code}, 消息: ${res.msg || "无"}`,
                showCancel: false
              });
            }
          }).catch((err) => {
            common_vendor.index.hideLoading();
            common_vendor.index.__f__("error", "at pages/device/detail.vue:296", "获取手机号码失败(catch):", err);
            let errMsg = err.message || err.toString();
            common_vendor.index.showModal({
              title: "获取手机号失败",
              content: "错误信息: " + errMsg,
              showCancel: false
            });
          });
        } catch (outerError) {
          common_vendor.index.hideLoading();
          common_vendor.index.__f__("error", "at pages/device/detail.vue:308", "获取手机号外部错误:", outerError);
          common_vendor.index.showModal({
            title: "意外错误",
            content: "处理过程发生异常: " + (outerError.message || outerError),
            showCancel: false
          });
        }
      } else {
        common_vendor.index.showToast({
          title: "获取授权码失败",
          icon: "none"
        });
      }
    };
    const fetchDeviceInfo = async () => {
      const res = await config_user.getDeviceInfo(deviceId.value);
      if (res.code == 200) {
        deviceInfo.value = res.data.device || {};
        if (deviceInfo.value.deviceLocation) {
          deviceLocation.value = deviceInfo.value.deviceLocation;
        } else if (res.data.position && res.data.position.name) {
          deviceLocation.value = res.data.position.name;
        }
        if (deviceInfo.value.status) {
          if (deviceInfo.value.status === "online") {
            deviceStatus.text = "可使用";
            deviceStatus.class = "available";
          } else if (deviceInfo.value.status === "offline") {
            deviceStatus.text = "离线";
            deviceStatus.class = "offline";
          }
        }
        common_vendor.index.__f__("log", "at pages/device/detail.vue:346", "feeconfig", deviceInfo.value.feeConfig);
        deviceFeeConfig.value = JSON.parse(deviceInfo.value.feeConfig)[0] || {};
      }
    };
    const showLoginTip = () => {
      common_vendor.index.showModal({
        title: "提示",
        content: "请先登录后再操作",
        confirmText: "去登录",
        success: (res) => {
          if (res.confirm) {
            common_vendor.index.navigateTo({
              url: "/pages/login/index"
            });
          }
        }
      });
    };
    const checkOrderStatus = async () => {
      try {
        const result = await common_vendor.index.$api.checkActiveOrder();
        if (result.hasOrder) {
          const order = result.order;
          if (order.status === "waiting_for_payment") {
            common_vendor.index.redirectTo({
              url: `/pages/order/payment?orderId=${order.orderId}&deviceId=${deviceId.value}`
            });
          } else if (order.status === "in_used") {
            common_vendor.index.redirectTo({
              url: `/pages/device/return?deviceId=${deviceId.value}`
            });
          }
        }
      } catch (error) {
        common_vendor.index.showToast({
          title: "订单状态查询失败",
          icon: "none"
        });
      }
    };
    const handleRent = (payWay) => {
      if (!isLoggedIn.value) {
        showLoginTip();
        return;
      }
      if (!phoneNumber.value) {
        showPhoneAuthPopup.value = true;
        return;
      }
      submitRentOrder(payWay);
    };
    const selectedPkg = common_vendor.reactive({
      time: "1小时",
      price: "5.00"
    });
    const depositAmount = common_vendor.ref("99.00");
    const submitRentOrder = async (payWay) => {
      try {
        common_vendor.index.showLoading({
          title: "处理中"
        });
        const rentResult = await config_user.rentPowerBank(deviceId.value, phoneNumber.value);
        if (rentResult.code !== 200) {
          throw new Error(rentResult.msg || "设备租借失败");
        }
        const order = rentResult.data;
        try {
          let packageTimeMinutes = 0;
          if (selectedPkg.time.includes("小时")) {
            packageTimeMinutes = parseInt(selectedPkg.time) * 60;
          } else if (selectedPkg.time.includes("分钟")) {
            packageTimeMinutes = parseInt(selectedPkg.time);
          } else {
            packageTimeMinutes = parseInt(selectedPkg.time) * 60;
          }
          const updateRes = await config_user.updateOrderPackage({
            orderId: order.orderId,
            packageTime: packageTimeMinutes,
            packagePrice: parseFloat(selectedPkg.price)
          });
          if (updateRes.code !== 200) {
            common_vendor.index.__f__("warn", "at pages/device/detail.vue:454", "更新订单套餐信息失败:", updateRes.msg);
          } else {
            common_vendor.index.__f__("log", "at pages/device/detail.vue:457", "订单套餐信息已提前更新");
          }
        } catch (updateError) {
          common_vendor.index.__f__("error", "at pages/device/detail.vue:460", "更新订单套餐信息时出错:", updateError);
        }
        if (payWay == "wx-pay") {
          common_vendor.index.hideLoading();
          const res = await config_user.getOrderByOrderNo(order.orderNo);
          common_vendor.index.__f__("log", "at pages/device/detail.vue:469", res);
          const deposit = parseFloat(deviceInfo.value.depositAmount);
          const packagePrice = parseFloat(selectedPkg.price);
          const totalAmount = (deposit + packagePrice).toFixed(2);
          common_vendor.index.hideLoading();
          common_vendor.index.redirectTo({
            url: `/pages/order/payment?orderId=${order.orderId}&packageTimeHours=${selectedPkg.time.replace("小时", "")}&packagePrice=${selectedPkg.price}&totalAmount=${totalAmount}&depositAmount=${depositAmount.value}${deviceInfo.value && deviceInfo.value.feeConfig ? "&feeConfig=" + encodeURIComponent(deviceInfo.value.feeConfig) : ""}`
          });
        } else if (payWay == "wx-score-pay") {
          common_vendor.index.hideLoading();
          const res = await config_user.getOrderByOrderNoScore(order.orderNo);
          common_vendor.index.hideLoading();
          if (res && res.code === 200) {
            try {
              const payResult = await util_index.initiateWeChatScorePayment(res);
              if (payResult.errCode == "0") {
                const res2 = await config_user.getOrderByOrderNoScorePayStatus(order.orderNo);
                common_vendor.index.__f__("log", "at pages/device/detail.vue:497", res2.data.orderStatus);
                if (res2.data.orderStatus == "in_used") {
                  common_vendor.index.showToast({
                    title: "设备租借成功",
                    icon: "success"
                  });
                  setTimeout(() => {
                    common_vendor.index.redirectTo({
                      url: "/pages/order/index"
                    });
                  }, 1500);
                } else if (res2.data.orderStatus == "waiting_for_payment") {
                  common_vendor.index.showToast({
                    title: "设备租借失败，订单已取消",
                    icon: "error"
                  });
                  await config_user.cancelOrder({
                    orderId: order.orderNo
                  });
                  setTimeout(() => {
                    common_vendor.index.switchTab({
                      url: "/pages/index/index"
                    });
                  }, 1500);
                }
              }
            } catch (payError) {
              common_vendor.index.showToast({
                title: "支付分调用失败，请重试",
                icon: "none"
              });
            }
          } else {
            common_vendor.index.showToast({
              title: (res == null ? void 0 : res.msg) || "获取支付参数失败",
              icon: "none"
            });
          }
        }
      } catch (error) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: error.message || "租借失败，请重试",
          icon: "none"
        });
      }
    };
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_vendor.t(deviceStatus.text),
        b: common_vendor.n(deviceStatus.class),
        c: common_vendor.t(deviceId.value),
        d: common_assets._imports_0$4,
        e: common_vendor.t(deviceLocation.value),
        f: common_vendor.t(deviceFeeConfig.value.maxHourPrice),
        g: common_vendor.t(deviceInfo.value.depositAmount),
        h: common_vendor.t(hasActiveOrder.value ? "归还设备" : "免押租借"),
        i: hasActiveOrder.value ? 1 : "",
        j: common_vendor.o(($event) => handleRent("wx-score-pay")),
        k: common_assets._imports_0$3,
        l: showPhoneAuthPopup.value
      }, showPhoneAuthPopup.value ? {
        m: common_vendor.o(() => {
        }),
        n: common_vendor.o(onGetPhoneNumber),
        o: common_vendor.o(($event) => showPhoneAuthPopup.value = false)
      } : {});
    };
  }
};
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-d65de3a7"]]);
wx.createPage(MiniProgramPage);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/device/detail.js.map
