<template>
  <view class="order-detail-page flex flex-col h-screen">
    <TopNavBar titleAlign="center" :background="$theme-color-100" title="订单详情" />

    <view class="order-detail-wrapper border-box flex-full overflow-hidden scroll-y">
      <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" />
    </view>

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

  <!-- 核销凭证 二维码 -->
  <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 { onLoad, onUnload } from "@dcloudio/uni-app";
import { userOrderDetail, orderRefund } from "@/request/api/OrderApi";
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";

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

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

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

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 });

    uni.showToast({ title: "退款申请已提交", icon: "success" });

    // 刷新订单状态
    const res = await userOrderDetail({ orderId });
    orderData.value = res.data;
  } catch (error) {
    uni.showToast({ title: "退款申请失败，请重试", icon: "none" });
  }
};

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

onUnload(() => {
  eventChannel.on('refreshOrderList');
});

</script>

<style lang="scss" scoped>
@import "./styles/detail.scss";
</style>
