<template>
    <div class="work-setup-container">
        <div class="work-setup-content">
            <div class="page-header">
                <h2 class="page-title">作品设置</h2>
                <el-button @click="goBack">返回作品列表</el-button>
            </div>

            <div class="setup-form-container">
                <el-form :model="workForm" :rules="rules" ref="workFormRef" label-position="top">
                    <el-form-item label="作品名称" prop="name">
                        <el-input v-model="workForm.name" placeholder="请输入作品名称"></el-input>
                    </el-form-item>

                    <el-form-item label="作品分类" prop="shopClass">
                        <el-select 
                            v-model="workForm.shopClass" 
                            placeholder="请选择分类" 
                            multiple
                        >
                            <el-option v-for="item in categories" :key="item.id" :label="item.title" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="作品状态" prop="status">
                        <el-radio-group v-model="workForm.status">
                            <el-radio :label="0">连载中</el-radio>
                            <el-radio :label="1">已完结</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="简介" prop="details">
                        <el-input 
                            v-model="workForm.details" 
                            type="textarea" 
                            :rows="5" 
                            placeholder="请输入作品简介"
                            maxlength="500"
                            show-word-limit
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="封面图片">
                        <div>
                            <el-upload
                                class="cover-uploader"
                                action="#"
                                :http-request="uploadCover"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                            >
                                <img v-if="workForm.image" :src="workForm.image" class="cover-image" />
                                <div v-else class="cover-placeholder">
                                    <el-icon><Plus /></el-icon>
                                    <div class="upload-text">点击上传封面</div>
                                </div>
                            </el-upload>
                            <div class="upload-tip">JPG/PNG格式</div>
                        </div>
                    </el-form-item>

                    <div class="form-actions">
                        <el-button @click="goBack">取消</el-button>
                        <el-button type="primary" @click="submitForm" :loading="loading">保存设置</el-button>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { myBookApi } from '@/api/bookshelf';
import { useMainStore } from '@/store';
import { ossService } from '@/utils/oss';

export default defineComponent({
    name: 'WorkSetup',
    components: {
        Plus
    },
    setup() {
        const router = useRouter();
        const route = useRoute();
        const workId = route.params.id;
        const store = useMainStore();
        
        const workFormRef = ref(null);
        const loading = ref(false);
        const categories = computed(() => store.allCategories);

        // 表单数据
        const workForm = reactive({
            id: workId,
            name: '', // 作品名称
            image: '', // 封面图片
            shopClass: [], // 作品分类 - 改为数组
            details: '', // 作品简介
            status: '0', // 作品状态，默认连载
        });

        // 表单验证规则
        const rules = {
            name: [
                { required: true, message: '请输入作品名称', trigger: 'blur' },
                { min: 2, max: 30, message: '长度应为2-30个字符', trigger: 'blur' }
            ],
            shopClass: [
                { 
                    required: true, 
                    type: 'array',
                    min: 1,
                    message: '请至少选择一个分类', 
                    trigger: 'change' 
                }
            ],
            details: [
                { required: true, message: '请输入作品简介', trigger: 'blur' },
                { min: 10, max: 500, message: '简介长度应为10-500个字符', trigger: 'blur' }
            ],
            status: [
                { required: true, message: '请选择作品状态', trigger: 'change' }
            ]
        };

        // 加载作品信息
        const loadWorkData = async () => {
            try {
                loading.value = true;
                const response = await myBookApi.getMyShopPage({
                    pageNo: 1,
                    pageSize: 1,
                    id: workId
                });

                if (response.success && response.result?.records?.length > 0) {
                    const workData = response.result.records[0];
                    Object.assign(workForm, {
                        name: workData.name,
                        image: workData.image,
                        shopClass: workData.shopClass ? workData.shopClass.split(',').map(id => parseInt(id)) : [], // 将逗号分隔的字符串转换为数组
                        details: workData.details,
                        status: workData.status
                    });
                } else {
                    ElMessage.error('作品不存在');
                    router.push({ name: 'authorCenter' });
                }
            } catch (error) {
                console.error('加载作品信息失败:', error);
                ElMessage.error('加载作品信息失败');
            } finally {
                loading.value = false;
            }
        };

        // 上传前校验
        const beforeUpload = (file) => {
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                ElMessage.error('封面图片只能是JPG或PNG格式!');
                return false;
            }
            if (!isLt2M) {
                ElMessage.error('封面图片大小不能超过2MB!');
                return false;
            }
            return true;
        };

        // 上传封面
        const uploadCover = async (options) => {
            const { file } = options;
            try {
                loading.value = true;
                // 使用 OSS 服务上传图片
                const imageUrl = await ossService.uploadImage(file);
                workForm.image = imageUrl;
                ElMessage.success('封面上传成功');
            } catch (error) {
                ElMessage.error(error.message || '上传失败，请重试');
            } finally {
                loading.value = false;
            }
        };

        // 提交表单
        const submitForm = () => {
            workFormRef.value.validate(async (valid) => {
                if (valid) {
                    try {
                        loading.value = true;
                        // 准备提交数据，将分类数组转换为逗号分隔的字符串
                        const submitData = {
                            ...workForm,
                            shopClass: workForm.shopClass.join(',')
                        };
                        
                        // 调用保存作品接口
                        await myBookApi.saveOrUpdateShop(submitData);
                        
                        ElMessage.success('作品设置保存成功！');
                        router.push({ name: 'authorCenter' });
                    } catch (error) {
                        ElMessage.error('保存失败，请稍后重试');
                    } finally {
                        loading.value = false;
                    }
                } else {
                    ElMessage.warning('请正确填写表单信息');
                    return false;
                }
            });
        };

        // 返回作品列表
        const goBack = () => {
            router.push({ name: 'authorCenter' });
        };
        
        onMounted(async () => {
            // 确保分类数据已加载
            await store.fetchCategories();
            // 加载作品信息
            await loadWorkData();
        });

        return {
            workFormRef,
            workForm,
            rules,
            categories,
            loading,
            beforeUpload,
            uploadCover,
            submitForm,
            goBack
        };
    }
});
</script>

<style lang="scss" scoped>
.work-setup-container {
    background-color: #f5f5f9;
    min-height: calc(100vh - 60px);
    padding: 30px 0;

    .work-setup-content {
        max-width: 800px;
        margin: 0 auto;
        padding: 30px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            
            .page-title {
                font-size: 24px;
                color: #333;
                margin: 0;
            }
        }

        .setup-form-container {
            :deep(.el-form-item__label) {
                font-weight: 500;
                color: #333;
            }

            :deep(.el-input__wrapper) {
                padding: 0 15px;
                height: 44px;
            }

            .cover-uploader {
                .cover-image {
                    width: 150px;
                    height: 200px;
                    object-fit: cover;
                    border-radius: 4px;
                }

                .cover-placeholder {
                    width: 150px;
                    height: 200px;
                    background-color: #f7f9fc;
                    border: 1px dashed #d9d9d9;
                    border-radius: 4px;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    cursor: pointer;

                    &:hover {
                        border-color: #0A2463;
                        color: #0A2463;
                    }

                    .el-icon {
                        font-size: 28px;
                        color: #8c939d;
                        margin-bottom: 8px;
                    }

                    .upload-text {
                        font-size: 14px;
                        color: #8c939d;
                    }
                }
            }

            .upload-tip {
                font-size: 12px;
                color: #aaa;
                margin-top: 8px;
            }

            .form-actions {
                margin-top: 40px;
                display: flex;
                justify-content: center;
                gap: 20px;

                .el-button {
                    width: 120px;
                }

                .el-button--primary {
                    background-color: #0A2463;
                    border-color: #0A2463;

                    &:hover, &:focus {
                        background-color: #1a3473;
                        border-color: #1a3473;
                    }
                }
            }
        }
    }
}
</style> 