<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <image src="/static/images/search-icon.png" class="search-icon" />
        <input 
          v-model="searchKeyword"
          class="search-input" 
          placeholder="搜索保险产品"
          @input="onSearchInput"
          @confirm="handleSearch"
        />
        <text v-if="searchKeyword" class="clear-btn" @tap="clearSearch">×</text>
      </view>
    </view>
    
    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <scroll-view class="tabs-scroll" scroll-x="true">
        <view class="tab-list">
          <text 
            v-for="category in categories" 
            :key="category.value"
            class="tab-item"
            :class="{ active: selectedCategory === category.value }"
            @tap="selectCategory(category.value)"
          >
            {{ category.label }}
          </text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 产品列表 -->
    <view class="product-list">
      <view 
        v-for="product in products" 
        :key="product.id"
        class="product-item"
        @tap="goToProductDetail(product.id)"
      >
        <image 
          :src="product.icon || '/static/images/default-product.png'" 
          class="product-image" 
          mode="aspectFill"
        />
        <view class="product-content">
          <view class="product-header">
            <text class="product-name">{{ product.name }}</text>
            <text v-if="product.is_hot" class="hot-tag">热门</text>
          </view>
          <text class="product-desc">{{ product.description }}</text>
          <view class="product-features">
            <text 
              v-for="feature in getProductFeatures(product)" 
              :key="feature"
              class="feature-tag"
            >
              {{ feature }}
            </text>
          </view>
          <view class="product-footer">
            <view class="price-info">
              <text class="price-label">起保费</text>
              <text class="price-value">¥{{ product.min_premium }}</text>
              <text class="price-unit">/年</text>
            </view>
            <view class="coverage-info">
              <text class="coverage-label">最高保额</text>
              <text class="coverage-value">{{ formatAmount(product.max_amount) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-if="!loading && products.length === 0" class="empty-state">
      <image src="/static/images/empty-products.png" class="empty-icon" />
      <text class="empty-text">{{ searchKeyword ? '未找到相关产品' : '暂无产品' }}</text>
      <button v-if="searchKeyword" class="empty-btn" @tap="clearSearch">清除搜索</button>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore && !loading" class="load-more" @tap="loadMore">
      <text>加载更多</text>
    </view>
    
    <!-- 没有更多数据 -->
    <view v-if="!hasMore && products.length > 0" class="no-more">
      <text>没有更多数据了</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useInsuranceStore } from '@/store/insurance'
import { INSURANCE_TYPES_TEXT } from '@/utils/constants'

// 状态管理
const insuranceStore = useInsuranceStore()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const searchTimer = ref(null)

// 产品分类
const categories = ref([
  { label: '全部', value: '' },
  { label: '人寿保险', value: 'life' },
  { label: '健康保险', value: 'health' },
  { label: '车险', value: 'car' },
  { label: '财产保险', value: 'property' },
  { label: '旅行保险', value: 'travel' }
])

// 计算属性
const products = computed(() => insuranceStore.insuranceTypes)
const hasMore = computed(() => {
  const pagination = insuranceStore.pagination.products
  return pagination.page * pagination.limit < pagination.total
})

// 获取产品特色标签
const getProductFeatures = (product) => {
  const features = []
  if (product.is_hot) features.push('热门推荐')
  if (product.min_premium <= 100) features.push('低保费')
  if (product.max_amount >= 1000000) features.push('高保额')
  return features.slice(0, 2)
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount >= 10000) {
    return (amount / 10000).toFixed(0) + '万'
  }
  return amount.toString()
}

// 加载产品列表（动态调用保险端后端）
const loadProducts = async (isRefresh = true) => {
  try {
    loading.value = true
    
    if (isRefresh) {
      insuranceStore.resetPagination('products')
    }
    
    // 构建查询参数
    const params = {
      page: isRefresh ? 1 : insuranceStore.pagination.products.page + 1
    }
    
    if (searchKeyword.value.trim()) {
      params.name = searchKeyword.value.trim()
    }
    
    if (selectedCategory.value) {
      params.category = selectedCategory.value
    }
    
    // 动态调用保险端 /api/insurance-types 接口
    await insuranceStore.fetchInsuranceTypes(params)
    
    console.log('产品列表加载成功')
  } catch (error) {
    console.error('加载产品列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 搜索输入处理（使用防抖优化）
const onSearchInput = (event) => {
  const value = event.detail.value
  searchKeyword.value = value
  
  // 清除之前的定时器
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
  
  // 设置新的定时器（300ms 防抖）
  searchTimer.value = setTimeout(() => {
    handleSearch()
  }, 300)
}

// 执行搜索
const handleSearch = () => {
  console.log('搜索关键词:', searchKeyword.value)
  loadProducts(true)
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
  loadProducts(true)
}

// 选择分类
const selectCategory = (category) => {
  selectedCategory.value = category
  console.log('选择分类:', category)
  loadProducts(true)
}

// 加载更多
const loadMore = () => {
  if (loading.value || !hasMore.value) return
  loadProducts(false)
}

// 跳转到产品详情
const goToProductDetail = (id) => {
  uni.navigateTo({
    url: `/pages/product-detail/product-detail?id=${id}`
  })
}

// 下拉刷新
const onPullDownRefresh = async () => {
  try {
    await loadProducts(true)
  } finally {
    uni.stopPullDownRefresh()
  }
}

// 页面触底加载更多
const onReachBottom = () => {
  loadMore()
}

// 生命周期
onMounted(() => {
  loadProducts(true)
})

// 页面显示时刷新
onShow(() => {
  // 如果列表为空，重新加载
  if (products.value.length === 0) {
    loadProducts(true)
  }
})
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  background: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 50rpx;
  padding: 0 30rpx;
  height: 70rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 20rpx;
  opacity: 0.6;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  height: 70rpx;
  line-height: 70rpx;
}

.clear-btn {
  font-size: 40rpx;
  color: #999;
  margin-left: 10rpx;
  padding: 0 10rpx;
}

.filter-tabs {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

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

.tab-list {
  display: flex;
  padding: 0 20rpx;
}

.tab-item {
  display: inline-block;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  white-space: nowrap;
  border-bottom: 3rpx solid transparent;
}

.tab-item.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: bold;
}

.product-list {
  padding: 20rpx;
}

.product-item {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 30rpx;
  flex-shrink: 0;
}

.product-content {
  flex: 1;
}

.product-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.hot-tag {
  background: #ff4d4f;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-left: 20rpx;
}

.product-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  margin-bottom: 15rpx;
}

.product-features {
  display: flex;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.feature-tag {
  background: #f0f9ff;
  color: #1890ff;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 20rpx;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.price-label {
  font-size: 24rpx;
  color: #999;
  margin-right: 10rpx;
}

.price-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
}

.price-unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 4rpx;
}

.coverage-info {
  text-align: right;
}

.coverage-label {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.coverage-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.loading {
  text-align: center;
  padding: 60rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 40rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.empty-btn {
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 44rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.load-more {
  text-align: center;
  padding: 40rpx;
  color: #1890ff;
  font-size: 28rpx;
}

.no-more {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 26rpx;
}
</style>