from rest_framework import serializers
from user_management.models import OperatorAccount, PlatformAccount, Video, KnowledgeBase, KnowledgeBaseDocument
import uuid
from django.db.models import Q


class OperatorAccountSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(read_only=False, required=False)  # 允许前端不提供ID，但如果提供则必须是有效的UUID
    
    class Meta:
        model = OperatorAccount
        fields = ['id', 'username', 'password', 'real_name', 'email', 'phone', 'position', 'department', 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']
        extra_kwargs = {
            'password': {'write_only': True}
        }
    
    def create(self, validated_data):
        # 如果没有提供ID，则生成一个UUID
        if 'id' not in validated_data:
            validated_data['id'] = uuid.uuid4()
            
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password:
            instance.password = password  # 在实际应用中应该加密存储密码
        instance.save()
        return instance


class PlatformAccountSerializer(serializers.ModelSerializer):
    operator_name = serializers.CharField(source='operator.real_name', read_only=True)
    
    class Meta:
        model = PlatformAccount
        fields = ['id', 'operator', 'operator_name', 'platform_name', 'account_name', 'account_id', 
                 'status', 'followers_count', 'account_url', 'description', 
                 'tags', 'profile_image', 'last_posting',
                 'created_at', 'updated_at', 'last_login']
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def to_internal_value(self, data):
        # 处理operator字段，可能是字符串格式的UUID
        if 'operator' in data and isinstance(data['operator'], str):
            try:
                # 尝试获取对应的运营账号对象
                operator = OperatorAccount.objects.get(id=data['operator'])
                data['operator'] = operator.id  # 确保使用正确的ID格式
            except OperatorAccount.DoesNotExist:
                # 如果找不到对应的运营账号，保持原值，让验证器捕获此错误
                pass
            except Exception as e:
                # 其他类型的错误，如ID格式不正确等
                pass
        
        return super().to_internal_value(data)
        
    def to_representation(self, instance):
        """将tags字符串转换为数组"""
        representation = super().to_representation(instance)
        if representation.get('tags'):
            representation['tags'] = representation['tags'].split(',')
        return representation


class PlatformDetailSerializer(serializers.Serializer):
    """平台详情序列化器，用于多平台账号创建"""
    platform_name = serializers.ChoiceField(choices=PlatformAccount.PLATFORM_CHOICES)
    platform_url = serializers.URLField()


class MultiPlatformAccountSerializer(serializers.Serializer):
    """多平台账号创建序列化器"""
    operator = serializers.PrimaryKeyRelatedField(queryset=OperatorAccount.objects.all())
    account_name = serializers.CharField(max_length=100)
    account_id = serializers.CharField(max_length=100)
    status = serializers.ChoiceField(choices=PlatformAccount.STATUS_CHOICES, default='active')
    followers_count = serializers.IntegerField(default=0)
    description = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    # 使用CharField而不是ListField，我们会在to_internal_value和to_representation中手动处理转换
    tags = serializers.CharField(required=False, allow_blank=True, allow_null=True, max_length=255)
    profile_image = serializers.URLField(required=False, allow_blank=True, allow_null=True)
    last_posting = serializers.DateTimeField(required=False, allow_null=True)
    platforms = PlatformDetailSerializer(many=True)
    
    def to_internal_value(self, data):
        # 处理tags字段，将列表转换为逗号分隔的字符串
        if 'tags' in data and isinstance(data['tags'], list):
            data = data.copy()
            data['tags'] = ','.join(data['tags'])
        
        # 处理operator字段，可能是字符串类型的ID
        if 'operator' in data and isinstance(data['operator'], str):
            try:
                # 尝试通过ID查找运营账号
                operator_id = data['operator']
                try:
                    # 先尝试通过整数ID查找
                    operator_id_int = int(operator_id)
                    operator = OperatorAccount.objects.get(id=operator_id_int)
                    data['operator'] = operator.id
                except (ValueError, OperatorAccount.DoesNotExist):
                    # 如果无法转换为整数或找不到对应账号，尝试通过用户名或真实姓名查找
                    operator = OperatorAccount.objects.filter(
                        Q(username=operator_id) | Q(real_name=operator_id)
                    ).first()
                    
                    if operator:
                        data['operator'] = operator.id
            except Exception as e:
                pass
        
        return super().to_internal_value(data)
        
    def to_representation(self, instance):
        """将tags字符串转换为数组"""
        representation = super().to_representation(instance)
        if representation.get('tags') and isinstance(representation['tags'], str):
            representation['tags'] = representation['tags'].split(',')
        return representation


class VideoSerializer(serializers.ModelSerializer):
    platform_account_name = serializers.CharField(source='platform_account.account_name', read_only=True)
    platform_name = serializers.CharField(source='platform_account.platform_name', read_only=True)
    
    class Meta:
        model = Video
        fields = ['id', 'platform_account', 'platform_account_name', 'platform_name', 'title', 
                 'description', 'video_url', 'local_path', 'thumbnail_url', 'status', 
                 'views_count', 'likes_count', 'comments_count', 'shares_count', 'tags', 
                 'publish_time', 'scheduled_time', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at', 'views_count', 'likes_count', 
                           'comments_count', 'shares_count']
                           
    def to_internal_value(self, data):
        # 处理tags字段，将列表转换为逗号分隔的字符串
        if 'tags' in data and isinstance(data['tags'], list):
            data = data.copy()
            data['tags'] = ','.join(data['tags'])
        
        # 处理platform_account字段，可能是字符串格式的UUID
        if 'platform_account' in data and isinstance(data['platform_account'], str):
            try:
                # 尝试获取对应的平台账号对象
                platform_account = PlatformAccount.objects.get(id=data['platform_account'])
                data['platform_account'] = platform_account.id  # 确保使用正确的ID格式
            except PlatformAccount.DoesNotExist:
                # 如果找不到对应的平台账号，保持原值，让验证器捕获此错误
                pass
            except Exception as e:
                # 其他类型的错误，如ID格式不正确等
                pass
        
        return super().to_internal_value(data)
        
    def to_representation(self, instance):
        """将tags字符串转换为数组"""
        representation = super().to_representation(instance)
        if representation.get('tags'):
            representation['tags'] = representation['tags'].split(',')
        return representation


class KnowledgeBaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = KnowledgeBase
        fields = ['id', 'user_id', 'name', 'desc', 'type', 'department', 'group', 
                 'external_id', 'create_time', 'update_time']
        read_only_fields = ['id', 'create_time', 'update_time']


class KnowledgeBaseDocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = KnowledgeBaseDocument
        fields = ['id', 'knowledge_base', 'document_id', 'document_name', 
                 'external_id', 'uploader_name', 'status', 'create_time', 'update_time']
        read_only_fields = ['id', 'create_time', 'update_time'] 
        