<template>
    <el-dialog 
        :model-value="visible" 
        @update:model-value="$emit('update:visible', $event)"
        :title="isEdit ? '编辑作家信息' : '申请成为创作者'" 
        width="500px" 
        :show-close="true" 
        :close-on-click-modal="false" 
        center
        class="author-application-modal"
    >
        <div class="application-form">
            <div class="form-item">
                <div class="required-label">笔名</div>
                <el-input v-model="penName" placeholder="请输入..." />
            </div>

            <div class="form-item">
                <div class="required-label">简介</div>
                <el-input 
                    v-model="introduction" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请输入..." 
                />
            </div>

            <el-button 
                type="primary" 
                class="submit-button" 
                :loading="loading"
                :disabled="!isValid" 
                @click="handleSubmit"
            >
                {{ isEdit ? '保存修改' : '成为创作者' }}
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useMainStore } from '@/store';
import { writerApi } from '@/api/user';

export default {
    name: 'AuthorApplicationModal',
    props: {
        visible: {
            type: Boolean,
            required: true
        }
    },
    emits: ['update:visible', 'application-success'],
    setup(props, { emit }) {
        const store = useMainStore();
        
        // 表单数据
        const penName = ref('');
        const introduction = ref('');
        const loading = ref(false);
        const writerId = ref(null); // 作家ID，用于判断是新增还是编辑
        const isEdit = ref(false); // 是否为编辑模式

        // 表单验证
        const isValid = computed(() => {
            return penName.value.trim() !== '' && introduction.value.trim() !== '';
        });

        // 获取作家信息
        const getMyWriter = async () => {
            try {
                // 首先检查用户是否已经是作家
                if (!store.isCurrentAuthor) {
                    // 不是作家，直接进入申请模式
                    resetForm();
                    isEdit.value = false;
                    return;
                }

                // 是作家，获取作家详细信息进行回显
                const response = await writerApi.getMyWriter();
                if (response.result) {
                    const writerInfo = response.result;
                    penName.value = writerInfo.name || '';
                    introduction.value = writerInfo.details || '';
                    writerId.value = writerInfo.id || null;
                    isEdit.value = true;
                } else {
                    // 虽然是作家但获取不到详细信息，仍然进入申请模式
                    resetForm();
                    isEdit.value = false;
                }
            } catch (error) {
                console.error('获取作家信息失败:', error);
                // 获取失败时，根据store中的作家状态来决定模式
                if (store.isCurrentAuthor) {
                    // 是作家但获取信息失败，进入编辑模式但不填充信息
                    resetForm();
                    isEdit.value = true;
                } else {
                    // 不是作家，进入申请模式
                    resetForm();
                    isEdit.value = false;
                }
            }
        };

        // 提交申请
        const handleSubmit = async () => {
            if (!isValid.value) {
                ElMessage.warning('请填写完整信息');
                return;
            }

            try {
                loading.value = true;
                
                // 准备提交数据
                const data = {
                    penName: penName.value.trim(),
                    details: introduction.value.trim()
                };

                // 如果是编辑模式，添加ID
                if (writerId.value) {
                    data.id = writerId.value;
                }

                // 调用API
                const response = await writerApi.saveOrUpdateWriter(data);
                
                if (response.code === 200) {
                    ElMessage.success(isEdit.value ? '修改成功' : '申请成功');
                    
                    // 如果是新申请成功，需要更新用户的作家状态
                    if (!isEdit.value) {
                        // 重新获取最新的用户信息以更新作家状态
                        try {
                            await store.fetchLatestUserInfo();
                        } catch (error) {
                            console.error('更新用户信息失败:', error);
                            // 即使更新失败，也手动设置作家状态
                            store.setAsAuthor();
                        }
                    }
                    
                    // 触发成功回调
                    emit('application-success', {
                        penName: penName.value,
                        introduction: introduction.value,
                        isEdit: isEdit.value
                    });
                    
                    // 关闭弹窗
                    emit('update:visible', false);
                } else {
                    ElMessage.error(response.message || '提交失败，请稍后重试');
                }
            } catch (error) {
                console.error('提交失败:', error);
                ElMessage.error('提交失败，请稍后重试');
            } finally {
                loading.value = false;
            }
        };

        // 重置表单
        const resetForm = () => {
            penName.value = '';
            introduction.value = '';
            writerId.value = null;
            isEdit.value = false;
        };

        // 监听弹窗显示状态，打开时获取作家信息
        watch(
            () => props.visible,
            (newVisible) => {
                if (newVisible) {
                    getMyWriter();
                }
            }
        );

        return {
            penName,
            introduction,
            loading,
            isValid,
            isEdit,
            handleSubmit
        };
    }
};
</script>

<style lang="scss" scoped>
@use 'sass:color';

.author-application-modal {
    // 全局共享样式
    :deep(.el-input__wrapper),
    :deep(.el-textarea__inner),
    :deep(.el-button) {
        box-sizing: border-box;
    }
    
    :deep(.el-input__wrapper) {
        padding: 0 15px;
        height: 44px !important;
        line-height: 44px !important;
    }
    
    :deep(.el-input__inner),
    :deep(.el-textarea__inner) {
        font-size: 15px;
    }
    
    .application-form {
        padding: 10px 0;
        
        .form-item {
            margin-bottom: 20px;
            
            .required-label {
                margin-bottom: 8px;
                font-size: 14px;
                font-weight: 500;
                color: #333;
                
                &::before {
                    content: '*';
                    color: #f56c6c;
                    margin-right: 4px;
                }
            }
        }
        
        .submit-button {
            width: 100%;
            height: 44px;
            margin-top: 10px;
            background-color: #0A2463;
            border-color: #0A2463;
            
            &:hover {
                background-color: color.adjust(#0A2463, $lightness: -10%);
                border-color: color.adjust(#0A2463, $lightness: -10%);
            }
        }
    }
}
</style> 