"use strict";
const common_vendor = require("../../common/vendor.js");
const config_user = require("../../config/user.js");
const config_url = require("../../config/url.js");
const _sfc_main = {
  data() {
    return {
      orderId: null,
      deviceNo: null,
      orderInfo: {},
      packageInfo: {
        time: "",
        price: "0.00"
      },
      deviceInfo: null,
      passedTotalAmount: null,
      passedDepositAmount: null,
      orderStatus: {
        text: "等待支付",
        desc: "请在15分钟内完成支付",
        class: "waiting"
      }
    };
  },
  computed: {
    totalAmount() {
      if (this.passedTotalAmount !== null) {
        return parseFloat(this.passedTotalAmount).toFixed(2);
      }
      const deposit = parseFloat(this.orderInfo.deposit || this.passedDepositAmount || 99);
      const packagePrice = parseFloat(this.packageInfo.price || 0);
      return (deposit + packagePrice).toFixed(2);
    },
    // 计算每小时的价格
    hourlyRate() {
      const price = parseFloat(this.packageInfo.price || 0);
      let time = parseFloat(this.packageInfo.time || 1);
      if (this.packageInfo.time && this.packageInfo.time.includes("分钟")) {
        time = time / 60;
      } else if (this.packageInfo.time && this.packageInfo.time.includes("次")) {
        return price.toFixed(2);
      }
      if (time <= 0)
        time = 1;
      return (price / time).toFixed(2);
    }
  },
  onLoad(options) {
    if (options && options.orderId) {
      this.orderId = options.orderId;
      if (options.totalAmount) {
        this.passedTotalAmount = options.depositAmount;
      }
      if (options.depositAmount) {
        this.passedDepositAmount = options.depositAmount;
      }
      if (options.feeConfig) {
        try {
          common_vendor.index.__f__("log", "at pages/order/payment.vue:135", "从URL获取到feeConfig:", options.feeConfig);
          const feeConfigStr = decodeURIComponent(options.feeConfig);
          this.deviceInfo = { feeConfig: feeConfigStr };
        } catch (e) {
          common_vendor.index.__f__("error", "at pages/order/payment.vue:140", "解析URL中的feeConfig失败:", e);
        }
      }
      this.loadOrderInfo();
    } else {
      common_vendor.index.showToast({
        title: "订单信息不存在",
        icon: "none"
      });
      setTimeout(() => {
        common_vendor.index.redirectTo({
          url: "/pages/index/index"
        });
      }, 1500);
    }
  },
  methods: {
    // 加载订单信息
    async loadOrderInfo() {
      try {
        common_vendor.index.showLoading({
          title: "加载中"
        });
        const res = await config_user.queryById(this.orderId);
        if (res.code === 200 && res.data) {
          const orderData = res.data;
          let formattedTime;
          try {
            if (orderData.createTime) {
              formattedTime = this.formatTime(new Date(orderData.createTime));
            } else {
              formattedTime = this.formatTime(/* @__PURE__ */ new Date());
            }
          } catch (e) {
            common_vendor.index.__f__("error", "at pages/order/payment.vue:180", "时间格式化错误:", e);
            formattedTime = this.formatTime(/* @__PURE__ */ new Date());
          }
          this.orderInfo = {
            orderNo: orderData.orderNo || orderData.orderId,
            deviceNo: orderData.deviceNo,
            createTime: formattedTime,
            phone: orderData.phone,
            deposit: this.passedDepositAmount || orderData.depositAmount || "99.00"
          };
          if (orderData.packageTime && orderData.packagePrice) {
            const timeInHours = (parseFloat(orderData.packageTime) / 60).toFixed(1);
            this.packageInfo = {
              time: timeInHours.toString(),
              price: orderData.packagePrice.toString()
            };
          }
          this.deviceNo = orderData.deviceNo;
          await this.loadDeviceInfo();
        } else {
          throw new Error("获取订单信息失败");
        }
        common_vendor.index.hideLoading();
      } catch (error) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: error.message || "获取订单信息失败",
          icon: "none"
        });
      }
    },
    // 加载设备信息
    async loadDeviceInfo() {
      if (!this.deviceNo)
        return;
      try {
        const res = await config_user.getDeviceInfo(this.deviceNo);
        if (res.code === 200 && res.data) {
          this.deviceInfo = res.data.device;
          if (this.deviceInfo && this.deviceInfo.depositAmount) {
            this.orderInfo.deposit = this.deviceInfo.depositAmount;
          }
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/order/payment.vue:234", "获取设备信息失败:", error);
      }
    },
    // 处理支付
    async handlePayment() {
      try {
        common_vendor.index.showLoading({
          title: "处理中"
        });
        const res = await common_vendor.index.request({
          url: `${config_url.URL || "http://127.0.0.1:8080"}/app/wx-payment/create/${this.orderInfo.orderNo}`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          }
        });
        if (res.statusCode === 200 && res.data.code === 200) {
          const payParams = res.data.data;
          await common_vendor.index.requestPayment({
            ...payParams,
            success: async () => {
              common_vendor.index.showToast({
                title: "支付成功",
                icon: "success"
              });
              try {
                await config_user.updateUserBalance(this.orderId);
              } catch (error) {
                common_vendor.index.__f__("warn", "at pages/order/payment.vue:271", "更新用户余额失败:", error);
              }
              setTimeout(() => {
                common_vendor.index.redirectTo({
                  url: `/pages/order/index?orderId=${this.orderId}`
                });
              }, 1500);
            },
            fail: (err) => {
              common_vendor.index.__f__("error", "at pages/order/payment.vue:282", "支付失败:", err);
              throw new Error("支付失败，请重试");
            }
          });
        } else {
          throw new Error(res.data.msg || "创建支付订单失败");
        }
      } catch (error) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: error.message || "支付失败",
          icon: "none"
        });
      }
    },
    // 发送租借指令
    async sendRentCommand() {
      try {
        common_vendor.index.showLoading({
          title: "处理中"
        });
        const res = await this.sendRentRequest();
        if (res.code === 200) {
          common_vendor.index.hideLoading();
          common_vendor.index.showToast({
            title: "租借成功",
            icon: "success"
          });
          setTimeout(() => {
            common_vendor.index.redirectTo({
              url: `/pages/order/index?orderId=${this.orderId}`
            });
          }, 1500);
        } else {
          throw new Error(res.msg || "租借失败");
        }
      } catch (error) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: error.message || "租借失败",
          icon: "none"
        });
      }
    },
    // 发送租借请求
    sendRentRequest() {
      return new Promise((resolve, reject) => {
        common_vendor.index.request({
          url: `${config_url.URL}/app/device/sendRentCommand`,
          method: "POST",
          data: {
            orderId: this.orderId
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          },
          success(res) {
            if (res.statusCode === 200) {
              resolve(res.data);
            } else {
              reject(new Error("请求失败"));
            }
          },
          fail(err) {
            reject(err);
          }
        });
      });
    },
    // 格式化时间
    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}`;
    },
    // 检查订单状态（单次查询，不轮询）
    async checkOrderStatus() {
      try {
        const res = await common_vendor.index.request({
          url: `${config_url.URL || "http://127.0.0.1:8080"}/app/wx-payment/status/${this.orderInfo.orderNo}`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          }
        });
        if (res.statusCode === 200 && res.data.code === 200) {
          return res.data.data;
        } else {
          throw new Error("查询订单状态失败");
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/order/payment.vue:390", "查询订单状态错误:", error);
        return null;
      }
    }
  }
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return {
    a: common_vendor.n($data.orderStatus.class),
    b: common_vendor.t($data.orderStatus.text),
    c: common_vendor.t($data.orderStatus.desc),
    d: common_vendor.t($data.orderInfo.orderNo || "-"),
    e: common_vendor.t($data.orderInfo.deviceNo || "-"),
    f: common_vendor.t($data.orderInfo.createTime || "-"),
    g: common_vendor.t($data.orderInfo.phone || "-"),
    h: common_vendor.t($data.orderInfo.deposit || "99.00"),
    i: common_vendor.t($data.packageInfo.price),
    j: common_vendor.t($data.packageInfo.time),
    k: common_vendor.t($options.totalAmount),
    l: common_vendor.t($options.totalAmount),
    m: common_vendor.o((...args) => $options.handlePayment && $options.handlePayment(...args))
  };
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-13c3fb22"]]);
wx.createPage(MiniProgramPage);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/order/payment.js.map
