<template>
  <view class="shop-detail-page">
    <!-- 店铺头部信息 -->
    <view class="shop-header">
      <image :src="merchant.shop_banner || '/static/default-banner.png'" class="shop-banner" mode="aspectFill" />
      <view class="shop-info-card">
        <image :src="merchant.shop_logo || '/static/default-shop.png'" class="shop-logo" />
        <view class="shop-basic-info">
          <text class="shop-name">{{ merchant.shop_name }}</text>
          <view class="shop-stats">
            <text class="stat-item">⭐ {{ merchant.rating.toFixed(1) }}</text>
            <text class="stat-item">销量 {{ merchant.total_sales }}</text>
          </view>
        </view>
        <button class="follow-btn" @click="toggleFollow">{{ isFollowed ? '已关注' : '+ 关注' }}</button>
      </view>
      <text class="shop-desc">{{ merchant.shop_description || '这家店很懒，什么都没写~' }}</text>
    </view>

    <!-- 商品列表 -->
    <view class="product-section">
      <view class="section-title">全部商品</view>
      <view class="product-grid">
        <view v-for="product in products" :key="product.id" class="product-item" @click="goToProduct(product.id)">
          <image :src="product.images[0]" class="product-image" mode="aspectFill" />
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="price-row">
              <view class="price-left">
                <text class="product-price">¥{{ product.price }}</text>
                <text class="product-sales">已售 {{ product.sales }}</text>
              </view>
              <view class="cart-btn" @click.stop="addToCart(product)">
                <text class="cart-icon">🛒</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { MerchantType, ProductType } from '@/types/mall-types.uts'
import { supabaseService } from '@/utils/supabaseService.uts'

const merchant = ref<MerchantType>({
  id: '',
  user_id: '',
  shop_name: '',
  shop_logo: '',
  shop_banner: '',
  shop_description: '',
  contact_name: '',
  contact_phone: '',
  shop_status: 0,
  rating: 0,
  total_sales: 0,
  created_at: ''
} as MerchantType)

const products = ref<ProductType[]>([])
const isFollowed = ref(false)

onMounted(() => {
  const pages = getCurrentPages()
  const options = pages[pages.length - 1].options as any
  const merchantId = options['merchantId'] as string
  
  if (merchantId) {
    loadShopData(merchantId)
    loadShopProducts(merchantId)
  }
})

const loadShopData = async (id: string) => {
  const shop = await supabaseService.getShopByMerchantId(id)
  if (shop) {
    merchant.value = {
      id: shop.id,
      user_id: shop.merchant_id, // 映射关系
      shop_name: shop.shop_name,
      shop_logo: shop.shop_logo || '/static/default-shop.png',
      shop_banner: shop.shop_banner || '/static/default-banner.png',
      shop_description: shop.description || '',
      contact_name: shop.contact_name || '',
      contact_phone: shop.contact_phone || '',
      shop_status: 1, // 默认正常
      rating: shop.rating_avg || 5.0,
      total_sales: shop.total_sales || 0,
      created_at: shop.created_at || ''
    }
  }
}

const loadShopProducts = async (id: string) => {
  const res = await supabaseService.getProductsByMerchantId(id)
  if (res.data.length > 0) {
    products.value = res.data.map((item): ProductType => {
      // 解析图片数组
      let images: string[] = []
      if (item.image_urls) {
        try {
          const rawUrl = item.image_urls
          if (Array.isArray(rawUrl)) {
             // 已经是数组
             images = rawUrl as string[]
          } else if (typeof rawUrl === 'string') {
             if (rawUrl.startsWith('[')) {
                images = JSON.parse(rawUrl) as string[]
             } else {
                // 单个图片路径字符串
                images = [rawUrl]
             }
          }
        } catch(e) { 
            console.error('解析图片数组失败:', e)
            // 降级处理：尝试直接作为单个图片
            if (typeof item.image_urls === 'string') {
                images = [item.image_urls!]
            }
        }
      }
      if (images.length === 0 && item.image) {
        images.push(item.image!)
      }
      if (images.length === 0 && item.main_image_url) {
        images.push(item.main_image_url!)
      }
      
      return {
        id: item.id,
        merchant_id: item.merchant_id,
        category_id: item.category_id,
        name: item.name,
        description: item.description || '',
        images: images,
        price: item.price,
        original_price: item.original_price || item.price,
        stock: item.stock || 0,
        sales: item.sales || 0,
        status: 1,
        created_at: item.created_at || ''
      }
    })
  }
}

const toggleFollow = () => {
  // TODO: Implement actual follow logic with Supabase
  isFollowed.value = !isFollowed.value
  uni.showToast({
    title: isFollowed.value ? '关注成功' : '已取消关注',
    icon: 'none'
  })
}

const addToCart = async (product: ProductType) => {
  uni.showLoading({ title: '添加中...' })
  
  const success = await supabaseService.addToCart(product.id, 1)
  
  uni.hideLoading()
  
  if (success) {
    uni.showToast({
      title: '已添加到购物车',
      icon: 'success'
    })
  } else {
    uni.showToast({
      title: '添加失败，请重试',
      icon: 'none'
    })
  }
}

const goToProduct = (id: string) => {
  uni.navigateTo({
    url: `/pages/mall/consumer/product-detail?productId=${id}`
  })
}
</script>

<style>
.shop-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.shop-header {
  background-color: #fff;
  padding-bottom: 20px;
  margin-bottom: 10px;
}

.shop-banner {
  width: 100%;
  height: 150px;
  background-color: #eee;
}

.shop-info-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0 15px;
  margin-top: -30px; /* Logo 向上重叠 banner */
  position: relative;
  z-index: 1;
}

.shop-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  border: 2px solid #fff;
  background-color: #fff;
  margin-right: 12px;
}

.shop-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding-top: 30px; /* 给 logo 上浮留空间 */
}

.shop-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

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

.stat-item {
  font-size: 12px;
  color: #666;
  margin-right: 12px;
  background-color: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
}

.follow-btn {
  font-size: 14px;
  background-color: #ff4444;
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  margin-top: 30px; /* 对齐 */
  line-height: 1.5;
}

.shop-desc {
  display: block;
  font-size: 14px;
  color: #666;
  padding: 10px 15px 0;
  line-height: 1.4;
}

.product-section {
  padding: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-left: 8px;
  border-left: 4px solid #ff4444;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.product-item {
  width: calc(50% - 5px);
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

.product-image {
  width: 100%;
  height: 170px;
  background-color: #f5f5f5;
}

.product-info {
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
  line-height: 20px;
}

.price-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.price-left {
  display: flex;
  flex-direction: row;
  align-items: baseline;
}

.cart-btn {
  width: 24px;
  height: 24px;
  background-color: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-icon {
  font-size: 14px;
  color: white;
}

.product-price {
  font-size: 16px;
  color: #ff4444;
  font-weight: bold;
}

.product-sales {
  font-size: 12px;
  color: #999;
}
</style>