from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import User, Data, Permission, ChatHistory, KnowledgeBase, Notification
import uuid
import logging

logger = logging.getLogger(__name__)

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'role', 'department', 'phone', 'avatar']
        read_only_fields = ['id']

class DataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Data
        fields = [
            'id', 'name', 'desc', 'type', 'meta',
            'user_id', 'department', 'char_length',
            'document_count', 'application_mapping_count',
            'create_time', 'update_time'
        ]
        read_only_fields = ['id', 'create_time', 'update_time', 'user_id']

    def validate(self, data):
        request = self.context.get('request')
        if not request or not request.user.is_authenticated:
            raise ValidationError("用户未认证")

        # 验证数据类型权限
        user = request.user
        data_type = data.get('type')
        if data_type == 'admin' and user.role != 'admin':
            raise ValidationError("只有管理员可以创建管理员数据")
        elif data_type == 'leader' and user.role not in ['admin', 'leader']:
            raise ValidationError("只有管理员和组长可以创建组长数据")

        return data

class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = [
            'id',
            'knowledge_base',
            'applicant',
            'permissions',
            'status',
            'reason',
            'response_message',
            'expires_at',
            'created_at',
            'updated_at'
        ]
        read_only_fields = [
            'id',
            'applicant',
            'status',
            'created_at',
            'updated_at'
        ]

class ChatHistorySerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatHistory
        fields = [
            'id', 'user', 'knowledge_base',
            'conversation_id', 'parent_id', 'role',
            'content', 'create_time'
        ]
        read_only_fields = ['id', 'create_time']

class KnowledgeBaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = KnowledgeBase
        fields = '__all__'
        read_only_fields = ('user_id',)  # 移除 owners

    def create(self, validated_data):
        """创建时自动设置 user_id"""
        request = self.context.get('request')
        if not request or not hasattr(request, 'user'):
            raise serializers.ValidationError('无法获取当前用户信息')
            
        user = request.user
        if not user.is_authenticated:
            raise serializers.ValidationError('用户未登录')
            
        # 设置 user_id
        validated_data['user_id'] = user.id
        
        logger.info(f"设置知识库创建者: user_id={user.id}, username={user.username}")
        
        return super().create(validated_data)

class KnowledgePermissionSerializer(serializers.ModelSerializer):
    """知识库权限序列化器"""
    
    class Meta:
        model = Permission
        fields = [
            'id',
            'resource_type',
            'resource_id',
            'applicant',
            'approver',
            'operations',
            'status',
            'expires_at',
            'create_time',
            'update_time'
        ]
        read_only_fields = ['id', 'create_time', 'update_time']

    def validate(self, data):
        """验证权限申请数据"""
        if data['resource_type'] != 'knowledge':
            raise serializers.ValidationError("资源类型必须是知识库")
            
        # 验证知识库是否存在
        try:
            KnowledgeBase.objects.get(id=data['resource_id'])
        except KnowledgeBase.DoesNotExist:
            raise serializers.ValidationError("知识库不存在")
            
        return data

    def create(self, validated_data):
        """创建权限申请"""
        validated_data['resource_type'] = 'knowledge'
        return super().create(validated_data)

class NotificationSerializer(serializers.ModelSerializer):
    """通知序列化器"""
    class Meta:
        model = Notification
        fields = ['id', 'type', 'title', 'content', 'sender', 'receiver', 
                 'is_read', 'related_resource', 'created_at']
        read_only_fields = ['id', 'created_at']
