<template>
    <div class="search-container">
        <!-- 搜索结果标题区 -->
        <div class="search-header">
            <div class="search-title">
                <h1>{{ pageTitle }}</h1>
                <div class="search-info" v-if="searchKeyword || currentType">
                    <span class="search-keyword" v-if="searchKeyword">"{{ searchKeyword }}"</span>
                    <span class="search-count" v-if="!loading">共找到 {{ total }} 个结果</span>
                </div>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- 搜索内容区 -->
            <div class="search-content">
                <!-- 搜索框 -->
                <div class="search-box" v-if="!currentType">
                    <el-input 
                        v-model="localSearchKeyword" 
                        placeholder="请输入书名或作者名" 
                        class="search-input"
                        @keyup.enter="handleSearch"
                        clearable
                    >
                        <template #append>
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                搜索
                            </el-button>
                        </template>
                    </el-input>
                </div>

                <!-- 分类筛选 -->
                <div class="filter-section">
                    <div class="filter-item">
                        <span class="filter-label">分类：</span>
                        <div class="filter-options">
                            <el-button 
                                :type="selectedCategory === '' ? 'primary' : ''" 
                                :plain="selectedCategory !== ''"
                                size="small"
                                @click="handleCategoryChange('')"
                            >
                                全部
                            </el-button>
                            <el-button 
                                v-for="category in categories" 
                                :key="category.id"
                                :type="selectedCategory === category.id ? 'primary' : ''" 
                                :plain="selectedCategory !== category.id"
                                size="small"
                                @click="handleCategoryChange(category.id)"
                            >
                                {{ category.title }}
                            </el-button>
                        </div>
                    </div>
                </div>

                <!-- 加载状态 -->
                <div v-if="loading" class="loading-container">
                    <el-skeleton :rows="8" animated />
                </div>
                
                <!-- 搜索结果列表 -->
                <div v-else-if="books.length > 0" class="book-list-container">
                    <div v-for="(book, index) in books" :key="index" class="book-item">
                        <book-card :book="book" />
                    </div>
                </div>

                <!-- 空状态 -->
                <div v-else class="empty-state">
                    <div class="empty-icon">
                        <svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <circle cx="32" cy="32" r="16" stroke="#E5E5E5" stroke-width="2" fill="none"/>
                            <path d="M44 44L56 56" stroke="#E5E5E5" stroke-width="2" stroke-linecap="round"/>
                            <circle cx="32" cy="32" r="8" fill="#F5F5F5"/>
                        </svg>
                    </div>
                    <p class="empty-title">{{ searchKeyword ? '未找到相关书籍' : '请输入关键词搜索' }}</p>
                    <p class="empty-desc">{{ searchKeyword ? '换个关键词试试看' : '输入书名或作者名来搜索您感兴趣的书籍' }}</p>
                </div>

                <!-- 分页 -->
                <div v-if="!loading && books.length > 0" class="pagination-container">
                    <el-pagination 
                        v-model:current-page="currentPage" 
                        background
                        :page-size="pageSize" 
                        :total="total"
                        layout="prev, pager, next" 
                        @current-change="handlePageChange" 
                    />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { homeApi } from '@/api/modules.js';
import BookCard from '@/components/common/BookCard.vue';

export default {
    name: 'SearchView',
    components: {
        BookCard
    },
    setup() {
        const route = useRoute();
        const router = useRouter();
        
        // 搜索关键词
        const searchKeyword = ref('');
        const localSearchKeyword = ref('');
        
        // 页面类型和标题
        const currentType = ref('');
        const pageTitle = computed(() => {
            if (currentType.value === 'recommend') return '热门推荐';
            if (currentType.value === 'latest') return '最新更新';
            return searchKeyword.value ? '搜索结果' : '搜索书籍';
        });
        
        // 分类相关
        const categories = ref([]);
        const selectedCategory = ref('');
        
        // 分页相关
        const currentPage = ref(1);
        const pageSize = ref(20);
        const total = ref(0);
        const loading = ref(false);

        // 响应式数据
        const books = ref([]);

        // 获取分类列表
        const fetchCategories = async () => {
            try {
                const response = await homeApi.getCategoryList();
                if (response.success && response.result) {
                    categories.value = response.result;
                }
            } catch (error) {
                console.error('获取分类列表失败:', error);
            }
        };

        // 获取书籍列表
        const fetchBooks = async () => {
            loading.value = true;
            try {
                let response;
                const params = {
                    pageNo: currentPage.value,
                    pageSize: pageSize.value
                };

                // 添加分类参数
                if (selectedCategory.value) {
                    params.shopClass = selectedCategory.value;
                }

                // 根据不同类型调用不同API
                if (currentType.value === 'recommend') {
                    // 热门推荐
                    response = await homeApi.getRecommendList(params);
                } else if (currentType.value === 'latest') {
                    // 最新更新
                    response = await homeApi.getNewList(params);
                } else if (searchKeyword.value.trim()) {
                    // 搜索功能
                    params.name = searchKeyword.value.trim();
                    response = await homeApi.getRecommendList(params);
                } else {
                    // 没有搜索关键词也没有类型，显示推荐列表
                    response = await homeApi.getRecommendList(params);
                }
                
                if (response && response.success && response.result) {
                    books.value = response.result.records || response.result || [];
                    total.value = response.result.total || (Array.isArray(response.result) ? response.result.length : 0);
                } else {
                    books.value = [];
                    total.value = 0;
                }
            } catch (error) {
                console.error('获取书籍失败:', error);
                books.value = [];
                total.value = 0;
            } finally {
                loading.value = false;
            }
        };

        // 处理搜索
        const handleSearch = () => {
            if (localSearchKeyword.value.trim()) {
                // 清除类型，进入搜索模式
                const query = {
                    q: localSearchKeyword.value.trim(),
                    page: 1
                };
                
                if (selectedCategory.value) {
                    query.category = selectedCategory.value;
                }
                
                // 更新URL参数
                router.push({
                    path: '/search',
                    query: query
                });
            }
        };

        // 处理分页变化
        const handlePageChange = (page) => {
            currentPage.value = page;
            
            // 构建查询参数
            const query = {
                page: page
            };
            
            if (searchKeyword.value) {
                query.q = searchKeyword.value;
            }
            if (currentType.value) {
                query.type = currentType.value;
                query.title = pageTitle.value;
            }
            if (selectedCategory.value) {
                query.category = selectedCategory.value;
            }
            
            // 更新URL参数
            router.push({
                path: '/search',
                query: query
            });
        };

        // 处理分类变化
        const handleCategoryChange = (categoryId) => {
            selectedCategory.value = categoryId;
            currentPage.value = 1;
            
            // 直接获取数据
            fetchBooks();
            
            // 构建查询参数
            const query = {};
            
            if (searchKeyword.value) {
                query.q = searchKeyword.value;
            }
            if (currentType.value) {
                query.type = currentType.value;
                query.title = pageTitle.value;
            }
            if (categoryId) {
                query.category = categoryId;
            }
            
            // 更新URL参数
            router.push({
                path: '/search',
                query: query
            });
        };

        // 监听路由变化
        watch(
            () => route.query,
            (newQuery) => {
                const keyword = newQuery.q || '';
                const type = newQuery.type || '';
                const category = newQuery.category || '';
                const page = parseInt(newQuery.page) || 1;
                
                // 检查是否有变化
                const hasChanges = 
                    keyword !== searchKeyword.value ||
                    type !== currentType.value ||
                    category !== selectedCategory.value ||
                    page !== currentPage.value;
                
                if (hasChanges) {
                    searchKeyword.value = keyword;
                    localSearchKeyword.value = keyword;
                    currentType.value = type;
                    selectedCategory.value = category;
                    currentPage.value = page;
                    
                    fetchBooks();
                }
            },
            { immediate: true }
        );

        onMounted(async () => {
            // 获取分类列表
            await fetchCategories();
            
            // 初始化参数
            const keyword = route.query.q || '';
            const type = route.query.type || '';
            const category = route.query.category || '';
            const page = parseInt(route.query.page) || 1;
            
            searchKeyword.value = keyword;
            localSearchKeyword.value = keyword;
            currentType.value = type;
            selectedCategory.value = category;
            currentPage.value = page;
            
            // 如果有搜索关键词或类型，执行获取数据
            if (keyword || type) {
                fetchBooks();
            }
        });

        return {
            searchKeyword,
            localSearchKeyword,
            currentType,
            pageTitle,
            categories,
            selectedCategory,
            books,
            loading,
            currentPage,
            pageSize,
            total,
            handleSearch,
            handlePageChange,
            handleCategoryChange
        };
    }
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as vars;

.search-container {
    width: 100%;
    background-color: #fff;
    min-height: 100vh;
}

.search-header {
    margin-bottom: 30px;
    padding: 30px 20px 20px;
    background: linear-gradient(135deg, #f8fbff 0%, #f0f7ff 100%);
    border-bottom: 1px solid #e4e7ed;

    .search-title {
        text-align: center;
        padding: 10px 0;

        h1 {
            font-size: 28px;
            font-weight: 600;
            color: vars.$primary-color;
            margin: 0 0 15px 0;
            letter-spacing: 1px;
        }

        .search-info {
            font-size: 15px;
            color: #666;
            
            .search-keyword {
                color: vars.$primary-color;
                font-weight: 600;
                font-size: 16px;
            }

            .search-count {
                margin-left: 12px;
                color: #888;
                font-weight: 500;
            }
        }
    }
}

.content-wrapper {
    padding: 0 20px;
}

.search-content {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;

    .search-box {
        margin: 0 auto 40px auto;
        max-width: 600px;
        text-align: center;

        .search-input {
            width: 100%;
            
            :deep(.el-input__wrapper) {
                border-radius: 12px;
                box-shadow: 0 2px 12px rgba(10, 36, 99, 0.1);
                border: 1px solid #e4e7ed;
                transition: all 0.3s;
                
                &:hover {
                    border-color: vars.$primary-color;
                    box-shadow: 0 4px 16px rgba(10, 36, 99, 0.15);
                }
            }
            
            :deep(.el-input-group__append) {
                border-radius: 0 12px 12px 0;
                background-color: vars.$primary-color;
                border-color: vars.$primary-color;
                transition: all 0.3s;
                
                &:hover {
                    background-color: #082047;
                    border-color: #082047;
                }
                
                .el-button {
                    border: none;
                    background: transparent;
                    color: white;
                    font-weight: 500;
                    
                    &:hover {
                        background: transparent;
                        color: white;
                    }
                }
            }
            
            :deep(.el-input__inner) {
                font-size: 16px;
                padding: 12px 16px;
                height: 48px;
                
                &::placeholder {
                    color: #a8abb2;
                }
            }
        }
    }

    .filter-section {
        margin-bottom: 30px;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 12px;
        border: 1px solid #e4e7ed;

        .filter-item {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;

            .filter-label {
                font-size: 14px;
                font-weight: 600;
                color: #303133;
                white-space: nowrap;
                margin-right: 8px;
            }

            .filter-options {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                flex: 1;

                .el-button {
                    border-radius: 20px;
                    font-size: 13px;
                    padding: 8px 16px;
                    transition: all 0.3s;

                    &.el-button--primary {
                        background-color: vars.$primary-color;
                        border-color: vars.$primary-color;

                        &:hover {
                            background-color: #082047;
                            border-color: #082047;
                        }
                    }

                    &.is-plain {
                        color: #606266;
                        background-color: #fff;
                        border-color: #dcdfe6;

                        &:hover {
                            color: vars.$primary-color;
                            border-color: vars.$primary-color;
                            background-color: rgba(10, 36, 99, 0.05);
                        }
                    }
                }
            }
        }

        @media screen and (max-width: 768px) {
            .filter-item {
                flex-direction: column;
                align-items: flex-start;

                .filter-label {
                    margin-bottom: 8px;
                }

                .filter-options {
                    width: 100%;
                }
            }
        }
    }

    .loading-container {
        padding: 20px 0;
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 100px 20px;
        text-align: center;
        background: linear-gradient(135deg, #fafbff 0%, #f5f7ff 100%);
        border-radius: 16px;
        margin: 20px 0;

        .empty-icon {
            margin-bottom: 24px;
            opacity: 0.7;
            transform: scale(1.1);
        }

        .empty-title {
            font-size: 20px;
            font-weight: 600;
            color: #555;
            margin: 0 0 12px 0;
        }

        .empty-desc {
            font-size: 15px;
            color: #888;
            margin: 0;
            line-height: 1.6;
            max-width: 400px;
        }
    }
}

.book-list-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 24px;
    margin-bottom: 40px;
    padding: 0 10px;

    @media screen and (min-width: 1400px) {
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 28px;
    }

    @media screen and (max-width: vars.$md) {
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 20px;
    }

    @media screen and (max-width: 768px) {
        grid-template-columns: 1fr;
        gap: 16px;
        padding: 0;
    }
}

.book-item {
    width: 100%;
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 30px 0 40px;
    
    :deep(.el-pagination) {
        .el-pager li {
            border-radius: 8px;
            margin: 0 2px;
            transition: all 0.3s;
            
            &:hover {
                color: vars.$primary-color;
                background-color: rgba(10, 36, 99, 0.1);
            }
            
            &.is-active {
                background-color: vars.$primary-color;
                color: white;
                
                &:hover {
                    background-color: #082047;
                }
            }
        }
        
        .btn-prev,
        .btn-next {
            border-radius: 8px;
            transition: all 0.3s;
            
            &:hover {
                color: vars.$primary-color;
            }
        }
    }
}
</style> 