<template>
  <view class="order-detail-wrapper">
    <uni-icons type="left" size="20" color="#fff" @click="goBack" />

    <OrderStatusInfo :orderData="orderData" />
    <OrderQrcode
      v-if="orderData.orderStatus === '2'"
      size="132"
      unit="px"
      :val="orderData.orderId"
    />
    <GoodsInfo :orderData="orderData" />
    <UserInfo :orderData="orderData" />
    <NoticeInfo :orderData="orderData" />
    <OrderInfo :orderData="orderData" @show-refund-popup="showRefundPopup" />

    <!-- 退款状态显示 -->
    <RefundPopup
      v-model="refundVisible"
      :refund-type="refundType"
      :refund-amount="refundAmount"
      @policy-click="viewRefundPolicy"
      @confirm-click="handleRefundConfirm"
    />
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { userOrderDetail, orderRefund } from "@/request/api/OrderApi";
import OrderQrcode from "./components/OrderQrcode/index.vue";
import OrderStatusInfo from "./components/OrderStatusInfo/index.vue";
import GoodsInfo from "./components/GoodsInfo/index.vue";
import UserInfo from "./components/UserInfo/index.vue";
import NoticeInfo from "./components/NoticeInfo/index.vue";
import OrderInfo from "./components/OrderInfo/index.vue";
import RefundPopup from "./components/RefundPopup/index.vue";

const refundVisible = ref(false);
const refundType = ref("free_cancel"); // 默认退款类型
const refundAmount = ref(0); // 退款金额
const orderData = ref({});
onLoad(async ({ orderId }) => {
  const res = await userOrderDetail({ orderId });

  orderData.value = res.data;
  // 设置退款金额为订单支付金额
  refundAmount.value = parseFloat(res.data.payAmt || 0);
  console.log(res);
});

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};

// 显示退款弹窗
const showRefundPopup = () => {
  refundVisible.value = true;
};

// 查看退款政策
const viewRefundPolicy = () => {
  console.log("查看退款政策");
  // 这里可以跳转到退款政策页面或显示详细政策
};

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

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

    // 刷新订单状态
    const res = await userOrderDetail({ orderId: orderData.value.orderId });
    orderData.value = res.data;
    // 更新退款金额
    refundAmount.value = parseFloat(res.data.payAmt || 0);
  } catch (error) {
    console.error("退款失败:", error);
    uni.showToast({
      title: "退款申请失败，请重试",
      icon: "none",
    });
  }
};
</script>

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