<script setup lang="ts">
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { showConfirmDialog, showDialog, showSuccessToast } from 'vant';
import { debounce } from 'lodash-es';
import {
    getGoodsList,
    deleteGoods,
    type ShopGoodsDTO,
    type SearchShopGoodsQuery
} from '@/common/apis/manage/goods';

// 商品列表数据
const goodsList = ref<ShopGoodsDTO[]>([]);
const loading = ref(false);
const finished = ref(false);

// 搜索参数
const searchParams = reactive<SearchShopGoodsQuery>({
    pageNum: 1,
    pageSize: 10,
    goodsName: '',
    status: undefined
});

// 路由
const router = useRouter();

// 获取商品列表
const fetchGoodsList = async () => {
    try {
        searchParams.pageNum = 1;
        const res = await getGoodsList(searchParams);
        goodsList.value = res.data.rows;
    } catch (e) {
        showDialog({ message: '加载失败，请重试' });
    }
};

// 防抖搜索
const debouncedFetchGoodsList = debounce(fetchGoodsList, 500);

// 监听搜索条件变化
watch(() => searchParams.goodsName, debouncedFetchGoodsList);

// 组件卸载时取消防抖
onUnmounted(() => {
    debouncedFetchGoodsList.cancel();
});

// 加载数据
const onLoad = async () => {
    try {
        const res = await getGoodsList(searchParams);
        const rows = res.data.rows.filter(row => goodsList.value.findIndex(g => g.goodsId === row.goodsId) === -1);
        goodsList.value.push(...rows);
        loading.value = false;

        if (goodsList.value.length >= res.data.total) {
            finished.value = true;
        } else {
            if (searchParams.pageNum) {
                searchParams.pageNum++;
            } else {
                searchParams.pageNum = 1;
            }
        }
    } catch (error) {
        console.error('获取商品列表失败', error);
        finished.value = true;
    }
};

// 删除商品
const handleDelete = async (ids: number[]) => {
    await showConfirmDialog({ message: '确认删除选中商品？' });
    await deleteGoods(ids);
    showSuccessToast('删除成功');
    await fetchGoodsList();
};


// 跳转到新增/编辑页面
const navigateToEdit = (goods?: ShopGoodsDTO) => {
    if (goods?.goodsId) {
        router.push(`/manage/goods/edit/${goods.goodsId}`);
    } else {
        router.push('/manage/goods/add');
    }
};

// 跳转到详情页面
const navigateToDetail = (goods: ShopGoodsDTO) => {
    if (goods?.goodsId) {
        router.push(`/manage/goods/detail/${goods.goodsId}`);
    }
};

onMounted(fetchGoodsList);
</script>

<template>
    <div class="goods-manage">
        <!-- 搜索栏和操作按钮 -->
        <div class="search-action-bar">
            <van-search v-model="searchParams.goodsName" placeholder="输入商品名称搜索" />
            <van-button type="primary" @click="navigateToEdit">添加商品</van-button>
        </div>

        <!-- 商品表格 -->
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <div class="goods-grid">
                <div v-for="item in goodsList" :key="item.goodsId" class="goods-card" @click="navigateToDetail(item)" style="cursor: pointer;">
                    <div class="goods-image-container">
                        <van-image :src="item.coverImg" class="goods-image">
                            <div v-if="item.stock === 0" class="sold-out-overlay">
                                <span class="sold-out-text">已售罄</span>
                            </div>
                            <template #error>
                                <div class="custom-error">
                                    图片加载失败
                                </div>
                            </template>
                        </van-image>
                    </div>
                    <div class="goods-info">
                        <div class="goods-name van-ellipsis">{{ item.goodsName }}</div>
                        <div class="goods-price">¥{{ item.price?.toFixed(2) }}</div>
                        <div class="goods-footer">
                            <span v-if="item.stock! > 0" class="stock-count">库存: {{ item.stock }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </van-list>

    </div>
</template>

<style scoped>
.goods-manage {
    padding: 12px;
    background-color: #f7f8fa;
    min-height: 100vh;
}

.search-action-bar {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    background: white;
    padding: 8px 12px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.search-action-bar .van-search {
    flex: 1;
    background: transparent;
    padding: 0;
}

.search-action-bar .van-search .van-search__content {
    border-radius: 8px;
    background-color: #f7f8fa;
}

.goods-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
    margin: 0;
}

.goods-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    display: flex;
    flex-direction: column;
}

.goods-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.goods-image-container {
    position: relative;
    width: 100%;
    padding-top: 100%; /* 1:1 正方形比例 */
    background-color: #f7f8fa;
}

.goods-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.goods-image .van-image__img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.goods-info {
    padding: 12px;
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.goods-name {
    font-size: 14px;
    color: #333;
    line-height: 1.4;
    font-weight: 500;
    margin: 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    min-height: 40px;
}

.goods-price {
    font-size: 18px;
    color: #ff4444;
    font-weight: 700;
    margin: 4px 0;
}

.goods-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: auto;
}

.goods-actions {
    display: flex;
    gap: 4px;
}

.stock-count {
    font-size: 12px;
    color: #969799;
    background-color: #f7f8fa;
    padding: 2px 8px;
    border-radius: 10px;
    font-weight: 400;
}

.sold-out-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
}

.sold-out-text {
    color: #ff4444;
    font-size: 14px;
    font-weight: 600;
    background: rgba(255, 255, 255, 0.9);
    padding: 6px 12px;
    border-radius: 20px;
    border: 2px solid #ff4444;
    transform: rotate(-5deg);
    box-shadow: 0 2px 8px rgba(255, 68, 68, 0.2);
}

.custom-error {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #969799;
    font-size: 12px;
    background-color: #f7f8fa;
}

</style>