"use strict";
const common_vendor = require("../../common/vendor.js");
const common_assets = require("../../common/assets.js");
const config_user = require("../../config/user.js");
const config_url = require("../../config/url.js");
const _sfc_main = {
  __name: "index",
  setup(__props) {
    const currentTab = common_vendor.ref(0);
    const orderList = common_vendor.ref([]);
    const orderStatusMap = common_vendor.reactive({
      "0": {
        text: "待支付",
        class: "status-waiting"
      },
      "1": {
        text: "使用中",
        class: "status-using"
      },
      "2": {
        text: "已完成",
        class: "status-finished"
      },
      "3": {
        text: "已取消",
        class: "status-cancelled"
      },
      "waiting_for_payment": {
        text: "待支付",
        class: "status-waiting"
      },
      "in_used": {
        text: "使用中",
        class: "status-using"
      },
      "used_done": {
        text: "已完成",
        class: "status-finished"
      },
      "order_cancelled": {
        text: "已取消",
        class: "status-cancelled"
      }
    });
    const orderStatusTabs = common_vendor.reactive([
      {
        text: "全部",
        status: []
      },
      {
        text: "待付款",
        status: ["waiting_for_payment"]
      },
      {
        text: "使用中",
        status: ["in_used"]
      },
      {
        text: "已完成",
        status: ["used_done"]
      },
      {
        text: "已取消",
        status: ["order_cancelled"]
      }
    ]);
    common_vendor.onLoad(async (options) => {
      if (options && options.orderId) {
        try {
          const res = await config_user.queryById(options.orderId);
          if (res.code === 200 && res.data) {
            const orderData = res.data;
            const orderStartTime = orderData.startTime || orderData.createTime || "";
            const formattedOrder = {
              orderNo: orderData.orderId,
              status: orderData.orderStatus,
              deviceId: orderData.deviceNo,
              payWay: orderData.payWay,
              startTime: orderStartTime,
              endTime: orderData.endTime || "",
              amount: orderData.payAmount || orderData.actualDeviceAmount || "0.00"
            };
            orderList.value = [formattedOrder, ...orderList.value];
            const tabIndex = orderStatusTabs.findIndex(
              (tab) => tab.status.includes(orderData.orderStatus)
            );
            if (tabIndex !== -1) {
              switchTab(tabIndex);
            }
          }
        } catch (error) {
          common_vendor.index.__f__("error", "at pages/order/index.vue:226", "获取订单详情失败:", error);
        }
      }
      await loadOrderList();
    });
    const switchTab = async (index) => {
      currentTab.value = index;
      const statusList = orderStatusTabs[index].status[0];
      await loadOrderList(statusList);
    };
    const loadOrderList = async (statusList) => {
      try {
        if (statusList != void 0) {
          statusList = {
            orderStatus: statusList
          };
        }
        const res = await config_user.getOrderList(statusList);
        if (res.code === 200 && res.data && res.data.records) {
          orderList.value = res.data.records.map((item) => {
            const orderStartTime = item.startTime || item.createTime || "";
            return {
              orderNo: item.orderNo,
              orderId: item.orderId,
              orderStatus: item.orderStatus,
              deviceId: item.deviceNo,
              payWay: item.payWay,
              startTime: orderStartTime,
              endTime: item.endTime || "",
              amount: item.payAmount || item.actualDeviceAmount || "0.00"
            };
          });
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/order/index.vue:270", "获取订单列表失败:", error);
        common_vendor.index.showToast({
          title: "获取订单列表失败",
          icon: "none"
        });
      }
    };
    const navigateToReturn = (deviceId, orderId) => {
      common_vendor.index.__f__("log", "at pages/order/index.vue:299", orderId);
      common_vendor.index.navigateTo({
        url: `/pages/return/index?deviceId=${deviceId}&orderId=${orderId}`
      });
    };
    const navigateToDetails = (order) => {
      common_vendor.index.navigateTo({
        url: `/pages/order/details?orderId=${order.orderId || order.orderNo}`
      });
    };
    const handlePayment = async (order) => {
      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/${order.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(order.orderId || order.orderNo);
              } catch (error) {
                common_vendor.index.__f__("warn", "at pages/order/index.vue:345", "更新用户余额失败:", error);
              }
              await loadOrderList(orderStatusTabs[currentTab.value].status);
            },
            fail: (err) => {
              common_vendor.index.__f__("error", "at pages/order/index.vue:352", "支付失败:", err);
              throw new Error("支付失败，请重试");
            }
          });
        } else {
          throw new Error(res.data.msg || "创建支付订单失败");
        }
        common_vendor.index.hideLoading();
      } catch (error) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: error.message || "支付失败",
          icon: "none"
        });
      }
    };
    const handleCancelOrder = async (order) => {
      try {
        common_vendor.index.showModal({
          title: "确认取消",
          content: "确定要取消此订单吗？",
          success: async (res) => {
            if (res.confirm) {
              common_vendor.index.showLoading({
                title: "处理中"
              });
              const result = await config_user.cancelOrder({
                orderId: order.orderNo
              });
              if (result) {
                common_vendor.index.hideLoading();
                common_vendor.index.showToast({
                  title: "订单已取消",
                  icon: "success"
                });
                await loadOrderList();
              } else {
                throw new Error(result.msg || "取消订单失败");
              }
            }
          }
        });
      } 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.f(orderStatusTabs, (tab, index, i0) => {
          return {
            a: common_vendor.t(tab.text),
            b: index,
            c: currentTab.value === index ? 1 : "",
            d: common_vendor.o(($event) => switchTab(index), index)
          };
        }),
        b: orderList.value.length === 0
      }, orderList.value.length === 0 ? {} : {}, {
        c: common_vendor.f(orderList.value, (order, index, i0) => {
          var _a, _b;
          return common_vendor.e({
            a: common_vendor.t(order.orderNo),
            b: common_vendor.t((_a = orderStatusMap[order.orderStatus]) == null ? void 0 : _a.text),
            c: common_vendor.n((_b = orderStatusMap[order.orderStatus]) == null ? void 0 : _b.class),
            d: common_vendor.t(order.deviceId),
            e: order.payWay == "wx_score_pay"
          }, order.payWay == "wx_score_pay" ? {
            f: common_assets._imports_0$3
          } : {}, {
            g: common_vendor.t(order.startTime),
            h: common_vendor.t(order.endTime || "-"),
            i: common_vendor.t(order.amount),
            j: order.status === "waiting_for_payment" || order.orderStatus === "waiting_for_payment"
          }, order.status === "waiting_for_payment" || order.orderStatus === "waiting_for_payment" ? {
            k: common_vendor.o(($event) => handlePayment(order), index)
          } : {}, {
            l: order.status === "waiting_for_payment" || order.orderStatus === "waiting_for_payment"
          }, order.status === "waiting_for_payment" || order.orderStatus === "waiting_for_payment" ? {
            m: common_vendor.o(($event) => handleCancelOrder(order), index)
          } : {}, {
            n: order.status == "in_used" || order.orderStatus == "in_used"
          }, order.status == "in_used" || order.orderStatus == "in_used" ? {
            o: common_vendor.o(($event) => navigateToReturn(order.deviceId, order.orderId), index)
          } : {}, {
            p: common_vendor.o(($event) => navigateToDetails(order), index),
            q: index
          });
        })
      });
    };
  }
};
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-17a44f9d"]]);
wx.createPage(MiniProgramPage);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/order/index.js.map
