<template>
  <div class="footer bg-white border-box flex flex-items-center flex-justify-between p-12">
    <button v-if="['1', '2'].includes(statusCode)"
      class="left border-none border-box bg-white rounded-10 flex flex-items-center flex-justify-center font-size-14 font-500 color-525866 mr-12"
      @click="emit('refund', orderData)">
      申请退款
    </button>
    <button :class="[
      'right border-none rounded-10 flex flex-full flex-items-center flex-justify-center font-size-14 font-500 bg-theme-color-500',
      {
        'bg-FF3D60': statusCode === '0',
        'color-white': ['1', '2', '3', '4', '5', '6'].includes(statusCode),
      },
    ]" @click="handleButtonClick(orderData)">
      {{ buttonspan }}
    </button>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, computed } from "vue";
import { orderPayNow } from "@/api/order";
import { DebounceUtils } from "@/utils/DebounceUtils";

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 statusCode = computed(() => props.orderData.orderStatus);

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

// 定义事件发射器
const emit = defineEmits(["refund", "refresh"]);

// 处理按钮点击事件
const handleButtonClick = DebounceUtils.createDebounce(async (orderData) => {
  try {
    // 再次预定跳转商品详情
    if (["1", "2", "3", "4", "5", "6"].includes(statusCode.value)) {
      uni.navigateTo({
        url: `/pages/goods/index?commodityId=${orderData.commodityId}`,
      });
      return;
    }

    // 待支付状态，调用支付接口
    if (statusCode.value === "0") {
      // 显示 loading
      uni.showLoading({ title: "正在提交订单..." });

      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.hideLoading();
        setTimeout(() => {
          uni.showToast({
            title: res.msg || "订单创建失败，请重试",
            icon: "none",
          });
        }, 100);
        return;
      }

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

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

      // 在发起微信支付前关闭 loading（避免与原生支付 UI 冲突）
      uni.hideLoading();

      // #ifdef MP-WEIXIN
      // 调用微信支付
      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",
            success: () => {
              console.log("支付成功，刷新订单详情");
              emit("refresh", { orderId: orderId });
            },
          });
        },
        fail: () => {
          uni.showToast({ title: "支付失败，请重试", icon: "none" });
        },
      });
      // #endif

      // #ifdef APP-PLUS
      uni.showModal({
        title: "提示",
        content: "支付功能开发中",
        showCancel: false,
      });
      // #endif
    }
  } catch (error) {
    console.error("操作失败:", error);
    uni.hideLoading();
  }
}, 1000);
</script>

<style lang="scss" scoped>
.footer {
  border-radius: 12px 12px 0 0;
  padding-bottom: 88rpx;
}

.left,
.right {
  height: 48px;
}

.left {
  border: 1px solid #e5e8ee;
  width: 104px;
}
</style>
