<template>
    <div class="author-content">
        <div class="page-header">
            <div class="header-tabs">
                <router-link :to="{ name: 'authorWorks' }" class="tab-item active">我的作品</router-link>
                <!-- 可以根据需要添加其他标签页 -->
            </div>
            <el-button type="primary" class="new-work-btn" @click="handleCreateNewWork">新建作品</el-button>
        </div>

        <div class="works-container">
            <!-- <div class="works-filter">
                <el-radio-group v-model="statusFilter" size="default" @change="handleFilterChange">
                    <el-radio-button label="all">全部</el-radio-button>
                    <el-radio-button label="draft">连载中</el-radio-button>
                    <el-radio-button label="published">已完结</el-radio-button>
                    <el-radio-button label="publishing">审核中</el-radio-button>
                </el-radio-group>
            </div> -->

            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>

            <div v-else-if="error" class="error-container">
                <el-result
                    icon="error"
                    title="加载失败"
                    sub-title="无法加载作品数据，请稍后再试"
                >
                    <template #extra>
                        <el-button type="primary" @click="loadWorks">重试</el-button>
                    </template>
                </el-result>
            </div>

            <div v-else-if="filteredWorks.length > 0" class="works-list">
                <work-item
                    v-for="work in filteredWorks"
                    :key="work.id"
                    :work="work"
                    @setup="handleWorkSetup"
                    @edit="handleWorkEdit"
                    @delete="handleDeleteWork"
                />
                
                <!-- 分页组件 -->
                <div v-if="pagination.total > pagination.pageSize" class="pagination-container">
                    <el-pagination
                        v-model:current-page="pagination.pageNo"
                        v-model:page-size="pagination.pageSize"
                        :total="pagination.total"
                        layout="prev, pager, next"
                        background
                        @size-change="handleSizeChange"
                        @current-change="handlePageChange"
                    />
                </div>
            </div>

            <div v-else class="no-works">
                <el-empty 
                    :description="works.length === 0 ? '暂无作品，快来创作您的第一部作品吧！' : '暂无符合条件的作品'"
                    :image-size="200"
                >
                    <template #extra v-if="works.length === 0">
                        <el-button type="primary" @click="handleCreateNewWork">立即创建</el-button>
                    </template>
                </el-empty>
            </div>
        </div>
    </div>
</template>

<script>
import { defineComponent, ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import WorkItem from '@/components/author/WorkItem.vue';
import { myBookApi } from '@/api/bookshelf.js';

export default defineComponent({
    name: 'WorksManagement',
    components: {
        WorkItem
    },
    setup() {
        const router = useRouter();
        const works = ref([]);
        const loading = ref(true);
        const error = ref(false);
        const statusFilter = ref('all');
        
        // 分页相关状态
        const pagination = ref({
            pageNo: 1,
            pageSize: 10,
            total: 0
        });
        
        const filteredWorks = computed(() => {
            if (statusFilter.value === 'all') {
                return works.value;
            }
            return works.value.filter(work => work.status === statusFilter.value);
        });

        // 加载作品列表
        const loadWorks = async () => {
            loading.value = true;
            error.value = false;

            try {
                const response = await myBookApi.getMyShopPage({
                    pageNo: pagination.value.pageNo,
                    pageSize: pagination.value.pageSize
                });

                if (response.result && response.code === 200) {
                    const data = response.result;
                    
                    // 转换API返回的数据格式为组件需要的格式
                    works.value = data.records || []
                    
                    // 更新分页信息
                    pagination.value.total = data.total || 0;
                } else {
                    throw new Error(response.data?.message || '获取作品列表失败');
                }
            } catch (err) {
                console.error('加载作品失败', err);
                error.value = true;
                ElMessage.error(err.message || '加载作品失败，请稍后再试');
            } finally {
                loading.value = false;
            }
        };

        // 处理筛选变化
        const handleFilterChange = (value) => {
            console.log('筛选状态变为:', value);
        };

        // 创建新作品
        const handleCreateNewWork = () => {
            router.push({ name: 'createWork' });
        };

        // 作品设置
        const handleWorkSetup = (workId) => {
            router.push({ name: 'workSetup', params: { id: workId } });
        };

        // 跳转到写作页面
        const handleWorkEdit = (workId) => {
            router.push({ name: 'workEdit', params: { id: workId } });
        };

        // 删除作品
        const handleDeleteWork = async (workId) => {
            try {
                // 获取要删除的作品信息
                const work = works.value.find(w => w.id === workId);
                const workTitle = work ? work.name : '此作品';

                // 显示确认对话框
                await ElMessageBox.confirm(
                    `确定要删除作品"${workTitle}"吗？删除后无法恢复。`,
                    '删除确认',
                    {
                        confirmButtonText: '确定删除',
                        cancelButtonText: '取消',
                        type: 'warning',
                        confirmButtonClass: 'el-button--danger'
                    }
                );

                // 用户确认后执行删除
                const response = await myBookApi.deleteMyShop(workId);
                if (response && response.code === 200) {
                    ElMessage.success('删除成功');
                    // 重新加载作品列表
                    loadWorks();
                } else {
                    throw new Error(response?.message || '删除失败');
                }
            } catch (err) {
                if (err === 'cancel') {
                    // 用户取消删除，不显示错误信息
                    return;
                }
                console.error('删除作品失败', err);
                ElMessage.error(err.message || '删除作品失败');
            }
        };

        // 分页变化处理
        const handlePageChange = (page) => {
            pagination.value.pageNo = page;
            loadWorks();
        };

        const handleSizeChange = (size) => {
            pagination.value.pageSize = size;
            pagination.value.pageNo = 1; // 重置到第一页
            loadWorks();
        };

        onMounted(() => {
            // 加载作品列表
            loadWorks();
            
            // 输出调试信息
            console.log('[WorksManagement] 组件已挂载');
        });

        return {
            works,
            loading,
            error,
            loadWorks,
            statusFilter,
            filteredWorks,
            pagination,
            handleFilterChange,
            handleCreateNewWork,
            handleWorkSetup,
            handleWorkEdit,
            handleDeleteWork,
            handlePageChange,
            handleSizeChange
        };
    }
});
</script>

<style lang="scss" scoped>
.author-content {
    flex: 1;
    
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        background-color: #fff;
        padding: 16px 20px;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        
        .header-tabs {
            display: flex;
            position: relative;
            
            .tab-item {
                padding: 8px 16px;
                margin-right: 24px;
                font-size: 16px;
                color: #666;
                text-decoration: none;
                position: relative;
                
                &.active {
                    color: #0A2463;
                    font-weight: bold;
                    
                    &::after {
                        content: '';
                        position: absolute;
                        bottom: -8px;
                        left: 0;
                        width: 100%;
                        height: 2px;
                        background-color: #0A2463;
                        border-radius: 1px;
                    }
                }
                
                &:hover:not(.active) {
                    color: #0A2463;
                }
            }
        }
        
        .new-work-btn {
            background-color: #0A2463;
            border-color: #0A2463;
            
            &:hover, &:focus {
                background-color: #1a3473;
                border-color: #1a3473;
            }
        }
    }

    .works-container {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        overflow: hidden;
        
        .works-filter {
            padding: 16px 20px;
            border-bottom: 1px solid #eee;
            
            :deep(.el-radio-button__inner) {
                border-color: #dcdfe6;
                color: #606266;
            }
            
            :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
                background-color: #0A2463;
                border-color: #0A2463;
                box-shadow: -1px 0 0 0 #0A2463;
                color: #fff;
            }
        }
        
        .loading-container,
        .error-container {
            padding: 20px;
        }
        
        .works-list {
            padding: 0;
            
            // 为每个作品项添加边框
            :deep(.work-item) {
                border-bottom: 1px solid #f0f0f0;
                padding: 20px;
                
                &:last-child {
                    border-bottom: none;
                }
            }
            
            .pagination-container {
                padding: 20px;
                border-top: 1px solid #f0f0f0;
                display: flex;
                justify-content: center;
                
                :deep(.el-pagination) {
                    .el-pager li.is-active {
                        background-color: #0A2463;
                        border-color: #0A2463;
                    }
                    
                    .btn-next, .btn-prev {
                        &:hover {
                            color: #0A2463;
                        }
                    }
                    
                    .el-pager li:hover {
                        color: #0A2463;
                    }
                }
            }
        }
        
        .no-works {
            padding: 60px 0;
            text-align: center;
        }
    }
}
</style> 