<template>
  <view class="footer bg-white flex items-center justify-between p-[12px]">
    <button v-if="['1', '2'].includes(statusCode)"
      class="left border-none after:!hidden bg-white rounded-[10px] flex items-center justify-center text-[14px] font-[500] text-[#525866] mr-[12px]"
      @click="emit('refund', orderData)">
      申请退款
    </button>
    <button :class="[
      'right border-none after:!hidden rounded-[10px] flex flex-1 items-center justify-center text-[14px] font-[500] bg-[#0CCD58]',
      {
        'bg-[#ff3d60]': statusCode === '0',
        'text-white': ['1', '2', '3', '4', '5', '6'].includes(statusCode),
      },
    ]" @click="handleButtonClick(orderData)">
      {{ buttonText }}
    </button>
  </view>
</template>

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

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 buttonText = 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 = ThrottleUtils.createExecutionLock(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) {
        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) {
        setTimeout(() => {
          uni.showToast({ title: "支付参数错误，请重试", icon: "none" });
        }, 100);
        return;
      }

      // 关闭 loading
      uni.hideLoading();

      // #ifdef MP-WEIXIN
      // 调用微信支付 - 包装成 Promise 以便锁住执行状态
      await new Promise((resolve) => {
        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 });
              },
            });
            resolve();
          },
          fail: () => {
            uni.showToast({ title: "支付失败，请重试", icon: "none" });
            resolve();
          },
        });
      });
      // #endif

      // #ifdef APP-PLUS
      uni.showModal({
        title: "提示",
        content: "支付功能开发中",
        showCancel: false,
      });
      // #endif
    }
  } catch (error) {
    console.error("操作失败:", error);
    uni.showToast({ title: "操作失败，请重试", icon: "none" });
  } finally {
    // 确保 loading 被关闭
    uni.hideLoading();
  }
});
</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>
