<template>
  <div class="h-screen flex flex-col bg-[linear-gradient(180deg,#e8fff1_0%,#f5f7fa_100%)_0_86px/100%_100px_no-repeat]">
    <TopNavBar titleAlign="center" backgroundColor="#E8FFF1" backIconColor="#000" :shadow="false">
      <template #title>
        {{ getGoodsTypeLabel(orderData.orderType) }}
      </template>
    </TopNavBar>

    <div class="flex-1  p-[12px] overflow-hidden overflow-y-auto">
      <!-- 预约内容 -->
      <div class="bg-white p-[12px] rounded-[12px] mb-[12px]">
        <!-- 酒店类型入住离店日期部分 -->
        <DateRangeSection v-if="orderData.orderType == 0" :selectedDate="selectedDate" :showBtn="true"
          @click="navigateToDetail(orderData)" />

        <div class="text-[16px] font-medium text-black leading-[24px] truncate">
          {{ orderData.commodityName }}
        </div>

        <div class=" border-b border-ink-200">
          <div class="text-[12px] text-ink-400 leading-[16px] pb-[12px] break-all">
            {{ orderData.commodityDescription }}
          </div>

          <!-- 权益部分 -->
          <div class="flex items-center mb-[8px]">
            <span
              class="bg-[#f7f7f7] rounded-[4px] text-[11px] text-ink-600 mr-[4px] pt-[4px] pb-[4px] pl-[6px] pr-[6px]"
              v-for="(item, index) in orderData.commodityFacilityList" :key="index">
              {{ item }}
            </span>
          </div>
        </div>

        <div class="flex items-center justify-between pt-[12px]">
          <span class="text-[12px] text-ink-600 leading-[18px]">{{ t("booking.policy.description") }}</span>
          <div class="flex items-center">
            <span class="text-[12px] text-[#2D91FF] leading-[16px]" @click="refundVisible = true">{{
              t("booking.policy.title") }}</span>
            <van-icon name="arrow" size="15" color="#99A0AE" />
          </div>
        </div>
      </div>

      <!-- 非酒店类型 -->
      <ContactSection v-if="orderData.orderType != 0" v-model="quantity" :userFormList="userFormList"
        v-model:reservationDate="selectedReservationDate" :orderData="orderData" />

      <!-- 酒店类型 -->
      <UserSection v-if="orderData.orderType == 0" v-model="quantity" :userFormList="userFormList" />
    </div>

    <!-- 底部 -->
    <FooterSection v-if="Object.keys(orderData).length" v-model="quantity" :selectedDate="selectedDate"
      :orderData="orderData" @detailClick="detailVisible = true" @payClick="handlePayClick" />

    <!-- 取消政策弹窗 -->
    <RefundPopup v-model="refundVisible" :orderData="orderData" />

    <!-- 明细弹窗 -->
    <DetailPopup v-model="detailVisible" :orderData="orderData" />
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from 'vue-router'
import TopNavBar from "@/components/TopNavBar/index.vue";
import DateRangeSection from "@/components/DateRangeSection/index.vue";
import ContactSection from "./components/ConactSection/index.vue";
import UserSection from "./components/UserSection/index.vue";
import RefundPopup from "@/components/RefundPopup/index.vue";
import DetailPopup from "./components/DetailPopup/index.vue";
import FooterSection from "./components/FooterSection/index.vue";
import { goodsDetail, orderPay } from "@/api/goods";
import { useSelectedDateStore } from "@/store";
import { ThrottleUtils } from "@/utils/ThrottleUtils";
import { PhoneUtils } from "@/utils/PhoneUtils";


const router = useRouter();
const { t } = useI18n();

const refundVisible = ref(false);
const detailVisible = ref(false);
const orderData = ref({});
const selectedDate = ref({
  startDate: "",
  endDate: "",
  totalDays: 1,
});
const quantity = ref(1);
const selectedReservationDate = ref("");
const goodsTypeKeys = {
  0: "goods.types.hotel",
  1: "goods.types.ticket",
  2: "goods.types.food",
  3: "goods.types.package",
};
const getGoodsTypeLabel = (type) => t(goodsTypeKeys[type] || "goods.title.detail");

// 工具函数
const createEmptyUserForm = () => ({ visitorName: "", contactPhone: "" });
const userFormList = ref([createEmptyUserForm()]);
const isDeleting = ref(false); // 标志位，防止删除时watch冲突

// 监听 quantity 变化，动态调整 userFormList
watch(
  quantity,
  async (newQuantity) => {
    // 只有在酒店类型（orderType == 0）时才动态调整 userFormList
    if (orderData.value.orderType !== 0) return;

    // 如果正在执行删除操作，跳过watch逻辑
    if (isDeleting.value) {
      isDeleting.value = false;
      return;
    }

    const currentLength = userFormList.value.length;

    if (newQuantity > currentLength) {
      // 数量增加，添加新的表单项
      const newForms = Array.from({ length: newQuantity - currentLength }, () =>
        createEmptyUserForm(),
      );
      userFormList.value.push(...newForms);
    } else if (newQuantity < currentLength) {
      // 数量减少，删除多余的表单项
      userFormList.value.splice(newQuantity);
    }

    // 等待DOM更新完成
    await nextTick();
  },
  { immediate: false },
);


// TODO

// onLoad((options) => {
//   const { commodityId } = options;

//   getGoodsDetail(commodityId);
// });

// onShow(() => {
//   const selectedDateStore = useSelectedDateStore();

//   selectedDate.value.startDate = selectedDateStore.selectedDate.startDate;
//   selectedDate.value.endDate = selectedDateStore.selectedDate.endDate;
//   selectedDate.value.totalDays = selectedDateStore.selectedDate.totalDays;
// });

const getGoodsDetail = async (commodityId) => {
  const res = await goodsDetail({ commodityId });

  console.log("获取商品详情", res);

  orderData.value = res.data;
  // 取commodityFacilityList前3个
  orderData.value.commodityFacilityList = res.data.commodityFacilityList.slice(
    0,
    3,
  );
};

// 跳转商品详情
const navigateToDetail = ({ commodityId }) => {
  router.push({
    path: "/pages/goods/index",
    query: {
      commodityId,
    },
  });
};

// 验证用户姓名
const validateUserForms = () => {
  const invalidUsers = userFormList.value.filter((user) => {
    return user.visitorName.trim() === "";
  });

  if (invalidUsers.length) {
    showToast(t("booking.validation.nameRequired"));
    return false;
  }

  return true;
};

// 处理支付点击事件
const handlePayClick = ThrottleUtils.createThrottle(async (goodsData) => {
  console.log("处理支付点击事件", userFormList.value);
  // 预约日期，酒店类型不需要
  if (orderData.value.reservationEnabled) {
    if (!selectedReservationDate.value) {
      showToast(t("booking.validation.reservationDateRequired"));
      return;
    }
  }

  // 校验用户姓名
  if (!validateUserForms()) {
    return;
  }

  // 校验手机号
  if (!PhoneUtils.validatePhone(userFormList.value[0].contactPhone)) {
    showToast(t("booking.validation.validPhone"));
    return;
  }

  // 购买的商品id
  const commodityId = goodsData.commodityId;
  // 消费者信息
  const consumerInfoEntityList = userFormList.value;
  // 购买数量
  const purchaseAmount = quantity.value;
  // 支付方式 0-微信 1-支付宝 2-云闪付
  const payWay = "0";
  // 支付渠道 0-app 1-小程序 2-h5
  const paySource = "1";

  const params = {
    commodityId,
    purchaseAmount,
    payWay,
    paySource,
    consumerInfoEntityList,
  };

  // 预约日期，酒店类型不需要
  if (orderData.value.reservationEnabled) {
    params.reservationDate = selectedReservationDate.value;
  }

  //酒店类型添加入住时间、离店时间
  if (goodsData.orderType == 0 && selectedDate.value) {
    const { startDate, endDate } = selectedDate.value;
    // 入住时间
    params.checkInData = startDate;
    // 离店时间
    params.checkOutData = endDate;
  }

  // 点击后立即展示 loading
  const res = await orderPay(params);
  console.log("确认订单---2:", res);


  // 检查接口返回数据
  if (!res || !res.data) {
    return;
  }

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

  // 验证支付参数是否完整
  if (!nonceStr || !packageVal || !paySign || !signType || !timeStamp) {
    return;
  }
}, 1000);
</script>
