<template>
  <view class="policy-list-page">
    <!-- 顶部搜索和筛选 -->
    <view class="header-section">
      <Search
        v-model="searchKeyword"
        placeholder="搜索保险产品名称"
        @search="handleSearch"
        @clear="handleSearchClear"
      />
      
      <view class="filter-bar">
        <view class="filter-item" @click="handleCategoryFilter">
          <text class="filter-text">{{ selectedCategory.label }}</text>
          <text class="filter-arrow">▼</text>
        </view>
        
        <view class="filter-item" @click="handleSortFilter">
          <text class="filter-text">{{ selectedSort.label }}</text>
          <text class="filter-arrow">▼</text>
        </view>
        
        <view class="filter-item" @click="handlePriceFilter">
          <text class="filter-text">价格</text>
          <text class="filter-arrow">▼</text>
        </view>
      </view>
    </view>
    
    <!-- 推荐保险 -->
    <view class="recommend-section" v-if="recommendPolicies.length">
      <Card title="推荐保险" class="recommend-card">
        <Swiper
          :list="recommendPolicies"
          :height="'300rpx'"
          :indicator-dots="true"
          :autoplay="true"
          @click="handleRecommendClick"
        >
          <template #item="{ item }">
            <view class="recommend-item">
              <image class="recommend-bg" :src="item.backgroundImage" mode="aspectFill" />
              <view class="recommend-content">
                <text class="recommend-title">{{ item.name }}</text>
                <text class="recommend-desc">{{ item.description }}</text>
                <view class="recommend-price">
                  <text class="price-text">¥{{ item.premium }}/年起</text>
                </view>
              </view>
            </view>
          </template>
        </Swiper>
      </Card>
    </view>
    
    <!-- 保险分类 -->
    <view class="category-section">
      <Card title="保险分类" class="category-card">
        <view class="category-grid">
          <view
            class="category-item"
            v-for="category in categoryList"
            :key="category.value"
            @click="handleCategoryClick(category)"
          >
            <view class="category-icon">{{ category.icon }}</view>
            <text class="category-name">{{ category.label }}</text>
            <text class="category-count">{{ category.count }}款</text>
          </view>
        </view>
      </Card>
    </view>
    
    <!-- 保险产品列表 -->
    <view class="policy-list">
      <Card
        v-for="policy in filteredPolicies"
        :key="policy.id"
        :clickable="true"
        class="policy-card"
        @click="handlePolicyClick(policy)"
      >
        <view class="policy-info">
          <!-- 保险公司logo和名称 -->
          <view class="policy-header">
            <image class="company-logo" :src="policy.companyLogo" mode="aspectFit" />
            <view class="policy-basic">
              <text class="policy-name">{{ policy.name }}</text>
              <text class="company-name">{{ policy.companyName }}</text>
            </view>
            <view class="policy-badge" v-if="policy.isHot">
              <text class="badge-text">热销</text>
            </view>
          </view>
          
          <!-- 保险特点 -->
          <view class="policy-features">
            <view
              class="feature-tag"
              v-for="feature in policy.features"
              :key="feature"
            >
              {{ feature }}
            </view>
          </view>
          
          <!-- 保障内容 -->
          <view class="policy-coverage">
            <view class="coverage-title">主要保障</view>
            <view class="coverage-list">
              <view
                class="coverage-item"
                v-for="coverage in policy.mainCoverage"
                :key="coverage.name"
              >
                <text class="coverage-name">{{ coverage.name }}</text>
                <text class="coverage-amount">{{ coverage.amount }}</text>
              </view>
            </view>
          </view>
          
          <!-- 价格和操作 -->
          <view class="policy-footer">
            <view class="price-section">
              <view class="current-price">
                <text class="price-symbol">¥</text>
                <text class="price-value">{{ policy.premium }}</text>
                <text class="price-unit">/年起</text>
              </view>
              <view class="original-price" v-if="policy.originalPremium">
                <text class="original-text">原价¥{{ policy.originalPremium }}</text>
              </view>
            </view>
            
            <view class="action-buttons">
              <button
                class="action-btn consult-btn"
                @click.stop="handleConsult(policy)"
              >
                咨询
              </button>
              <button
                class="action-btn apply-btn"
                @click.stop="handleApply(policy)"
              >
                立即投保
              </button>
            </view>
          </view>
          
          <!-- 评价信息 -->
          <view class="policy-rating" v-if="policy.rating">
            <view class="rating-stars">
              <text
                class="star"
                :class="{ active: index < Math.floor(policy.rating) }"
                v-for="index in 5"
                :key="index"
              >
                ⭐
              </text>
            </view>
            <text class="rating-score">{{ policy.rating }}分</text>
            <text class="rating-count">({{ policy.reviewCount }}人评价)</text>
          </view>
        </view>
      </Card>
    </view>
    
    <!-- 空状态 -->
    <Empty
      v-if="filteredPolicies.length === 0"
      description="暂无保险产品"
      image="🛡️"
    />
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore">
      <button class="load-more-btn" @click="loadMore" :loading="loading">
        {{ loading ? '加载中...' : '加载更多' }}
      </button>
    </view>
    
    <!-- 筛选弹窗 -->
    <view class="filter-modal" v-if="showFilterModal" @click="closeFilterModal">
      <view class="filter-content" @click.stop>
        <view class="filter-header">
          <text class="filter-title">{{ currentFilterType }}</text>
          <text class="filter-close" @click="closeFilterModal">✕</text>
        </view>
        
        <view class="filter-options">
          <view
            class="filter-option"
            :class="{ active: isOptionActive(option) }"
            v-for="option in currentFilterOptions"
            :key="option.value"
            @click="handleFilterOptionClick(option)"
          >
            <text class="option-text">{{ option.label }}</text>
            <text class="option-check" v-if="isOptionActive(option)">✓</text>
          </view>
        </view>
        
        <view class="filter-actions">
          <button class="filter-btn reset-btn" @click="handleFilterReset">
            重置
          </button>
          <button class="filter-btn confirm-btn" @click="handleFilterConfirm">
            确定
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import Search from '@/common/components/search/search.vue'
import Card from '@/common/components/card/card.vue'
import Swiper from '@/common/components/swiper/swiper.vue'
import Empty from '@/common/components/empty/empty.vue'
import { insuranceApi } from '@/common/api'

export default {
  name: 'PolicyListPage',
  components: {
    Search,
    Card,
    Swiper,
    Empty
  },
  setup() {
    // 响应式数据
    const searchKeyword = ref('')
    const loading = ref(false)
    const hasMore = ref(true)
    const currentPage = ref(1)
    const showFilterModal = ref(false)
    const currentFilterType = ref('')
    const currentFilterOptions = ref([])
    
    // 保险数据
    const policyData = ref([])
    const recommendPolicies = ref([])
    
    // 筛选条件
    const selectedCategory = ref({ label: '全部分类', value: 'all' })
    const selectedSort = ref({ label: '综合排序', value: 'default' })
    const selectedPriceRange = ref({ label: '全部价格', value: 'all' })
    
    // 分类数据
    const categoryList = [
      { label: '意外险', value: 'accident', icon: '🚑', count: 15 },
      { label: '健康险', value: 'health', icon: '🏥', count: 23 },
      { label: '财产险', value: 'property', icon: '🏠', count: 18 },
      { label: '责任险', value: 'liability', icon: '⚖️', count: 12 },
      { label: '车险', value: 'vehicle', icon: '🚗', count: 8 },
      { label: '旅游险', value: 'travel', icon: '✈️', count: 6 }
    ]
    
    // 筛选选项
    const categoryOptions = [
      { label: '全部分类', value: 'all' },
      ...categoryList
    ]
    
    const sortOptions = [
      { label: '综合排序', value: 'default' },
      { label: '价格从低到高', value: 'price_asc' },
      { label: '价格从高到低', value: 'price_desc' },
      { label: '评分最高', value: 'rating_desc' },
      { label: '最新上架', value: 'newest' }
    ]
    
    const priceOptions = [
      { label: '全部价格', value: 'all' },
      { label: '100元以下', value: '0-100' },
      { label: '100-500元', value: '100-500' },
      { label: '500-1000元', value: '500-1000' },
      { label: '1000元以上', value: '1000-' }
    ]
    
    // 计算属性
    const filteredPolicies = computed(() => {
      let result = policyData.value
      
      // 关键词搜索
      if (searchKeyword.value) {
        result = result.filter(item => 
          item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          item.companyName.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
      }
      
      // 分类筛选
      if (selectedCategory.value.value !== 'all') {
        result = result.filter(item => item.category === selectedCategory.value.value)
      }
      
      // 价格筛选
      if (selectedPriceRange.value.value !== 'all') {
        const [min, max] = selectedPriceRange.value.value.split('-').map(Number)
        result = result.filter(item => {
          const price = parseFloat(item.premium)
          if (max) {
            return price >= min && price <= max
          } else {
            return price >= min
          }
        })
      }
      
      // 排序
      switch (selectedSort.value.value) {
        case 'price_asc':
          result.sort((a, b) => parseFloat(a.premium) - parseFloat(b.premium))
          break
        case 'price_desc':
          result.sort((a, b) => parseFloat(b.premium) - parseFloat(a.premium))
          break
        case 'rating_desc':
          result.sort((a, b) => (b.rating || 0) - (a.rating || 0))
          break
        case 'newest':
          result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          break
      }
      
      return result
    })
    
    // 方法
    const loadPolicyData = async () => {
      try {
        loading.value = true
        const response = await insuranceApi.getPolicyList({
          page: currentPage.value,
          pageSize: 20,
          category: selectedCategory.value.value,
          keyword: searchKeyword.value
        })
        
        if (currentPage.value === 1) {
          policyData.value = response.data.list
        } else {
          policyData.value.push(...response.data.list)
        }
        
        hasMore.value = response.data.hasMore
      } catch (error) {
        console.error('加载保险产品失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      } finally {
        loading.value = false
      }
    }
    
    const loadRecommendPolicies = async () => {
      try {
        const response = await insuranceApi.getRecommendPolicies()
        recommendPolicies.value = response.data
      } catch (error) {
        console.error('加载推荐保险失败:', error)
      }
    }
    
    const handleSearch = (keyword) => {
      currentPage.value = 1
      loadPolicyData()
    }
    
    const handleSearchClear = () => {
      searchKeyword.value = ''
      currentPage.value = 1
      loadPolicyData()
    }
    
    const handleCategoryFilter = () => {
      currentFilterType.value = '保险分类'
      currentFilterOptions.value = categoryOptions
      showFilterModal.value = true
    }
    
    const handleSortFilter = () => {
      currentFilterType.value = '排序方式'
      currentFilterOptions.value = sortOptions
      showFilterModal.value = true
    }
    
    const handlePriceFilter = () => {
      currentFilterType.value = '价格范围'
      currentFilterOptions.value = priceOptions
      showFilterModal.value = true
    }
    
    const handleCategoryClick = (category) => {
      selectedCategory.value = category
      currentPage.value = 1
      loadPolicyData()
    }
    
    const handleRecommendClick = (e) => {
      const { item } = e
      uni.navigateTo({
        url: `/pages/policy/detail?id=${item.id}`
      })
    }
    
    const handlePolicyClick = (policy) => {
      uni.navigateTo({
        url: `/pages/policy/detail?id=${policy.id}`
      })
    }
    
    const handleConsult = (policy) => {
      uni.navigateTo({
        url: `/pages/consult/chat?policyId=${policy.id}`
      })
    }
    
    const handleApply = (policy) => {
      uni.navigateTo({
        url: `/pages/policy/apply?id=${policy.id}`
      })
    }
    
    const loadMore = () => {
      if (loading.value || !hasMore.value) return
      currentPage.value++
      loadPolicyData()
    }
    
    const closeFilterModal = () => {
      showFilterModal.value = false
    }
    
    const isOptionActive = (option) => {
      switch (currentFilterType.value) {
        case '保险分类':
          return selectedCategory.value.value === option.value
        case '排序方式':
          return selectedSort.value.value === option.value
        case '价格范围':
          return selectedPriceRange.value.value === option.value
        default:
          return false
      }
    }
    
    const handleFilterOptionClick = (option) => {
      switch (currentFilterType.value) {
        case '保险分类':
          selectedCategory.value = option
          break
        case '排序方式':
          selectedSort.value = option
          break
        case '价格范围':
          selectedPriceRange.value = option
          break
      }
    }
    
    const handleFilterReset = () => {
      switch (currentFilterType.value) {
        case '保险分类':
          selectedCategory.value = { label: '全部分类', value: 'all' }
          break
        case '排序方式':
          selectedSort.value = { label: '综合排序', value: 'default' }
          break
        case '价格范围':
          selectedPriceRange.value = { label: '全部价格', value: 'all' }
          break
      }
    }
    
    const handleFilterConfirm = () => {
      showFilterModal.value = false
      currentPage.value = 1
      loadPolicyData()
    }
    
    // 生命周期
    onMounted(() => {
      loadPolicyData()
      loadRecommendPolicies()
    })
    
    return {
      searchKeyword,
      loading,
      hasMore,
      showFilterModal,
      currentFilterType,
      currentFilterOptions,
      policyData,
      recommendPolicies,
      selectedCategory,
      selectedSort,
      selectedPriceRange,
      categoryList,
      filteredPolicies,
      handleSearch,
      handleSearchClear,
      handleCategoryFilter,
      handleSortFilter,
      handlePriceFilter,
      handleCategoryClick,
      handleRecommendClick,
      handlePolicyClick,
      handleConsult,
      handleApply,
      loadMore,
      closeFilterModal,
      isOptionActive,
      handleFilterOptionClick,
      handleFilterReset,
      handleFilterConfirm
    }
  }
}
</script>

<style lang="scss" scoped>
.policy-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header-section {
  background-color: #fff;
  padding: 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.filter-bar {
  display: flex;
  gap: 24rpx;
  margin-top: 24rpx;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  
  .filter-text {
    font-size: 24rpx;
    color: #333;
  }
  
  .filter-arrow {
    font-size: 20rpx;
    color: #666;
    transition: transform 0.3s ease;
  }
  
  &:active {
    background-color: #e9ecef;
    
    .filter-arrow {
      transform: rotate(180deg);
    }
  }
}

.recommend-section {
  margin: 16rpx 32rpx;
}

.recommend-card {
  overflow: hidden;
}

.recommend-item {
  position: relative;
  width: 100%;
  height: 300rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.recommend-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.recommend-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 32rpx;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: #fff;
}

.recommend-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 8rpx;
}

.recommend-desc {
  display: block;
  font-size: 24rpx;
  opacity: 0.9;
  margin-bottom: 16rpx;
}

.recommend-price {
  .price-text {
    font-size: 28rpx;
    font-weight: 600;
  }
}

.category-section {
  margin: 16rpx 32rpx;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24rpx;
  padding: 16rpx 0;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
  padding: 24rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  
  .category-icon {
    font-size: 48rpx;
  }
  
  .category-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
  
  .category-count {
    font-size: 22rpx;
    color: #666;
  }
  
  &:active {
    background-color: #e9ecef;
  }
}

.policy-list {
  padding: 0 32rpx;
}

.policy-card {
  margin-bottom: 24rpx;
}

.policy-info {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.policy-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  position: relative;
}

.company-logo {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
}

.policy-basic {
  flex: 1;
  
  .policy-name {
    display: block;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .company-name {
    font-size: 24rpx;
    color: #666;
  }
}

.policy-badge {
  position: absolute;
  top: -8rpx;
  right: 0;
  padding: 6rpx 12rpx;
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  border-radius: 12rpx;
  
  .badge-text {
    font-weight: 500;
  }
}

.policy-features {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.feature-tag {
  padding: 8rpx 16rpx;
  background-color: #f0f8f0;
  color: #2e8b57;
  font-size: 22rpx;
  border-radius: 16rpx;
}

.policy-coverage {
  .coverage-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .coverage-list {
    display: flex;
    flex-direction: column;
    gap: 12rpx;
  }
  
  .coverage-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12rpx 0;
    border-bottom: 2rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .coverage-name {
      font-size: 26rpx;
      color: #333;
    }
    
    .coverage-amount {
      font-size: 26rpx;
      color: #2e8b57;
      font-weight: 600;
    }
  }
}

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

.price-section {
  .current-price {
    display: flex;
    align-items: baseline;
    margin-bottom: 4rpx;
    
    .price-symbol {
      font-size: 24rpx;
      color: #ff4757;
      font-weight: 600;
    }
    
    .price-value {
      font-size: 36rpx;
      color: #ff4757;
      font-weight: 600;
      margin: 0 4rpx;
    }
    
    .price-unit {
      font-size: 22rpx;
      color: #666;
    }
  }
  
  .original-price {
    .original-text {
      font-size: 20rpx;
      color: #999;
      text-decoration: line-through;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  
  &.consult-btn {
    border: 2rpx solid #2e8b57;
    background-color: #fff;
    color: #2e8b57;
  }
  
  &.apply-btn {
    border: 2rpx solid #ff4757;
    background-color: #ff4757;
    color: #fff;
  }
  
  &:active {
    opacity: 0.8;
  }
}

.policy-rating {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding-top: 16rpx;
  border-top: 2rpx solid #f0f0f0;
}

.rating-stars {
  .star {
    font-size: 20rpx;
    color: #ddd;
    
    &.active {
      color: #ffa500;
    }
  }
}

.rating-score {
  font-size: 24rpx;
  color: #333;
  font-weight: 600;
}

.rating-count {
  font-size: 22rpx;
  color: #666;
}

.load-more {
  padding: 32rpx;
  text-align: center;
}

.load-more-btn {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #fff;
  font-size: 28rpx;
  color: #666;
  
  &:active {
    background-color: #f8f9fa;
  }
}

.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.filter-content {
  width: 100%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.filter-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.filter-close {
  font-size: 32rpx;
  color: #666;
  padding: 8rpx;
}

.filter-options {
  max-height: 60vh;
  overflow-y: auto;
}

.filter-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 2rpx solid #f8f9fa;
  
  &.active {
    background-color: #f0f8f0;
    
    .option-text {
      color: #2e8b57;
    }
  }
  
  .option-text {
    font-size: 28rpx;
    color: #333;
  }
  
  .option-check {
    font-size: 24rpx;
    color: #2e8b57;
    font-weight: 600;
  }
}

.filter-actions {
  display: flex;
  padding: 32rpx;
  gap: 24rpx;
  border-top: 2rpx solid #f0f0f0;
}

.filter-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 600;
  
  &.reset-btn {
    border: 2rpx solid #d9d9d9;
    background-color: #fff;
    color: #666;
  }
  
  &.confirm-btn {
    border: 2rpx solid #2e8b57;
    background-color: #2e8b57;
    color: #fff;
  }
  
  &:active {
    opacity: 0.8;
  }
}
</style>