<template>
  <view class="search-page">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-bar">
        <view class="back-icon" @tap="goBack">
          <u-icon name="arrow-left" size="20" color="#333" />
        </view>
        <view class="input-wrapper">
          <u-icon name="search" size="18" color="#999" />
          <input
            v-model="keyword"
            type="text"
            placeholder="搜索酒店、民宿、品牌"
            confirm-type="search"
            class="input"
            @confirm="handleSearch"
          />
          <view v-if="keyword" class="clear-icon" @tap="clearKeyword">
            <u-icon name="close-circle-fill" size="16" color="#ccc" />
          </view>
        </view>
        <text class="search-text" @tap="handleSearch">搜索</text>
      </view>

      <view class="filter-bar">
        <view class="filter-item">
          <u-icon name="map-fill" size="14" color="#ff6b35" />
          <text class="filter-text">{{ city }}</text>
        </view>
        <view class="divider" />
        <view class="filter-item">
          <u-icon name="calendar-fill" size="14" color="#ff6b35" />
          <text class="filter-text">{{ dateRangeText }}</text>
        </view>
      </view>
    </view>

    <!-- 结果统计 -->
    <view v-if="!loading && merchantList.length > 0" class="result-info">
      <text class="result-text">找到 <text class="result-num">{{ merchantList.length }}</text> 家</text>
    </view>

    <!-- 列表 -->
    <scroll-view
      scroll-y
      class="scroll-view"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-wrapper">
        <MerchantCard
          v-for="merchant in merchantList"
          :key="merchant.id"
          :merchant="formatMerchant(merchant)"
          @click="goMerchant(merchant.id)"
          class="merchant-item"
        />
      </view>

      <LoadingState v-if="loading" mode="dots" />

      <view v-if="!hasMore && merchantList.length > 0" class="load-end">
        <text class="end-text">没有更多了</text>
      </view>

      <EmptyState
        v-if="merchantList.length === 0 && !loading"
        type="search"
        description="换个关键词试试"
      />
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getMerchantList } from '@/api/user/merchant';
import MerchantCard from '@/components/business/MerchantCard.vue';
import EmptyState from '@/components/base/EmptyState.vue';
import LoadingState from '@/components/base/LoadingState.vue';

const city = ref('上海');
const keyword = ref('');
const checkInDate = ref('');
const checkOutDate = ref('');
const roomCount = ref(1);
const adultCount = ref(1);
const childCount = ref(0);
const minPrice = ref<number | undefined>(undefined);
const maxPrice = ref<number | undefined>(undefined);

const merchantList = ref<any[]>([]);
const page = ref(1);
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);

const dateRangeText = computed(() => {
  if (!checkInDate.value || !checkOutDate.value) return '选择日期';
  const checkIn = new Date(checkInDate.value);
  const checkOut = new Date(checkOutDate.value);
  const nights = Math.max(1, Math.ceil((checkOut.getTime() - checkIn.getTime()) / (1000 * 60 * 60 * 24)));
  return `${checkIn.getMonth() + 1}/${checkIn.getDate()}-${checkOut.getMonth() + 1}/${checkOut.getDate()} · ${nights}晚`;
});

function initFromUrl() {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const options = currentPage.options || currentPage.$page?.options || {};

  city.value = options.city ? decodeURIComponent(options.city) : '上海';
  keyword.value = options.keyword ? decodeURIComponent(options.keyword) : '';
  checkInDate.value = options.checkIn || '';
  checkOutDate.value = options.checkOut || '';
  roomCount.value = options.roomCount != null ? Number(options.roomCount) : 1;
  adultCount.value = options.adultCount != null ? Number(options.adultCount) : 1;
  childCount.value = options.childCount != null ? Number(options.childCount) : 0;
  minPrice.value = options.minPrice != null ? Number(options.minPrice) : undefined;
  maxPrice.value = options.maxPrice != null ? Number(options.maxPrice) : undefined;
}

onMounted(() => {
  initFromUrl();
  fetchMerchants(true);
});

async function fetchMerchants(reset = false) {
  if (loading.value) return;
  if (!reset && !hasMore.value) return;

  loading.value = true;
  if (reset) {
    page.value = 1;
    hasMore.value = true;
  }

  try {
    const res = await getMerchantList({
      page: page.value,
      pageSize: 10,
      city: city.value,
      keyword: keyword.value || undefined,
    });
    const list = res.data?.list || [];
    merchantList.value = reset ? list : [...merchantList.value, ...list];
    hasMore.value = list.length >= 10;
    page.value++;
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
}

function handleSearch() {
  fetchMerchants(true);
}

function loadMore() {
  fetchMerchants();
}

function onRefresh() {
  refreshing.value = true;
  fetchMerchants(true);
}

function goMerchant(id: number) {
  const params = [
    `id=${id}`,
    `checkIn=${checkInDate.value}`,
    `checkOut=${checkOutDate.value}`,
    `roomCount=${roomCount.value}`,
    `adultCount=${adultCount.value}`,
    `childCount=${childCount.value}`,
  ].join('&');
  uni.navigateTo({ url: `/pages/merchant-detail/index?${params}` });
}

function goBack() {
  uni.navigateBack();
}

function clearKeyword() {
  keyword.value = '';
}

function formatMerchant(merchant: any) {
  return {
    id: merchant.id,
    name: merchant.shopName,
    coverImage: merchant.coverImage || merchant.logo || '/static/default-avatar.png',
    city: merchant.city,
    district: merchant.district,
    province: merchant.province,
    rating: merchant.rating,
    reviewCount: merchant.reviewCount,
    facilities: merchant.facilities || [],
    minPrice: merchant.minPrice || 0,
    originalPrice: merchant.originalPrice,
    distance: merchant.distance,
    salesCount: merchant.salesCount,
    promotion: merchant.promotion,
    type: merchant.type,
    hasVideo: merchant.hasVideo,
    recentPurchase: merchant.recentPurchase,
    nearbyLandmark: merchant.nearbyLandmark,
  };
}
</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

// 搜索头部
.search-header {
  background: #fff;
  padding: 16rpx 24rpx 20rpx;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12rpx;
  height: 72rpx;
  padding: 0 20rpx;
  background: #f5f5f5;
  border-radius: 36rpx;
  min-width: 0;

  .input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    height: 72rpx;
    line-height: 72rpx;
    min-width: 0;
  }

  .clear-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }
}

.search-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #ff6b35;
  flex-shrink: 0;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 6rpx;

  .filter-text {
    font-size: 24rpx;
    color: #666;
  }
}

.divider {
  width: 1rpx;
  height: 24rpx;
  background: #e0e0e0;
}

// 结果统计
.result-info {
  padding: 20rpx 24rpx 12rpx;
  background: #f5f5f5;

  .result-text {
    font-size: 24rpx;
    color: #999;

    .result-num {
      font-weight: 600;
      color: #333;
    }
  }
}

// 列表
.scroll-view {
  flex: 1;
}

.list-wrapper {
  padding: 12rpx 24rpx 24rpx;
}

.merchant-item {
  margin-bottom: 16rpx;
}

.load-end {
  padding: 40rpx 0;
  text-align: center;

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