<template>
  <div class="flex flex-col h-screen">
    <TopNavBar titleAlign="center" :background="$theme - color - 100" :title="t('order.title.detail')" />

    <div
      class="bg-linear-[180deg,#e8fff1_0%,#f5f7fa_100%] px-3 pb-10 flex-1 overflow-y-auto scrollbar-none [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
      <OrderStatusInfo :orderData="orderData" />

      <VoucherList v-if="orderData.orderType != 0 && orderData.orderStatus === '2'" :orderData="orderData"
        @selected="handleSelectedVoucher" />

      <AmtSection :orderData="orderData" @click="refundVisible = true" />

      <GoodsInfo :orderData="orderData" />

      <UserInfo v-if="orderData.orderType == 0" :orderData="orderData" />

      <OrderInfo :orderData="orderData" />
    </div>

    <FooterSection :orderData="orderData" @refund="handleRefundConfirm" @refresh="handlePaySuccess" />
  </div>

  <!-- 核销凭证 二维码 -->
  <OrderQrcode v-if="orderData.orderStatus === '2'" v-show="visbleQrcode" v-model="visbleQrcode" :orderData="orderData"
    :selectedVoucher="selectedVoucher" :selectedVoucherIndex="selectedVoucherIndex" @close="handleClose" />

  <!-- 退款状态显示 -->
  <RefundPopup v-model="refundVisible" :orderData="orderData" />
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useI18n } from "vue-i18n";
import { userOrderDetail, orderRefund } from "@/api/order";
import TopNavBar from "@/components/TopNavBar/index.vue";
import OrderQrcode from "./components/OrderQrcode/index.vue";
import VoucherList from "./components/VoucherList/index.vue";
import OrderStatusInfo from "./components/OrderStatusInfo/index.vue";
import GoodsInfo from "./components/GoodsInfo/index.vue";
import UserInfo from "./components/UserInfo/index.vue";
import AmtSection from "./components/AmtSection/index.vue";
import OrderInfo from "./components/OrderInfo/index.vue";
import FooterSection from "./components/FooterSection/index.vue";
import RefundPopup from "@/components/RefundPopup/index.vue";

const { t } = useI18n();

// 获取事件通道对象
let eventChannel = null;

const refundVisible = ref(false);
const orderData = ref({});

const visbleQrcode = ref(false);
const selectedVoucher = ref(null);
const selectedVoucherIndex = ref(0);

// TODO
// onLoad(({ orderId }) => {
//   getOrderDetail(orderId);

//   // 获取当前页面的事件通道（由 navigateTo 打开时可用）
//   const pages = getCurrentPages();
//   const currentPage = pages[pages.length - 1];
//   eventChannel = currentPage.getOpenerEventChannel();
// });

// 处理选中核销凭证事件
const handleSelectedVoucher = (voucher) => {
  console.log("选中的核销凭证：", voucher);
  selectedVoucher.value = voucher.item;
  selectedVoucherIndex.value = voucher.index;
  visbleQrcode.value = true;
};

// 关闭核销凭证二维码弹窗
const handleClose = () => {
  visbleQrcode.value = false;
  selectedVoucher.value = null;
  selectedVoucherIndex.value = 0;
};

// 获取订单详情
const getOrderDetail = async (orderId) => {
  const res = await userOrderDetail({ orderId });
  orderData.value = res.data;
};

// 确认退款
const handleRefundConfirm = async ({ orderId }) => {
  try {
    // 调用退款API
    await orderRefund({ orderId });

    showToast(t("order.refund.submitted"));

    // 刷新订单状态
    const res = await userOrderDetail({ orderId });
    orderData.value = res.data;
  } catch (error) {
    showToast(t("order.refund.failed"));
  }
};

// 再次预定
const handlePaySuccess = ({ orderId }) => {
  console.log("支付成功，刷新订单详情", orderId);
  getOrderDetail(orderId);
  // 支付成功后通知上一个页面
  setTimeout(() => {
    eventChannel.emit("refreshOrderList", { success: true });
  }, 1000);
};

// TODO
// onUnload(() => {
//   eventChannel.on("refreshOrderList");
// });
</script>
