<template>
  <view class="product-detail">
    <!-- 商品图片轮播 -->
    <view class="product-images">
      <Swiper
        :list="product.images"
        :height="'750rpx'"
        :indicator-dots="true"
        :autoplay="false"
        :circular="true"
        @click="handleImageClick"
      />
      
      <!-- 收藏按钮 -->
      <view class="favorite-btn" @click="handleFavorite">
        <text class="favorite-icon" :class="{ active: isFavorite }">
          {{ isFavorite ? '❤️' : '🤍' }}
        </text>
      </view>
    </view>
    
    <!-- 商品基本信息 -->
    <Card class="product-info">
      <view class="price-section">
        <view class="current-price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ product.price }}</text>
          <text class="price-unit">/{{ product.unit }}</text>
        </view>
        <view class="original-price" v-if="product.originalPrice">
          <text class="original-text">原价：¥{{ product.originalPrice }}</text>
        </view>
      </view>
      
      <view class="product-title">
        {{ product.name }}
      </view>
      
      <view class="product-subtitle" v-if="product.subtitle">
        {{ product.subtitle }}
      </view>
      
      <view class="product-tags" v-if="product.tags && product.tags.length">
        <view
          class="tag-item"
          v-for="tag in product.tags"
          :key="tag"
        >
          {{ tag }}
        </view>
      </view>
      
      <view class="product-stats">
        <view class="stat-item">
          <text class="stat-label">销量</text>
          <text class="stat-value">{{ product.sales || 0 }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">库存</text>
          <text class="stat-value">{{ product.stock || 0 }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">评价</text>
          <text class="stat-value">{{ product.rating || 5.0 }}分</text>
        </view>
      </view>
    </Card>
    
    <!-- 规格选择 -->
    <Card class="spec-section" v-if="product.specs && product.specs.length">
      <view class="section-title">选择规格</view>
      <view class="spec-list">
        <view
          class="spec-group"
          v-for="spec in product.specs"
          :key="spec.name"
        >
          <view class="spec-name">{{ spec.name }}</view>
          <view class="spec-options">
            <view
              class="spec-option"
              :class="{ active: selectedSpecs[spec.name] === option.value }"
              v-for="option in spec.options"
              :key="option.value"
              @click="handleSpecSelect(spec.name, option)"
            >
              <text class="option-text">{{ option.label }}</text>
              <text class="option-price" v-if="option.price">
                +¥{{ option.price }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </Card>
    
    <!-- 商品详情 -->
    <Card class="detail-section">
      <Tabs
        :tabs="detailTabs"
        :activeIndex="activeDetailTab"
        @change="handleDetailTabChange"
      />
      
      <view class="detail-content">
        <!-- 商品介绍 -->
        <view class="detail-intro" v-if="activeDetailTab === 0">
          <view class="intro-item" v-if="product.origin">
            <text class="intro-label">产地：</text>
            <text class="intro-value">{{ product.origin }}</text>
          </view>
          <view class="intro-item" v-if="product.brand">
            <text class="intro-label">品牌：</text>
            <text class="intro-value">{{ product.brand }}</text>
          </view>
          <view class="intro-item" v-if="product.shelfLife">
            <text class="intro-label">保质期：</text>
            <text class="intro-value">{{ product.shelfLife }}</text>
          </view>
          <view class="intro-item" v-if="product.storage">
            <text class="intro-label">储存方式：</text>
            <text class="intro-value">{{ product.storage }}</text>
          </view>
          
          <view class="intro-description" v-if="product.description">
            <text class="description-title">商品描述</text>
            <text class="description-content">{{ product.description }}</text>
          </view>
          
          <!-- 详情图片 -->
          <view class="detail-images" v-if="product.detailImages">
            <image
              class="detail-image"
              v-for="(image, index) in product.detailImages"
              :key="index"
              :src="image"
              mode="widthFix"
              @click="handleDetailImageClick(index)"
            />
          </view>
        </view>
        
        <!-- 商品评价 -->
        <view class="detail-reviews" v-if="activeDetailTab === 1">
          <view class="reviews-summary">
            <view class="summary-rating">
              <text class="rating-score">{{ product.rating || 5.0 }}</text>
              <text class="rating-total">{{ product.reviewCount || 0 }}条评价</text>
            </view>
            <view class="rating-stars">
              <text
                class="star"
                :class="{ active: index < Math.floor(product.rating || 5) }"
                v-for="index in 5"
                :key="index"
              >
                ⭐
              </text>
            </view>
          </view>
          
          <view class="reviews-list">
            <view
              class="review-item"
              v-for="review in reviews"
              :key="review.id"
            >
              <view class="review-header">
                <view class="reviewer-info">
                  <image class="reviewer-avatar" :src="review.avatar" />
                  <text class="reviewer-name">{{ review.nickname }}</text>
                </view>
                <view class="review-rating">
                  <text
                    class="star"
                    :class="{ active: index < review.rating }"
                    v-for="index in 5"
                    :key="index"
                  >
                    ⭐
                  </text>
                </view>
              </view>
              
              <view class="review-content">
                {{ review.content }}
              </view>
              
              <view class="review-images" v-if="review.images">
                <image
                  class="review-image"
                  v-for="(image, index) in review.images"
                  :key="index"
                  :src="image"
                  mode="aspectFill"
                  @click="handleReviewImageClick(review.images, index)"
                />
              </view>
              
              <view class="review-time">
                {{ formatDate(review.createTime) }}
              </view>
            </view>
          </view>
          
          <view class="load-more-reviews" v-if="hasMoreReviews">
            <button class="load-more-btn" @click="loadMoreReviews">
              查看更多评价
            </button>
          </view>
        </view>
      </view>
    </Card>
    
    <!-- 推荐商品 -->
    <Card class="recommend-section" v-if="recommendProducts.length">
      <view class="section-title">推荐商品</view>
      <scroll-view class="recommend-list" scroll-x>
        <view
          class="recommend-item"
          v-for="item in recommendProducts"
          :key="item.id"
          @click="handleRecommendClick(item)"
        >
          <image class="recommend-image" :src="item.image" mode="aspectFill" />
          <view class="recommend-info">
            <text class="recommend-name">{{ item.name }}</text>
            <text class="recommend-price">¥{{ item.price }}</text>
          </view>
        </view>
      </scroll-view>
    </Card>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-left">
        <view class="action-item" @click="handleCustomerService">
          <text class="action-icon">💬</text>
          <text class="action-text">客服</text>
        </view>
        <view class="action-item" @click="handleCart">
          <text class="action-icon">🛒</text>
          <text class="action-text">购物车</text>
          <view class="cart-badge" v-if="cartCount > 0">
            {{ cartCount }}
          </view>
        </view>
      </view>
      
      <view class="action-right">
        <button class="action-btn cart-btn" @click="handleAddToCart">
          加入购物车
        </button>
        <button class="action-btn buy-btn" @click="handleBuyNow">
          立即购买
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import Swiper from '@/common/components/swiper/swiper.vue'
import Card from '@/common/components/card/card.vue'
import Tabs from '@/common/components/tabs/tabs.vue'
import { mallApi } from '@/common/api'
import { formatDate } from '@/common/utils/format'
import { useMallStore } from '@/common/store/modules/mall'

export default {
  name: 'ProductDetail',
  components: {
    Swiper,
    Card,
    Tabs
  },
  setup() {
    const mallStore = useMallStore()
    
    // 响应式数据
    const productId = ref('')
    const product = ref({})
    const selectedSpecs = reactive({})
    const activeDetailTab = ref(0)
    const reviews = ref([])
    const hasMoreReviews = ref(true)
    const recommendProducts = ref([])
    const isFavorite = ref(false)
    
    // 详情标签
    const detailTabs = [
      { title: '商品介绍', value: 'intro' },
      { title: '商品评价', value: 'reviews' }
    ]
    
    // 计算属性
    const cartCount = computed(() => mallStore.cartCount)
    
    // 方法
    const loadProductDetail = async () => {
      try {
        const response = await mallApi.getProductDetail(productId.value)
        product.value = response.data
        
        // 初始化规格选择
        if (product.value.specs) {
          product.value.specs.forEach(spec => {
            if (spec.options && spec.options.length > 0) {
              selectedSpecs[spec.name] = spec.options[0].value
            }
          })
        }
        
        // 检查收藏状态
        checkFavoriteStatus()
        
      } catch (error) {
        console.error('加载商品详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      }
    }
    
    const loadReviews = async () => {
      try {
        const response = await mallApi.getProductReviews(productId.value, {
          page: 1,
          pageSize: 10
        })
        reviews.value = response.data.list
        hasMoreReviews.value = response.data.hasMore
      } catch (error) {
        console.error('加载评价失败:', error)
      }
    }
    
    const loadRecommendProducts = async () => {
      try {
        const response = await mallApi.getRecommendProducts(productId.value)
        recommendProducts.value = response.data
      } catch (error) {
        console.error('加载推荐商品失败:', error)
      }
    }
    
    const checkFavoriteStatus = async () => {
      try {
        const response = await mallApi.checkFavorite(productId.value)
        isFavorite.value = response.data.isFavorite
      } catch (error) {
        console.error('检查收藏状态失败:', error)
      }
    }
    
    const handleImageClick = (e) => {
      const { index } = e
      uni.previewImage({
        urls: product.value.images,
        current: index
      })
    }
    
    const handleFavorite = async () => {
      try {
        if (isFavorite.value) {
          await mallApi.removeFavorite(productId.value)
          isFavorite.value = false
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        } else {
          await mallApi.addFavorite(productId.value)
          isFavorite.value = true
          uni.showToast({
            title: '收藏成功',
            icon: 'success'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'error'
        })
      }
    }
    
    const handleSpecSelect = (specName, option) => {
      selectedSpecs[specName] = option.value
    }
    
    const handleDetailTabChange = (index) => {
      activeDetailTab.value = index
      if (index === 1 && reviews.value.length === 0) {
        loadReviews()
      }
    }
    
    const handleDetailImageClick = (index) => {
      uni.previewImage({
        urls: product.value.detailImages,
        current: index
      })
    }
    
    const handleReviewImageClick = (images, index) => {
      uni.previewImage({
        urls: images,
        current: index
      })
    }
    
    const loadMoreReviews = async () => {
      // 加载更多评价逻辑
    }
    
    const handleRecommendClick = (item) => {
      uni.navigateTo({
        url: `/pages/product/detail?id=${item.id}`
      })
    }
    
    const handleCustomerService = () => {
      uni.showToast({
        title: '客服功能开发中',
        icon: 'none'
      })
    }
    
    const handleCart = () => {
      uni.switchTab({
        url: '/pages/cart/cart'
      })
    }
    
    const handleAddToCart = async () => {
      try {
        await mallStore.addToCart({
          productId: productId.value,
          specs: selectedSpecs,
          quantity: 1
        })
        
        uni.showToast({
          title: '已加入购物车',
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: '加入购物车失败',
          icon: 'error'
        })
      }
    }
    
    const handleBuyNow = () => {
      // 立即购买逻辑
      uni.navigateTo({
        url: `/pages/order/confirm?productId=${productId.value}&specs=${JSON.stringify(selectedSpecs)}&quantity=1`
      })
    }
    
    // 生命周期
    onMounted(() => {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      productId.value = currentPage.options.id
      
      if (productId.value) {
        loadProductDetail()
        loadRecommendProducts()
      }
    })
    
    return {
      product,
      selectedSpecs,
      activeDetailTab,
      detailTabs,
      reviews,
      hasMoreReviews,
      recommendProducts,
      isFavorite,
      cartCount,
      handleImageClick,
      handleFavorite,
      handleSpecSelect,
      handleDetailTabChange,
      handleDetailImageClick,
      handleReviewImageClick,
      loadMoreReviews,
      handleRecommendClick,
      handleCustomerService,
      handleCart,
      handleAddToCart,
      handleBuyNow,
      formatDate
    }
  }
}
</script>

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

.product-images {
  position: relative;
}

.favorite-btn {
  position: absolute;
  top: 32rpx;
  right: 32rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  
  .favorite-icon {
    font-size: 32rpx;
    
    &.active {
      animation: heartbeat 0.6s ease-in-out;
    }
  }
}

@keyframes heartbeat {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.product-info {
  margin: 16rpx 32rpx;
}

.price-section {
  margin-bottom: 24rpx;
}

.current-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
  
  .price-symbol {
    font-size: 28rpx;
    color: #ff4757;
    font-weight: 600;
  }
  
  .price-value {
    font-size: 48rpx;
    color: #ff4757;
    font-weight: 600;
    margin: 0 8rpx;
  }
  
  .price-unit {
    font-size: 24rpx;
    color: #666;
  }
}

.original-price {
  .original-text {
    font-size: 24rpx;
    color: #999;
    text-decoration: line-through;
  }
}

.product-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 12rpx;
}

.product-subtitle {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
  margin-bottom: 16rpx;
}

.product-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 24rpx;
}

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

.product-stats {
  display: flex;
  justify-content: space-between;
  padding: 24rpx 0;
  border-top: 2rpx solid #f0f0f0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  
  .stat-label {
    font-size: 24rpx;
    color: #666;
  }
  
  .stat-value {
    font-size: 28rpx;
    color: #333;
    font-weight: 600;
  }
}

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

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.spec-group {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.spec-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.spec-option {
  padding: 16rpx 24rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #fff;
  
  &.active {
    border-color: #2e8b57;
    background-color: #f0f8f0;
    
    .option-text {
      color: #2e8b57;
    }
  }
  
  .option-text {
    font-size: 28rpx;
    color: #333;
  }
  
  .option-price {
    font-size: 24rpx;
    color: #ff4757;
    margin-left: 8rpx;
  }
}

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

.detail-content {
  margin-top: 24rpx;
}

.detail-intro {
  .intro-item {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 2rpx solid #f0f0f0;
    
    .intro-label {
      font-size: 28rpx;
      color: #666;
      width: 160rpx;
    }
    
    .intro-value {
      font-size: 28rpx;
      color: #333;
      flex: 1;
    }
  }
  
  .intro-description {
    margin-top: 32rpx;
    
    .description-title {
      display: block;
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 16rpx;
    }
    
    .description-content {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
  
  .detail-images {
    margin-top: 32rpx;
    
    .detail-image {
      width: 100%;
      display: block;
      margin-bottom: 16rpx;
      border-radius: 8rpx;
    }
  }
}

.detail-reviews {
  .reviews-summary {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 0;
    border-bottom: 2rpx solid #f0f0f0;
    margin-bottom: 24rpx;
    
    .summary-rating {
      display: flex;
      align-items: baseline;
      gap: 16rpx;
      
      .rating-score {
        font-size: 48rpx;
        font-weight: 600;
        color: #ff4757;
      }
      
      .rating-total {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .rating-stars {
      .star {
        font-size: 24rpx;
        color: #ddd;
        
        &.active {
          color: #ffa500;
        }
      }
    }
  }
  
  .reviews-list {
    .review-item {
      padding: 24rpx 0;
      border-bottom: 2rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
    }
    
    .review-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16rpx;
      
      .reviewer-info {
        display: flex;
        align-items: center;
        gap: 16rpx;
        
        .reviewer-avatar {
          width: 64rpx;
          height: 64rpx;
          border-radius: 50%;
        }
        
        .reviewer-name {
          font-size: 28rpx;
          color: #333;
        }
      }
      
      .review-rating {
        .star {
          font-size: 20rpx;
          color: #ddd;
          
          &.active {
            color: #ffa500;
          }
        }
      }
    }
    
    .review-content {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 16rpx;
    }
    
    .review-images {
      display: flex;
      gap: 12rpx;
      margin-bottom: 16rpx;
      
      .review-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
      }
    }
    
    .review-time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .load-more-reviews {
    text-align: center;
    margin-top: 32rpx;
    
    .load-more-btn {
      padding: 16rpx 32rpx;
      border: 2rpx solid #e5e5e5;
      border-radius: 8rpx;
      background-color: #fff;
      font-size: 28rpx;
      color: #666;
    }
  }
}

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

.recommend-list {
  display: flex;
  gap: 16rpx;
  padding: 16rpx 0;
}

.recommend-item {
  flex-shrink: 0;
  width: 200rpx;
  
  .recommend-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 8rpx;
    margin-bottom: 12rpx;
  }
  
  .recommend-info {
    .recommend-name {
      display: block;
      font-size: 24rpx;
      color: #333;
      margin-bottom: 8rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .recommend-price {
      font-size: 28rpx;
      color: #ff4757;
      font-weight: 600;
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 16rpx 32rpx;
  background-color: #fff;
  border-top: 2rpx solid #f0f0f0;
  z-index: 100;
}

.action-left {
  display: flex;
  gap: 32rpx;
  margin-right: 32rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  position: relative;
  
  .action-icon {
    font-size: 32rpx;
  }
  
  .action-text {
    font-size: 20rpx;
    color: #666;
  }
  
  .cart-badge {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    min-width: 32rpx;
    height: 32rpx;
    background-color: #ff4757;
    color: #fff;
    font-size: 20rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8rpx;
  }
}

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

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 600;
  
  &.cart-btn {
    border: 2rpx solid #2e8b57;
    background-color: #fff;
    color: #2e8b57;
  }
  
  &.buy-btn {
    border: 2rpx solid #ff4757;
    background-color: #ff4757;
    color: #fff;
  }
  
  &:active {
    opacity: 0.8;
  }
}
</style>