<template>
  <view class="reviews-page">
    <view class="stats-section" v-if="stats.total_count > 0">
      <view class="stats-header">
        <view class="stats-main">
          <text class="stats-avg">{{ stats.avg_rating }}</text>
          <text class="stats-label">综合评分</text>
        </view>
        <view class="stats-detail">
          <view class="stats-row">
            <text class="stats-good">{{ stats.good_rate }}%</text>
            <text class="stats-good-label">好评率</text>
          </view>
          <view class="stats-row">
            <text class="stats-total">{{ stats.total_count }}</text>
            <text class="stats-total-label">评价数</text>
          </view>
        </view>
      </view>
      <view class="rating-bars">
        <view class="rating-bar" v-for="i in 5" :key="i">
          <text class="rating-label">{{ 6 - i }}星</text>
          <view class="rating-progress">
            <view 
              class="rating-fill" 
              :style="{ width: getRatingPercent(6 - i) + '%' }"
            ></view>
          </view>
          <text class="rating-count">{{ getRatingCount(6 - i) }}</text>
        </view>
      </view>
    </view>

    <view class="filter-section">
      <scroll-view scroll-x class="filter-scroll">
        <view class="filter-list">
          <view 
            class="filter-item" 
            :class="{ active: filterRating === 0 }"
            @click="setFilterRating(0)"
          >
            <text class="filter-text">全部({{ stats.total_count }})</text>
          </view>
          <view 
            class="filter-item" 
            :class="{ active: filterRating === 5 }"
            @click="setFilterRating(5)"
          >
            <text class="filter-text">好评({{ getRatingCount(5) }})</text>
          </view>
          <view 
            class="filter-item" 
            :class="{ active: filterRating === 4 }"
            @click="setFilterRating(4)"
          >
            <text class="filter-text">中评({{ getRatingCount(4) + getRatingCount(3) }})</text>
          </view>
          <view 
            class="filter-item" 
            :class="{ active: filterRating === 2 }"
            @click="setFilterRating(2)"
          >
            <text class="filter-text">差评({{ getRatingCount(2) + getRatingCount(1) }})</text>
          </view>
          <view 
            class="filter-item" 
            :class="{ active: hasImageFilter }"
            @click="toggleHasImage"
          >
            <text class="filter-text">有图</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="review-list">
      <view class="review-item" v-for="review in reviews" :key="review.id">
        <view class="review-header">
          <image 
            class="user-avatar" 
            :src="review.user_avatar.length > 0 ? review.user_avatar : defaultAvatar" 
            mode="aspectFill"
          />
          <view class="user-info">
            <text class="user-name">{{ review.user_name }}</text>
            <view class="rating-stars">
              <text 
                v-for="star in 5" 
                :key="star" 
                class="star"
                :class="{ filled: star <= review.rating }"
              >★</text>
            </view>
          </view>
          <text class="review-time">{{ formatTime(review.created_at) }}</text>
        </view>

        <view class="review-content">
          <text class="review-text">{{ review.content }}</text>
        </view>

        <view class="review-images" v-if="review.images.length > 0">
          <image 
            v-for="(img, idx) in review.images.slice(0, 3)" 
            :key="idx"
            class="review-image"
            :src="img"
            mode="aspectFill"
            @click="previewImage(review.images, idx)"
          />
          <view class="more-images" v-if="review.images.length > 3">
            <text class="more-images-text">+{{ review.images.length - 3 }}</text>
          </view>
        </view>

        <view class="review-append" v-if="review.append_content">
          <text class="append-label">追评</text>
          <text class="append-text">{{ review.append_content }}</text>
          <text class="append-time">{{ formatTime(review.append_at) }}</text>
        </view>

        <view class="review-reply" v-if="review.reply">
          <text class="reply-label">商家回复：</text>
          <text class="reply-text">{{ review.reply }}</text>
        </view>

        <view class="review-footer">
          <view 
            class="like-btn" 
            :class="{ liked: review.is_liked }"
            @click="toggleLike(review)"
          >
            <text class="like-icon">{{ review.is_liked ? '❤' : '♡' }}</text>
            <text class="like-count">{{ review.like_count != null ? review.like_count : 0 }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="empty-state" v-if="!loading && reviews.length === 0">
      <text class="empty-text">暂无评价</text>
    </view>

    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <view class="load-more" v-if="!loading && hasMore && reviews.length > 0" @click="loadMore">
      <text class="load-more-text">加载更多</text>
    </view>

    <view class="no-more" v-if="!loading && !hasMore && reviews.length > 0">
      <text class="no-more-text">没有更多了</text>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { supabaseService } from '@/utils/supabaseService.uts'

type ReviewItem = {
  id: string
  user_id: string
  user_name: string
  user_avatar: string
  rating: number
  content: string
  images: string[]
  is_anonymous: boolean
  like_count: number
  is_liked: boolean
  append_content: string | null
  append_at: string | null
  reply: string | null
  created_at: string
}

type StatsType = {
  total_count: number
  avg_rating: number
  good_rate: number
  rating_distribution: Map<string, number>
}

const productId = ref<string>('')
const reviews = ref<ReviewItem[]>([])
const stats = ref<StatsType>({
  total_count: 0,
  avg_rating: 0,
  good_rate: 0,
  rating_distribution: new Map<string, number>()
})
const loading = ref<boolean>(true)
const hasMore = ref<boolean>(true)
const page = ref<number>(1)
const pageSize = 10
const filterRating = ref<number>(0)
const hasImageFilter = ref<boolean>(false)

const defaultAvatar: string = '/static/images/default.png'

const getRatingCount = (rating: number): number => {
  return stats.value.rating_distribution.get(rating.toString()) ?? 0
}

const getRatingPercent = (rating: number): number => {
  if (stats.value.total_count === 0) return 0
  const count = getRatingCount(rating)
  return Math.round((count / stats.value.total_count) * 100)
}

const loadStats = async (): Promise<void> => {
  try {
    const result = await supabaseService.getReviewStats(productId.value)
    const distMap = new Map<string, number>()
    
    const dist = result.get('rating_distribution')
    if (dist != null && dist instanceof UTSJSONObject) {
      for (let i = 1; i <= 5; i++) {
        distMap.set(i.toString(), dist.getNumber(i.toString()) ?? 0)
      }
    }
    
    const statsData: StatsType = {
      total_count: result.getNumber('total_count') ?? 0,
      avg_rating: result.getNumber('avg_rating') ?? 0,
      good_rate: result.getNumber('good_rate') ?? 0,
      rating_distribution: distMap
    }
    stats.value = statsData
  } catch (e) {
    console.error('加载统计失败:', e)
  }
}

const loadReviews = async (pageNum: number): Promise<void> => {
  loading.value = true
  
  try {
    const result = await supabaseService.getProductReviews(
      productId.value,
      pageNum,
      pageSize,
      filterRating.value,
      hasImageFilter.value
    )
    
    const total = result.getNumber('total') ?? 0
    const data = result.get('data')
    const reviewList: ReviewItem[] = []
    
    if (data != null && Array.isArray(data)) {
      const rawList = data as any[]
      for (let i = 0; i < rawList.length; i++) {
        const item = rawList[i]
        let reviewObj: UTSJSONObject
        if (item instanceof UTSJSONObject) {
          reviewObj = item
        } else {
          reviewObj = JSON.parse(JSON.stringify(item)) as UTSJSONObject
        }
        
        let images: string[] = []
        const imagesRaw = reviewObj.get('images')
        if (imagesRaw != null && typeof imagesRaw === 'string') {
          try {
            const parsed = JSON.parse(imagesRaw as string)
            if (Array.isArray(parsed)) {
              images = parsed as string[]
            }
          } catch (e) {
            console.error('解析图片失败:', e)
          }
        }
        
        const review: ReviewItem = {
          id: reviewObj.getString('id') ?? '',
          user_id: reviewObj.getString('user_id') ?? '',
          user_name: reviewObj.getString('user_name') ?? '匿名用户',
          user_avatar: reviewObj.getString('user_avatar') ?? '',
          rating: reviewObj.getNumber('rating') ?? 5,
          content: reviewObj.getString('content') ?? '',
          images: images,
          is_anonymous: reviewObj.getBoolean('is_anonymous') ?? false,
          like_count: reviewObj.getNumber('like_count') ?? 0,
          is_liked: reviewObj.getBoolean('is_liked') ?? false,
          append_content: reviewObj.getString('append_content'),
          append_at: reviewObj.getString('append_at'),
          reply: reviewObj.getString('reply'),
          created_at: reviewObj.getString('created_at') ?? ''
        }
        reviewList.push(review)
      }
    }
    
    if (pageNum === 1) {
      reviews.value = reviewList
    } else {
      reviews.value = [...reviews.value, ...reviewList]
    }
    
    hasMore.value = reviews.value.length < total
    page.value = pageNum
  } catch (e) {
    console.error('加载评价失败:', e)
  } finally {
    loading.value = false
  }
}

const loadMore = (): void => {
  if (!loading.value && hasMore.value) {
    loadReviews(page.value + 1)
  }
}

const setFilterRating = (rating: number): void => {
  filterRating.value = rating
  hasImageFilter.value = false
  page.value = 1
  loadReviews(1)
}

const toggleHasImage = (): void => {
  hasImageFilter.value = !hasImageFilter.value
  filterRating.value = 0
  page.value = 1
  loadReviews(1)
}

const toggleLike = async (review: ReviewItem): Promise<void> => {
  try {
    const result = await supabaseService.toggleReviewLike(review.id)
    if (result.getBoolean('success') === true) {
      review.is_liked = result.getBoolean('is_liked') ?? false
      review.like_count = result.getNumber('like_count') ?? 0
    }
  } catch (e) {
    console.error('点赞失败:', e)
  }
}

const previewImage = (images: string[], index: number): void => {
  uni.previewImage({
    urls: images,
    current: index
  })
}

const formatTime = (timeStr: string | null): string => {
  if (timeStr == null || timeStr === '') return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (24 * 60 * 60 * 1000))
  
  if (days === 0) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    if (hours === 0) {
      const minutes = Math.floor(diff / (60 * 1000))
      return minutes <= 1 ? '刚刚' : `${minutes}分钟前`
    }
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    const y = date.getFullYear()
    const m = (date.getMonth() + 1).toString().padStart(2, '0')
    const d = date.getDate().toString().padStart(2, '0')
    return `${y}-${m}-${d}`
  }
}

onLoad((options) => {
  if (options != null) {
    const optionsObj = options as UTSJSONObject
    const idVal = optionsObj.getString('product_id') ?? ''
    if (idVal != '') {
      productId.value = idVal
      loadStats()
      loadReviews(1)
    }
  }
})
</script>

<style>
.reviews-page {
  flex: 1;
  background-color: #f5f5f5;
}

.stats-section {
  background-color: white;
  padding: 16px;
  margin-bottom: 8px;
}

.stats-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stats-main {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stats-avg {
  font-size: 36px;
  font-weight: bold;
  color: #ff6b35;
}

.stats-label {
  font-size: 12px;
  color: #999;
}

.stats-detail {
  display: flex;
  flex-direction: row;
}

.stats-row {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 24px;
}

.stats-good {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b35;
}

.stats-good-label {
  font-size: 12px;
  color: #999;
}

.stats-total {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.stats-total-label {
  font-size: 12px;
  color: #999;
}

.rating-bars {
  display: flex;
  flex-direction: column;
}

.rating-bar {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 4px;
}

.rating-label {
  font-size: 12px;
  color: #999;
  width: 30px;
}

.rating-progress {
  flex: 1;
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px;
  margin: 0 8px;
  overflow: hidden;
}

.rating-fill {
  height: 100%;
  background-color: #ff6b35;
  border-radius: 3px;
}

.rating-count {
  font-size: 12px;
  color: #999;
  width: 30px;
  text-align: right;
}

.filter-section {
  background-color: white;
  margin-bottom: 8px;
}

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

.filter-list {
  display: flex;
  flex-direction: row;
  padding: 12px 16px;
}

.filter-item {
  padding: 6px 16px;
  background-color: #f5f5f5;
  border-radius: 16px;
  margin-right: 12px;
}

.filter-item.active {
  background-color: #fff5f0;
}

.filter-text {
  font-size: 13px;
  color: #666;
}

.filter-item.active .filter-text {
  color: #ff6b35;
}

.review-list {
  background-color: white;
}

.review-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.review-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 18px;
}

.user-info {
  flex: 1;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 14px;
  color: #333;
}

.rating-stars {
  display: flex;
  flex-direction: row;
  margin-top: 2px;
}

.star {
  font-size: 12px;
  color: #ddd;
}

.star.filled {
  color: #ff6b35;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  margin-bottom: 12px;
}

.review-text {
  font-size: 14px;
  color: #333;
  line-height: 20px;
}

.review-images {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.review-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.more-images {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-images-text {
  font-size: 14px;
  color: white;
}

.review-append {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 12px;
}

.append-label {
  font-size: 12px;
  color: #ff6b35;
  margin-right: 8px;
}

.append-text {
  font-size: 14px;
  color: #666;
}

.append-time {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  display: flex;
}

.review-reply {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 12px;
}

.reply-label {
  font-size: 12px;
  color: #999;
}

.reply-text {
  font-size: 14px;
  color: #666;
}

.review-footer {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.like-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 4px 12px;
}

.like-btn.liked .like-icon {
  color: #ff6b35;
}

.like-icon {
  font-size: 16px;
  color: #999;
  margin-right: 4px;
}

.like-count {
  font-size: 12px;
  color: #999;
}

.empty-state {
  padding: 60px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

.loading-state {
  padding: 30px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.load-more {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.load-more-text {
  font-size: 14px;
  color: #666;
}

.no-more {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.no-more-text {
  font-size: 12px;
  color: #999;
}
</style>
