<template>
    <div class="personal-info-modal">
        <el-dialog
            v-model="visible"
            title="个人信息"
            width="400px"
            :close-on-click-modal="false"
            :close-on-press-escape="true"
            @close="handleClose"
        >
            <div class="modal-content">
                <!-- 头像上传区域 -->
                <div class="avatar-section">
                    <div class="avatar-wrapper" @click="handleAvatarClick">
                        <el-avatar :size="80" :src="userInfo.headImage">
                            <el-icon v-if="!userInfo.headImage"><UserFilled /></el-icon>
                        </el-avatar>
                        <div class="camera-overlay">
                            <el-icon class="camera-icon"><Camera /></el-icon>
                        </div>
                    </div>
                    <!-- 隐藏的文件上传输入框 -->
                    <input
                        ref="fileInputRef"
                        type="file"
                        accept="image/*"
                        style="display: none"
                        @change="handleFileChange"
                    />
                </div>

                <!-- 表单区域 -->
                <el-form
                    ref="formRef"
                    :model="formData"
                    :rules="formRules"
                    label-position="left"
                    label-width="80px"
                    class="info-form"
                >
                    <!-- 昵称 -->
                    <el-form-item label="昵称" prop="nickName" required>
                        <el-input
                            v-model="formData.nickName"
                            placeholder="请输入昵称"
                            maxlength="20"
                            show-word-limit
                            @blur="handleNickNameBlur"
                        />
                    </el-form-item>

                    <!-- 个性签名 -->
                    <el-form-item label="个性签名">
                        <el-input
                            v-model="formData.details"
                            placeholder="请输入个性签名"
                            maxlength="50"
                            show-word-limit
                            @blur="handleSignatureBlur"
                        />
                    </el-form-item>

                    <!-- 手机号 -->
                    <el-form-item label="手机号">
                        <div class="phone-container">
                            <span class="phone-number">{{ maskPhoneNumber(userInfo.phone) }}</span>
                            <el-button 
                                type="text" 
                                class="modify-link"
                                @click="handleModifyPhone"
                            >
                                修改手机号
                            </el-button>
                        </div>
                    </el-form-item>

                    <!-- 豆豆 -->
                    <el-form-item label="豆豆">
                        <div class="bean-container">
                            <span class="bean-number">{{ userInfo.integerPrice || 0 }}</span>
                            <el-button 
                                type="text" 
                                class="detail-link"
                                @click="handleViewDetails"
                            >
                                查看详情
                            </el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 底部按钮 -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button 
                        type="primary" 
                        class="recharge-btn"
                        @click="handleRecharge"
                    >
                        去充值
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 手机号修改弹窗 -->
        <PhoneModifyModal
            v-model="showPhoneModal"
            @success="handlePhoneUpdateSuccess"
        />
    </div>
</template>

<script>
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Camera, UserFilled } from '@element-plus/icons-vue';
import { useMainStore } from '@/store';
import { useRouter } from 'vue-router';
import { ossService } from '@/utils/oss.js';
import PhoneModifyModal from './PhoneModifyModal.vue';

export default {
    name: 'PersonalInfoModal',
    components: {
        Camera,
        UserFilled,
        PhoneModifyModal
    },
    props: {
        modelValue: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:modelValue', 'success'],
    setup(props, { emit }) {
        const store = useMainStore();
        const router = useRouter();
        const formRef = ref(null);
        const fileInputRef = ref(null);
        const showPhoneModal = ref(false);

        const visible = computed({
            get: () => props.modelValue,
            set: (value) => emit('update:modelValue', value)
        });

        // 用户信息
        const userInfo = computed(() => store.user || {});

        // 表单数据
        const formData = reactive({
            nickName: '',
            details: ''
        });

        // 表单验证规则
        const formRules = {
            nickName: [
                { required: true, message: '请输入昵称', trigger: 'blur' },
                { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
            ]
        };

        // 手机号脱敏显示
        const maskPhoneNumber = (phone) => {
            if (!phone) return '未绑定';
            if (phone.length === 11) {
                return `${phone.slice(0, 3)} ${phone.slice(3, 7)} ${phone.slice(7)}`;
            }
            return phone;
        };

        // 监听弹窗显示状态，初始化数据
        watch(visible, (newVal) => {
            if (newVal) {
                initFormData();
            }
        });

        // 初始化表单数据
        const initFormData = () => {
            formData.nickName = userInfo.value.nickName || '';
            formData.details = userInfo.value.details || '';
        };

        // 头像点击处理
        const handleAvatarClick = () => {
            fileInputRef.value?.click();
        };

        // 文件选择处理
        const handleFileChange = async (event) => {
            const file = event.target.files[0];
            if (!file) return;

            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                ElMessage.error('请选择图片文件');
                return;
            }

            // 验证文件大小（2MB）
            if (file.size > 2 * 1024 * 1024) {
                ElMessage.error('图片大小不能超过2MB');
                return;
            }

            try {
                const loadingMessage = ElMessage.loading('上传头像中...');
                
                // 上传到OSS
                const imageUrl = await ossService.uploadImage(file);
                
                // 更新用户头像
                await store.updateUserInfo({
                    headImage: imageUrl
                });

                loadingMessage.close();
                ElMessage.success('头像更新成功');
                
            } catch (error) {
                console.error('头像上传失败:', error);
                ElMessage.error('头像上传失败，请重试');
            }

            // 清空input值，允许重复选择同一文件
            event.target.value = '';
        };

        // 修改手机号
        const handleModifyPhone = () => {
            showPhoneModal.value = true;
        };

        // 手机号更新成功回调
        const handlePhoneUpdateSuccess = () => {
            ElMessage.success('手机号修改成功');
        };

        // 查看详情
        const handleViewDetails = () => {
            visible.value = false;
            router.push('/money-log');
        };

        // 去充值
        const handleRecharge = () => {
            visible.value = false;
            router.push('/recharge');
        };

        // 保存个人信息
        const handleSave = async () => {
            try {
                await formRef.value?.validate();
                
                const loadingMessage = ElMessage.loading('保存中...');
                
                await store.updateUserInfo({
                    nickName: formData.nickName,
                    details: formData.details
                });

                loadingMessage.close();
                ElMessage.success('保存成功');
                emit('success');
                visible.value = false;
                
            } catch (error) {
                console.error('保存失败:', error);
                ElMessage.error('保存失败，请重试');
            }
        };

        // 昵称失焦保存
        const handleNickNameBlur = async () => {
            if (formData.nickName && formData.nickName !== userInfo.value.nickName) {
                try {
                    await formRef.value?.validateField('nickName');
                    await store.updateUserInfo({
                        nickName: formData.nickName
                    });
                    ElMessage.success('昵称保存成功');
                } catch (error) {
                    console.error('昵称保存失败:', error);
                }
            }
        };

        // 个性签名失焦保存
        const handleSignatureBlur = async () => {
            if (formData.details !== userInfo.value.details) {
                try {
                    await store.updateUserInfo({
                        details: formData.details
                    });
                    ElMessage.success('个性签名保存成功');
                } catch (error) {
                    console.error('个性签名保存失败:', error);
                }
            }
        };

        // 关闭弹窗
        const handleClose = () => {
            visible.value = false;
        };

        return {
            visible,
            formRef,
            fileInputRef,
            formData,
            formRules,
            userInfo,
            showPhoneModal,
            maskPhoneNumber,
            handleAvatarClick,
            handleFileChange,
            handleModifyPhone,
            handlePhoneUpdateSuccess,
            handleViewDetails,
            handleRecharge,
            handleNickNameBlur,
            handleSignatureBlur,
            handleClose
        };
    }
};
</script>

<style lang="scss" scoped>
.personal-info-modal {
    .modal-content {
        padding: 0;

        .avatar-section {
            display: flex;
            justify-content: center;
            margin-bottom: 24px;

            .avatar-wrapper {
                position: relative;
                cursor: pointer;
                transition: transform 0.3s ease;

                &:hover {
                    transform: scale(1.05);

                    .camera-overlay {
                        opacity: 1;
                    }
                }

                .camera-overlay {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0, 0, 0, 0.5);
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    opacity: 0;
                    transition: opacity 0.3s ease;

                    .camera-icon {
                        color: white;
                        font-size: 24px;
                    }
                }

                :deep(.el-avatar) {
                    border: 3px solid #f0f0f0;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                }
            }
        }

        .info-form {
            .phone-container,
            .bean-container {
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 100%;

                .phone-number,
                .bean-number {
                    font-size: 16px;
                    color: #606266;
                    flex: 1;
                }

                .modify-link,
                .detail-link {
                    color: #0A2463;
                    font-size: 14px;
                    padding: 0;
                    margin-left: 12px;

                    &:hover {
                        color: #083354;
                    }
                }
            }

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

            :deep(.el-input__inner) {
                border-radius: 6px;
            }

            :deep(.el-form-item) {
                margin-bottom: 20px;
            }

            :deep(.el-form-item__label::before) {
                color: #F56C6C;
            }
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
        padding-top: 10px;

        .recharge-btn {
            width: 100%;
            height: 44px;
            background-color: #0A2463;
            border-color: #0A2463;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;

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

    :deep(.el-dialog__header) {
        padding: 20px 20px 10px 20px;
        text-align: center;

        .el-dialog__title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
        }
    }

    :deep(.el-dialog__body) {
        padding: 10px 20px 20px 20px;
    }

    :deep(.el-dialog__footer) {
        padding: 10px 20px 20px 20px;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .personal-info-modal {
        :deep(.el-dialog) {
            width: 90% !important;
            margin: 5vh auto !important;
        }

        .modal-content {
            .avatar-section {
                margin-bottom: 20px;

                .avatar-wrapper {
                    :deep(.el-avatar) {
                        width: 70px !important;
                        height: 70px !important;
                    }
                }
            }

            .info-form {
                :deep(.el-form-item) {
                    margin-bottom: 16px;
                }

                :deep(.el-form-item__label) {
                    width: 70px !important;
                    font-size: 14px;
                }
            }
        }

        .dialog-footer {
            .recharge-btn {
                height: 40px;
                font-size: 14px;
            }
        }
    }
}
</style> 