<template>
  <div class="bg-white flex items-center justify-between pt-[12px] pr-[12px] pb-[44px] pl-[12px] rounded-t-[12px]">
    <button v-if="['1', '2'].includes(statusCode)"
      class="bg-white rounded-[10px] flex items-center justify-center text-[14px] font-medium text-ink-600 mr-[12px] h-[48px] w-[104px] border border-[#e5e8ee]"
      @click="emit('refund', orderData)">
      {{ t("order.footer.refund") }}
    </button>
    <button :class="[
      'border-none rounded-[10px] flex flex-1 items-center justify-center text-[14px] font-medium bg-[#f0f8f3] h-[48px]',
      {
        'text-[#ff3d60]': statusCode === '0',
        'text-white': ['1', '2', '3', '4', '5', '6'].includes(statusCode),
      },
    ]" @click="handleButtonClick(orderData)">
      {{ buttonText }}
    </button>
  </div>
</template>

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

const { t } = useI18n();

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 t("order.footer.payNow");
    case "1": // 已取消状态
    case "2": // 已取消状态
    case "3": // 已取消状态
    case "4": // 已取消状态
    case "5": // 已关闭状态
    case "6": // 已完成状态
      return t("order.footer.bookAgain");
  }
});

// 定义事件发射器
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: t("order.footer.submitting") });

      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(() => {
          showToast(res.msg || t("order.footer.createFailed"));
        }, 100);
        return;
      }

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

      // 验证支付参数是否完整
      if (!nonceStr || !packageVal || !paySign || !signType || !timeStamp) {
        uni.hideLoading();
        setTimeout(() => {
          showToast(t("order.footer.payParamsInvalid"));
        }, 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: async () => {
          await showToast(t("order.footer.paySuccess"));
          emit("refresh", { orderId: orderId });
        },
        fail: () => {
          showToast(t("order.footer.payFailed"));
        },
      });
      // #endif

      // #ifdef APP-PLUS
      uni.showModal({
        title: t("order.footer.tipTitle"),
        content: t("order.footer.payDeveloping"),
        showCancel: false,
      });
      // #endif
    }
  } catch (error) {
    console.error("操作失败:", error);
    uni.hideLoading();
  }
}, 1000);
</script>
