<template>
  <view class="page-index">
    <!-- 头部区域 -->
    <view class="header-section">
      <view class="header-top">
        <view class="city-selector" @tap="openCityPicker">
          <text class="city-name">{{ searchParams.city }}</text>
          <u-icon name="arrow-down" :size="16" color="#fff" />
        </view>
        <view class="header-icon">
          <u-icon name="bell" :size="22" color="#fff" />
        </view>
      </view>

      <view class="header-title">
        <text class="title-main">找个心仪的地方</text>
        <text class="title-sub">开启美好旅程</text>
      </view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-box" @tap="goLocationSearch">
        <u-icon name="search" :size="22" color="#999" />
        <text class="search-text">{{ searchParams.keyword || '搜索酒店、民宿、位置' }}</text>
      </view>

      <view class="date-selector" @tap="openDatePicker">
        <view class="date-info">
          <view class="date-col">
            <text class="date-day">{{ checkInLabel }}</text>
            <text class="date-tip">入住</text>
          </view>
          <view class="date-sep">
            <view class="sep-line" />
            <text class="sep-nights">{{ nightCount }}晚</text>
            <view class="sep-line" />
          </view>
          <view class="date-col">
            <text class="date-day">{{ checkOutLabel }}</text>
            <text class="date-tip">离店</text>
          </view>
        </view>
      </view>

      <view class="filter-row">
        <view class="filter-btn" @tap="openPricePicker">
          <u-icon name="rmb-circle" :size="18" color="#666" />
          <text class="filter-label">{{ priceRangeLabel || '价格筛选' }}</text>
        </view>
        <view class="search-btn" @tap="handleSearch">
          <text class="search-btn-text">搜索</text>
          <u-icon name="arrow-right" :size="16" color="#fff" />
        </view>
      </view>
    </view>

    <!-- 分类卡片 -->
    <view class="category-cards">
      <view
        v-for="category in categories"
        :key="category.type"
        class="category-card"
        :style="{ background: category.gradient }"
        @tap="handleCategoryClick(category.type)"
      >
        <text class="category-title">{{ category.name }}</text>
        <text class="category-desc">{{ category.desc }}</text>
      </view>
    </view>

    <!-- 推荐房源 -->
    <view class="recommend-section">
      <view class="section-header">
        <scroll-view scroll-x class="header-tabs" :show-scrollbar="false">
          <view
            v-for="tag in filterTags"
            :key="tag.value"
            class="header-tab"
            :class="{ active: activeTag === tag.value }"
            @tap="handleTagClick(tag.value)"
          >
            {{ tag.label }}
          </view>
        </scroll-view>
      </view>

      <scroll-view
        scroll-y
        class="merchant-list"
        @scrolltolower="handleLoadMore"
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="handleRefresh"
      >
        <!-- 骨架屏 -->
        <view v-if="isLoading && merchants.length === 0" class="skeleton-wrapper">
          <view v-for="i in 3" :key="i" class="skeleton-card">
            <view class="skeleton-image" />
            <view class="skeleton-info">
              <view class="skeleton-bar long" />
              <view class="skeleton-bar" />
              <view class="skeleton-bar short" />
            </view>
          </view>
        </view>

        <!-- 商家列表 -->
        <view v-else class="merchant-container">
          <merchant-card
            v-for="merchant in displayMerchants"
            :key="merchant.id"
            :merchant="merchant"
            @click="handleMerchantClick(merchant.id)"
          />
        </view>

        <!-- 加载中 -->
        <view v-if="isLoading && merchants.length > 0" class="loading-tip">
          <loading-state size="small" />
        </view>

        <!-- 到底了 -->
        <view v-if="!hasMoreData && merchants.length > 0" class="end-tip">
          <text class="end-text">· 到底了 ·</text>
        </view>

        <!-- 空状态 -->
        <empty-state
          v-if="merchants.length === 0 && !isLoading"
          type="search"
          title="暂无房源"
          description="换个条件试试"
          @action="handleRefresh"
        />
      </scroll-view>
    </view>

    <!-- 弹窗 -->
    <CityPicker
      ref="cityPickerRef"
      :city="searchParams.city"
      @change="handleCityChange"
    />
    <DatePicker
      ref="datePickerRef"
      :check-in="searchParams.checkIn"
      :check-out="searchParams.checkOut"
      @change="handleDateChange"
    />
    <RoomGuestPicker
      ref="roomGuestPickerRef"
      :room-count="searchParams.roomCount"
      :adult-count="searchParams.adultCount"
      :child-count="searchParams.childCount"
      @change="handleRoomGuestChange"
    />
    <PricePicker
      ref="pricePickerRef"
      :min="searchParams.minPrice"
      :max="searchParams.maxPrice"
      @change="handlePriceChange"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getMerchantList } from '@/api/user/merchant';
import { getDefaultDates, formatDateShort, calculateNights } from '@/utils/date';
import type { Merchant, MerchantCardData, SearchParams } from '@/types/merchant';
import CityPicker from '@/components/CityPicker.vue';
import DatePicker from '@/components/DatePicker.vue';
import RoomGuestPicker from '@/components/RoomGuestPicker.vue';
import PricePicker from '@/components/PricePicker.vue';
import MerchantCard from '@/components/business/MerchantCard.vue';
import LoadingState from '@/components/base/LoadingState.vue';
import EmptyState from '@/components/base/EmptyState.vue';

// 获取页面参数（用于接收邀请码）
onLoad((options: any) => {
  // 从小程序码 scene 参数中获取邀请码
  if (options.scene) {
    const scene = decodeURIComponent(options.scene);
    const match = scene.match(/i=([^&]+)/);
    if (match) {
      const inviteCode = match[1];
      // 保存邀请码到本地存储
      uni.setStorageSync('pendingInviteCode', inviteCode);
      console.log('获取到邀请码:', inviteCode);
    }
  }

  // 直接从 URL 参数获取邀请码
  if (options.inviteCode) {
    uni.setStorageSync('pendingInviteCode', options.inviteCode);
    console.log('获取到邀请码:', options.inviteCode);
  }
});

// 常量
const DEFAULT_CITY = '上海';
const PAGE_SIZE = 10;
const DEFAULT_COVER = '/static/default-avatar.png';

// 分类数据
const categories = ref([
  {
    type: 'hotel',
    name: '精品酒店',
    icon: 'home',
    desc: '舒适商务之选',
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  },
  {
    type: 'homestay',
    name: '特色民宿',
    icon: 'home-fill',
    desc: '体验当地生活',
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  },
  {
    type: 'apartment',
    name: '品质公寓',
    icon: 'grid',
    desc: '长住更优惠',
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  },
  {
    type: 'hostel',
    name: '青年旅舍',
    icon: 'bag',
    desc: '结识新朋友',
    gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
  },
]);

// 筛选标签
const filterTags = ref([
  { label: '推荐', value: 'recommend' },
  // { label: '特价', value: 'discount' },
  { label: '高分', value: 'rating' },
  // { label: '新房源', value: 'new' },
]);

const activeTag = ref('recommend');

// 获取默认日期
const { today, tomorrow } = getDefaultDates();

// 搜索参数
const searchParams = reactive<SearchParams>({
  city: DEFAULT_CITY,
  keyword: '',
  checkIn: today,
  checkOut: tomorrow,
  roomCount: 1,
  adultCount: 1,
  childCount: 0,
  minPrice: undefined,
  maxPrice: undefined,
});

// 商家列表状态
const merchants = ref<Merchant[]>([]);
const currentPage = ref(1);
const isLoading = ref(false);
const isRefreshing = ref(false);
const hasMoreData = ref(true);

// 弹窗引用
const cityPickerRef = ref();
const datePickerRef = ref();
const roomGuestPickerRef = ref();
const pricePickerRef = ref();

// 计算属性
const nightCount = computed(() =>
  calculateNights(searchParams.checkIn, searchParams.checkOut)
);

const checkInLabel = computed(() =>
  formatDateShort(searchParams.checkIn)
);

const checkOutLabel = computed(() =>
  formatDateShort(searchParams.checkOut)
);

const priceRangeLabel = computed(() => {
  const { minPrice, maxPrice } = searchParams;
  if (minPrice === undefined && maxPrice === undefined) return '';
  if (minPrice !== undefined && maxPrice !== undefined) return `¥${minPrice}-${maxPrice}`;
  if (minPrice !== undefined) return `¥${minPrice}+`;
  return `¥${maxPrice}以下`;
});

const displayMerchants = computed<MerchantCardData[]>(() =>
  merchants.value.map(transformMerchantData)
);

// 数据转换
function transformMerchantData(merchant: Merchant): MerchantCardData {
  return {
    id: merchant.id,
    name: merchant.shopName,
    coverImage: merchant.coverImage || merchant.logo || DEFAULT_COVER,
    cityName: merchant.city,
    city: merchant.city,
    district: merchant.district,
    province: merchant.province,
    rating: merchant.rating,
    reviewCount: merchant.reviewCount,
    description: merchant.description || '暂无简介',
    facilities: merchant.facilities || [],
    minPrice: merchant.minPrice || 0,
    roomCount: merchant.roomCount,
    distance: merchant.distance,
    isRecommend: merchant.isRecommend,
    isHot: merchant.isHot,
    isNew: merchant.isNew,
    salesCount: merchant.salesCount,
  };
}

// 获取商家列表
async function fetchMerchantList(shouldReset = false) {
  if (isLoading.value) return;
  if (!shouldReset && !hasMoreData.value) return;

  isLoading.value = true;

  if (shouldReset) {
    currentPage.value = 1;
    hasMoreData.value = true;
  }

  try {
    const response = await getMerchantList({
      page: currentPage.value,
      pageSize: PAGE_SIZE,
      checkInDate: searchParams.checkIn,
      checkOutDate: searchParams.checkOut,
    });

    const list = response.data?.list || [];
    merchants.value = shouldReset ? list : [...merchants.value, ...list];
    hasMoreData.value = list.length >= PAGE_SIZE;
    currentPage.value++;
  } catch (error) {
    console.error('获取商家列表失败:', error);
    uni.showToast({ title: '加载失败，请重试', icon: 'none' });
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
  }
}

// 弹窗操作
function openCityPicker() {
  cityPickerRef.value?.open();
}

function openDatePicker() {
  datePickerRef.value?.open();
}

function openPricePicker() {
  pricePickerRef.value?.open();
}

// 弹窗回调
function handleCityChange(city: string) {
  searchParams.city = city;
}

function handleDateChange(checkIn: string, checkOut: string) {
  searchParams.checkIn = checkIn;
  searchParams.checkOut = checkOut;
}

function handleRoomGuestChange(rooms: number, adults: number, children: number) {
  searchParams.roomCount = rooms;
  searchParams.adultCount = adults;
  searchParams.childCount = children;
}

function handlePriceChange(min: number | undefined, max: number | undefined) {
  searchParams.minPrice = min;
  searchParams.maxPrice = max;
}

// 导航操作
function goLocationSearch() {
  uni.navigateTo({ url: '/pages/location-search/index' });
}

function handleSearch() {
  const queryParams = buildSearchQuery();
  uni.navigateTo({ url: `/pages/search/index?${queryParams}` });
}

function handleMerchantClick(merchantId: number) {
  const queryParams = buildMerchantQuery(merchantId);
  uni.navigateTo({ url: `/pages/merchant-detail/index?${queryParams}` });
}

// 分类点击
function handleCategoryClick(type: string) {
  const queryParams = buildSearchQuery();
  uni.navigateTo({ url: `/pages/search/index?${queryParams}&type=${type}` });
}

// 标签点击
function handleTagClick(tag: string) {
  activeTag.value = tag;
  fetchMerchantList(true);
}

// 构建查询参数
function buildSearchQuery(): string {
  const params = [
    `city=${encodeURIComponent(searchParams.city)}`,
    searchParams.keyword ? `keyword=${encodeURIComponent(searchParams.keyword)}` : '',
    `checkIn=${searchParams.checkIn}`,
    `checkOut=${searchParams.checkOut}`,
    `roomCount=${searchParams.roomCount}`,
    `adultCount=${searchParams.adultCount}`,
    `childCount=${searchParams.childCount}`,
    searchParams.minPrice !== undefined ? `minPrice=${searchParams.minPrice}` : '',
    searchParams.maxPrice !== undefined ? `maxPrice=${searchParams.maxPrice}` : '',
  ];
  return params.filter(Boolean).join('&');
}

function buildMerchantQuery(merchantId: number): string {
  return [
    `id=${merchantId}`,
    `checkIn=${searchParams.checkIn}`,
    `checkOut=${searchParams.checkOut}`,
    `roomCount=${searchParams.roomCount}`,
    `adultCount=${searchParams.adultCount}`,
    `childCount=${searchParams.childCount}`,
  ].join('&');
}

// 列表操作
function handleRefresh() {
  isRefreshing.value = true;
  fetchMerchantList(true);
}

function handleLoadMore() {
  fetchMerchantList(false);
}

// 处理位置搜索回传的关键词
function checkLocationSearchKeyword() {
  const globalUni = uni as any;
  const keyword = globalUni.__locationSearchKeyword;
  if (keyword) {
    searchParams.keyword = keyword;
    globalUni.__locationSearchKeyword = '';
  }
}

// 生命周期
onMounted(() => {
  checkLocationSearchKeyword();
  fetchMerchantList(true);
});

onActivated(() => {
  checkLocationSearchKeyword();
});
</script>

<style lang="scss" scoped>
@import '@/static/styles/design-tokens.scss';
@import '@/static/styles/mixins.scss';

.page-index {
  min-height: 100vh;
  background: #f8f9fb;
}

/* ========== 头部区域 ========== */
.header-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24rpx 32rpx 80rpx;
  position: relative;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.city-selector {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50rpx;
  backdrop-filter: blur(10rpx);
  transition: all 0.3s;

  &:active {
    background: rgba(255, 255, 255, 0.3);
  }
}

.city-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
}

.header-icon {
  width: 72rpx;
  height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  backdrop-filter: blur(10rpx);
  transition: all 0.3s;

  &:active {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0.95);
  }
}

.header-title {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.title-main {
  font-size: 48rpx;
  font-weight: 700;
  color: #fff;
  letter-spacing: 1rpx;
}

.title-sub {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.85);
  font-weight: 400;
}

/* ========== 搜索区域 ========== */
.search-section {
  margin: -60rpx 32rpx 32rpx;
  padding: 32rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.15);
  position: relative;
  z-index: 10;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 28rpx 32rpx;
  background: #f5f7fa;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  transition: all 0.3s;

  &:active {
    background: #ebeef5;
  }
}

.search-text {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.date-selector {
  margin-bottom: 24rpx;
  padding: 28rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  border-radius: 16rpx;
  transition: all 0.3s;

  &:active {
    background: linear-gradient(135deg, #ebeef5 0%, #dfe3e8 100%);
  }
}

.date-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.date-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.date-day {
  font-size: 36rpx;
  font-weight: 700;
  color: #1a1a1a;
}

.date-tip {
  font-size: 24rpx;
  color: #999;
}

.date-sep {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 0 32rpx;
}

.sep-line {
  width: 40rpx;
  height: 2rpx;
  background: #ddd;
}

.sep-nights {
  font-size: 20rpx;
  color: $primary-color;
  font-weight: 600;
  padding: 4rpx 12rpx;
  background: rgba($primary-color, 0.1);
  border-radius: 8rpx;
}

.filter-row {
  display: flex;
  gap: 16rpx;
}

.filter-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 24rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  transition: all 0.3s;

  &:active {
    background: #ebeef5;
    transform: scale(0.98);
  }
}

.filter-label {
  font-size: 26rpx;
  color: #666;
  font-weight: 500;
}

.search-btn {
  flex: 1.5;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 24rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
  }
}

.search-btn-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
}

/* ========== 分类卡片 ========== */
.category-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  padding: 0 32rpx 32rpx;
}

.category-card {
  padding: 32rpx 24rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 100rpx;
    height: 100rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 0 0 0 100rpx;
  }

  &:active {
    transform: translateY(-4rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
  }
}

.category-icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  backdrop-filter: blur(10rpx);
}

.category-title {
  font-size: 30rpx;
  font-weight: 700;
  color: #fff;
  margin-top: 8rpx;
}

.category-desc {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.85);
}

/* ========== 推荐房源 ========== */
.recommend-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  overflow: hidden;
}

.section-header {
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 24rpx;
}

.header-tabs {
  white-space: nowrap;
}

.header-tab {
  display: inline-block;
  padding: 12rpx 28rpx;
  margin-right: 16rpx;
  background: #f5f7fa;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
  font-weight: 500;
  transition: all 0.3s;

  &.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  }

  &:active {
    transform: scale(0.96);
  }
}

/* ========== 商家列表 ========== */
.merchant-list {
  flex: 1;
  height: 0;
}

.merchant-container {
  padding: 24rpx 32rpx 32rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 骨架屏 */
.skeleton-wrapper {
  padding: 24rpx 32rpx;
}

.skeleton-card {
  display: flex;
  gap: 24rpx;
  padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.skeleton-image {
  width: 200rpx;
  height: 200rpx;
  flex-shrink: 0;
  border-radius: 12rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;
}

.skeleton-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 20rpx;
}

.skeleton-bar {
  height: 28rpx;
  border-radius: 8rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;

  &.long {
    width: 80%;
  }

  &.short {
    width: 50%;
  }
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 加载提示 */
.loading-tip {
  padding: 32rpx;
  display: flex;
  justify-content: center;
}

.end-tip {
  padding: 48rpx 32rpx;
  display: flex;
  justify-content: center;
}

.end-text {
  font-size: 24rpx;
  color: #ccc;
  letter-spacing: 4rpx;
}
</style>
