<template>
    <div class="product-container">
        <!-- 商品分类列表 -->
        <div>
            <van-sidebar v-model="activeKey">
                <van-sidebar-item v-for="category in categories" :key="category.id" :title="category.name"
                    @click="selectCategory(category.id)" />
            </van-sidebar>
        </div>
      
        <van-empty v-if="!loading && products.length === 0" description="该分类没有商品" class="empty-product"/>
        <!-- 商品列表 -->
        <div v-else>
            <van-list v-model="loading" :finished="finished" finished-text="没有更多商品了" @load="onLoad" class="product-list" >
                <van-card v-for="product in products" :key="product.id" :num="product.stock || 0" :price="product.price"
                    :desc="product.description" :title="product.name" :thumb="product.imgUrl" class="product-item">
                    <template #footer>
                        <van-button color="#7232dd" @click="handleAddToCart(product)" size="mini">立即加购</van-button>
                    </template>
                </van-card>
            </van-list>
        </div>
    </div>
</template>

<script>
import { listAllCategory } from '@/api/category'
import { listProductsByCategory } from '@/api/product'
import { addToCart, updateCartQuantity, removeFromCart, getCartList } from '@/api/cart'
import { Toast } from 'vant'

export default {
    name: 'ProductViewPage',
    data() {
        return {
            activeKey: 0,
            categories: [],
            products: [],
            currentCategory: null,
            loading: false,
            pageNum: 1,
            pageSize: 10,
            cartItems: [],
            finished: false,
            scrollTimer: null
        }
    },
    methods: {
        // 获取所有分类
        getCategories() {
            listAllCategory().then((response) => {
                if (response.data.code === 0) {
                    this.categories = response.data.data
                    if (this.categories.length > 0) {
                        this.selectCategory(this.categories[0].id);
                    }
                } else {
                    Toast.fail(response.data.message || '获取分类失败')
                }
            })
        },
        // 获取商品列表
        fetchProducts(categoryId, isLoadMore = false) {
            if (this.finished || !categoryId) return
            this.loading = true

            const data = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                categoryId: categoryId
            }

            listProductsByCategory(data).then((response) => {
                if (response.data.code === 0) {
                    const newProducts = response.data.data
                    if (isLoadMore) {
                        if (newProducts.length === 0) {
                            this.finished = true
                        } else {
                            this.products = [...this.products, ...newProducts]
                            this.pageNum++
                        }
                    } else {
                        this.products = newProducts
                        this.pageNum++
                    }
                } else {
                    Toast(response.data.message || '获取商品列表失败')
                }
            }).catch((error) => {
                console.log(error)
                Toast('获取商品列表失败')
            }).finally(() => {
                this.loading = false
            })
        },

        // 加载更多
        onLoad() {
            if (this.currentCategory === null) {
                this.loading = false
                this.finished = true
                return
            }
            const data = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                categoryId: this.currentCategory
            }

            listProductsByCategory(data).then((response) => {
                if (response.data.code === 0) {
                    const newProducts = response.data.data
                    if (newProducts.length === 0) {
                        this.finished = true
                    } else {
                        this.products.push(...newProducts)
                        this.pageNum++
                        this.loading = false
                    }
                } else {
                    Toast(response.data.message || '获取商品列表失败')
                }
            }).catch((error) => {
                console.log(error)
                Toast('获取商品列表失败')
            }).finally(() => {
                this.loading = false
            })
        },

        // 选择分类
        selectCategory(categoryId) {
            this.currentCategory = categoryId
            this.pageNum = 1
            this.products = []
            this.finished = false
            this.fetchProducts(categoryId)
        },

        // 添加到购物车
        handleAddToCart(product) {
            addToCart({
                productId: product.id,
                quantity: 1
            }).then((response) => {
                if (response.data.code === 0) {
                    Toast.success('添加成功')
                    this.fetchCartList()
                } else {
                    Toast(response.data.message || '添加失败')
                }
            }).catch((error) => {
                console.error('添加购物车失败:', error)
                Toast('添加失败')
            })
        },

        // 检查商品是否在购物车中
        isProductInCart(productId) {
            return this.cartItems.some(item => item.productId === productId)
        },

        // 更新购物车中商品的数量
        updateCartItemQuantity(productId, quantity) {
            updateCartQuantity({ productId, quantity }).then((response) => {
                if (response.data.code === 0) {
                    const cartItem = this.cartItems.find(item => item.productId === productId)
                    if (cartItem) {
                        cartItem.quantity = quantity
                    }
                } else {
                    Toast(response.data.message || '更新数量失败')
                }
            }).catch((error) => {
                console.error('更新购物车数量失败:', error)
                Toast('更新数量失败')
            })
        },

        // 从购物车中移除商品
        removeFromCart(productId) {
            removeFromCart(productId).then((response) => {
                if (response.data.code === 0) {
                    this.cartItems = this.cartItems.filter(item => item.productId !== productId)
                    Toast.success('移除成功')
                    this.fetchCartList()
                } else {
                    Toast(response.data.message || '移除失败')
                }
            }).catch((error) => {
                console.error('移除购物车失败:', error)
                Toast('移除失败')
            })
        },

        // 获取购物车列表
        fetchCartList() {
            getCartList().then((response) => {
                if (response.data.code === 0) {
                    this.cartItems = response.data.data
                    console.log('购物车数据:', this.cartItems)
                } else {
                    Toast(response.data.message || '获取购物车列表失败')
                }
            }).catch((error) => {
                console.log('获取购物车列表失败', error)
                Toast('获取购物车列表失败')
            })
        }
    },
    created() {
        this.getCategories()
    },
}
</script>

<style scoped>
.product-container {
    display: flex;
}

.product-list {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 1px;
    padding-bottom: 50px; 
}

.product-item {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    width: 100%;
}
.product-item .van-card {
    width: 100%;
}

.product-item:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.12);
    transform: translateY(-5px);
}

.empty-product {
    grid-column: 1 / -1;
    padding: 40px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>这个使用vue加vant的页面，为什么有些分类商品右边占满了，而有些分类商品右边有空白没有填充满