from django.contrib.auth.models import User
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions
from rest_framework.response import Response
from rest_framework import status, serializers
from rest_framework.generics import GenericAPIView

from flower.viewsets import LimitedLimitOffsetPagination
from basic_info.models import UserProfile


class UserCreationSerializer(serializers.Serializer):
    """用户创建序列化器"""
    username = serializers.CharField(max_length=150)
    email = serializers.EmailField(required=False)
    password = serializers.CharField(min_length=6, write_only=True)
    is_staff = serializers.BooleanField(default=False)
    description = serializers.CharField(required=False, allow_blank=True)
    merchant_id = serializers.IntegerField()

    def validate_username(self, value):
        """验证用户名是否已存在"""
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在")
        return value

    def validate_merchant_id(self, value):
        """验证merchant_id是否存在"""
        from basic_info.models import Merchant
        if not Merchant.objects.filter(id=value).exists():
            raise serializers.ValidationError("商户不存在")
        return value


class UserSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'is_staff', 'is_active', 'date_joined']


class UserProfileDetailSerializer(serializers.ModelSerializer):
    """用户资料详细信息序列化器"""
    user = UserSerializer(read_only=True)
    
    class Meta:
        model = UserProfile
        fields = ['id', 'user', 'merchant', 'description', 'created_at', 'updated_at']


class CreateUserWithProfileView(GenericAPIView):
    """创建用户和关联的用户资料信息视图"""
    queryset = User.objects.all()
    permission_classes = [IsAuthenticated, DjangoModelPermissions]
    pagination_class = LimitedLimitOffsetPagination

    def post(self, request):
        """
        创建用户和用户资料

        POST /api/v1/users/create/

        请求参数:
        - username: 用户名 (必需)
        - email: 邮箱 (可选)
        - password: 密码 (必需, 最少6位)
        - is_staff: 是否为员工 (可选, 默认为False)
        - description: 用户资料描述 (可选)
        - merchant_id: 商户ID (必需)

        返回:
        - user: 创建的用户信息
        - profile: 创建的用户资料信息
        """
        # 检查当前用户是否有权限（超级用户或有员工身份）
        if not request.user.is_authenticated:
            return Response({'error': '未授权'}, status=status.HTTP_401_UNAUTHORIZED)

        # 序列化和验证请求数据
        serializer = UserCreationSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        username = serializer.validated_data['username']
        email = serializer.validated_data.get('email', '')
        password = serializer.validated_data['password']
        is_staff = serializer.validated_data.get('is_staff', False)
        description = serializer.validated_data.get('description', '')
        merchant_id = serializer.validated_data['merchant_id']

        try:
            # 创建用户
            user = User.objects.create_user(
                username=username,
                email=email,
                password=password,
                is_staff=is_staff
            )

            # 创建用户资料
            from basic_info.models import Merchant
            merchant = Merchant.objects.get(id=merchant_id)
            profile = UserProfile.objects.create(
                user=user,
                merchant=merchant,
                description=description
            )

            # 返回创建的用户和用户资料信息
            user_data = UserSerializer(user).data
            profile_data = UserProfileDetailSerializer(profile).data

            return Response({
                'user': user_data,
                'profile': profile_data
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            # 如果创建过程中出现错误，删除已创建的用户
            if 'user' in locals():
                user.delete()
            return Response({
                'error': f'创建用户失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
