<template>
  <view class="order-info">
    <view class="order-item">
      <text class="label">订单号</text>
      <text class="value">{{ orderData.orderId }}</text>
    </view>
    <view class="order-item">
      <text class="label">流水号</text>
      <text class="value">{{ orderData.paySerialNumber }}</text>
    </view>
    <view class="order-item">
      <text class="label">支付方式</text>
      <text class="value">{{ payWayText }}</text>
    </view>
    <!-- 在已退款状态显示 -->
    <view v-if="orderData.orderStatus === '4'" class="order-item">
      <text class="label">退款单号</text>
      <text class="value">{{ orderData.refundOrderNo }}</text>
    </view>
    <view class="line"></view>
    <view class="order-item amount">
      <text class="label">实际支付金额</text>
      <text class="value">{{ formattedAmount }}</text>
    </view>
    <!-- 根据订单状态动态显示按钮 -->
    <button
      v-if="shouldShowButton"
      :class="['reserve-button', { loading: isLoading }]"
      :disabled="isLoading"
      @click="handleButtonClick(orderData)"
    >
      {{ isLoading ? "处理中..." : buttonText }}
    </button>
    <view class="feedback">
      <text @click="openFeedback">投诉反馈</text>
    </view>
  </view>
</template>

<script setup>
import { defineProps, computed, ref, defineEmits } from "vue";
import { orderPayNow } from "@/request/api/OrderApi";

// 支付方式映射常量
const PAY_WAY_MAP = {
  0: "微信",
  1: "支付宝",
  2: "云闪付",
};

// 加载状态
const isLoading = ref(false);

// 定义事件发射器
const emit = defineEmits(["show-refund-popup", "pay-success"]);

const props = defineProps({
  orderData: {
    type: Object,
    required: true,
    default: () => ({
      orderId: "",
      paySerialNumber: "",
      payWay: "", // 支付方式 0-微信 1-支付宝 2-云闪付
      payAmt: "",
      orderStatus: "0", // 订单状态 0-待支付 1-待确认 2-待使用 3-已取消 4-退款中 5-已关闭 6-已完成
      orderType: "0", // 0-酒店订单, 1-门票订单, 2-餐饮
    }),
  },
});

// 使用计算属性缓存支付方式文本
const payWayText = computed(() => {
  return PAY_WAY_MAP[props.orderData.payWay] || "未知支付方式";
});

// 格式化金额显示
const formattedAmount = computed(() => {
  const amount = props.orderData.payAmt;
  return amount ? `${parseFloat(amount).toFixed(2)}` : "0.00";
});

// 按钮文案逻辑，订单状态 0-待支付 1-待确认 2-待使用 3-已取消 4-退款中 5-已关闭 6-已完成
const buttonText = computed(() => {
  const status = props.orderData.orderStatus;
  switch (status) {
    case "0": // 待支付状态
      return "立即支付";
    case "2": // 待使用状态
      return "申请退款";
    case "3": // 已取消状态
    case "5": // 已关闭状态
    case "6": // 已完成状态
      return "再次预定";
  }
});

// 是否显示按钮（待支付、待使用、已取消、已关闭、已完成）
const shouldShowButton = computed(() => {
  const status = props.orderData.orderStatus;
  return ["0", "2", "3", "5", "6"].includes(status);
});

// 处理按钮点击事件
const handleButtonClick = async (orderData) => {
  if (isLoading.value) return; // 防止重复点击

  try {
    isLoading.value = true;

    const status = orderData.orderStatus;

    if (status === "2") {
      // 情况2：待使用状态，显示退款弹窗
      emit("show-refund-popup");
      return; // 直接返回，不执行后续代码
    }

    // 再次预定跳转商品详情
    if (["3", "5", "6"].includes(status)) {
      uni.navigateTo({
        url: `/pages/goods/index?commodityId=${orderData.commodityId}`,
      });
    }

    // 待支付状态，调用支付接口
    if (status === "0") {
      const orderId = orderData.orderId;
      const payWay = orderData.payWay;
      const paySource = orderData.paySource;

      const res = await orderPayNow({ orderId, payWay, paySource });
      console.log("确认订单---2:", res);

      // 检查接口返回数据
      if (!res || !res.data) {
        uni.showToast({
          title: "订单创建失败，请重试",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      const { data } = res;
      const { nonceStr, packageVal, paySign, signType, timeStamp } = data;

      // 验证支付参数是否完整
      if (!nonceStr || !packageVal || !paySign || !signType || !timeStamp) {
        console.error("支付参数不完整:", {
          nonceStr: !!nonceStr,
          packageVal: !!packageVal,
          paySign: !!paySign,
          signType: !!signType,
          timeStamp: !!timeStamp,
        });
        uni.showToast({
          title: "支付参数错误，请重试",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      // 调用微信支付
      uni.requestPayment({
        provider: "wxpay",
        timeStamp: String(timeStamp), // 确保为字符串类型
        nonceStr: String(nonceStr),
        package: String(packageVal), // 确保为字符串类型
        signType: String(signType),
        paySign: String(paySign),
        success: () => {
          uni.showToast({
            title: "支付成功",
            icon: "success",
            duration: 2000,
            success: () => {
              emit("pay-success");
            },
          });
        },
        fail: (err) => {
          uni.showToast({
            title: "支付失败，请重试",
            icon: "none",
            duration: 2000,
          });
        },
      });
    }
  } catch (error) {
    console.error("操作失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 投诉电话
const openFeedback = () => {
  const phoneNumber = props.orderData.complaintHotline;
  uni.makePhoneCall({ phoneNumber });
};
</script>

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