<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'

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 = (id: string) => {
  // 模拟加载店铺数据
  merchant.value = {
    id: id,
    user_id: 'user_001',
    shop_name: '优质好店',
    shop_logo: '/static/shop-logo.png',
    shop_banner: '/static/shop-banner.png',
    shop_description: '专注品质生活，为您提供最优质的商品和服务。',
    contact_name: '店主小王',
    contact_phone: '13800138000',
    shop_status: 1,
    rating: 4.8,
    total_sales: 15680,
    created_at: '2023-06-01'
  }
}

const loadShopProducts = (id: string) => {
  // 模拟加载店铺商品列表
  products.value = [
    {
      id: 'prod_001',
      merchant_id: id,
      category_id: 'cat_001',
      name: '精选好物商品 A',
      description: '商品描述 A',
      images: ['/static/product1.jpg'],
      price: 199.99,
      original_price: 299.99,
      stock: 100,
      sales: 1256,
      status: 1,
      created_at: '2024-01-15'
    },
    {
      id: 'prod_002',
      merchant_id: id,
      category_id: 'cat_001',
      name: '精选好物商品 B',
      description: '商品描述 B',
      images: ['/static/product2.jpg'],
      price: 299.00,
      original_price: 399.00,
      stock: 50,
      sales: 856,
      status: 1,
      created_at: '2024-01-16'
    },
    {
      id: 'prod_003',
      merchant_id: id,
      category_id: 'cat_002',
      name: '精选好物商品 C',
      description: '商品描述 C',
      images: ['/static/product3.jpg'],
      price: 99.00,
      original_price: 129.00,
      stock: 200,
      sales: 3256,
      status: 1,
      created_at: '2024-01-17'
    }
  ]
}

const toggleFollow = () => {
  isFollowed.value = !isFollowed.value
  uni.showToast({
    title: isFollowed.value ? '关注成功' : '已取消关注',
    icon: 'none'
  })
}

const addToCart = (product: ProductType) => {
  // 获取现有购物车数据
  const cartData = uni.getStorageSync('cart')
  let cartItems: any[] = []
  
  if (cartData) {
    try {
      cartItems = JSON.parse(cartData as string) as any[]
    } catch (e) {
      console.error('解析购物车数据失败', e)
    }
  }
  
  // 检查商品是否已存在
  const existingItem = cartItems.find((item: any) => item.productId === product.id)
  
  if (existingItem) {
    existingItem.quantity++
  } else {
    // 添加新商品
    cartItems.push({
      id: product.id, // 简单使用产品ID作为购物车ID，实际可能有规格
      productId: product.id,
      shopId: merchant.value.id,
      shopName: merchant.value.shop_name,
      name: product.name,
      price: product.price,
      image: product.images[0],
      spec: '默认规格',
      quantity: 1,
      selected: true
    })
  }
  
  // 保存回存储
  uni.setStorageSync('cart', JSON.stringify(cartItems))
  
  uni.showToast({
    title: '已添加到购物车',
    icon: 'success'
  })
}

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>