from django.contrib.auth.models import Group
from rest_framework import serializers, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from basic_info import models as basic_models
from basic_info.services import EmployeeUserProvisioningService

from django.contrib.auth import get_user_model

User = get_user_model()


class RoleListView(APIView):
    """
    获取所有角色列表（基于 Django Group）。

    GET /api/v2/roles/
    返回: [{"id": 1, "name": "管理员"}, ...]
    """

    permission_classes = [IsAuthenticated]

    def get(self, request):
        roles = Group.objects.all().values('id', 'name').order_by('id')
        return Response(list(roles))


class QuickEmployeeUserCreateSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=150)
    password = serializers.CharField(write_only=True, min_length=6)
    display_name = serializers.CharField(max_length=100)
    merchant_id = serializers.IntegerField()
    email = serializers.EmailField(required=False, allow_blank=True, allow_null=True)
    mobile = serializers.CharField(required=False, allow_blank=True, allow_null=True, max_length=20)
    area = serializers.CharField(required=False, allow_blank=True, allow_null=True, max_length=100)
    description = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    status = serializers.ChoiceField(
        choices=basic_models.EmployeeStatusEnum.choices,
        required=False,
        default=basic_models.EmployeeStatusEnum.ACTIVE,
    )
    role_id = serializers.IntegerField(required=False, allow_null=True, help_text='角色ID（可选）')

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

    def validate_merchant_id(self, value):
        if not basic_models.Merchant.objects.filter(id=value).exists():
            raise serializers.ValidationError('商户不存在')
        return value

    def validate_role_id(self, value):
        if value is not None and not Group.objects.filter(id=value).exists():
            raise serializers.ValidationError('角色不存在')
        return value


class QuickCreateEmployeeUserView(APIView):
    """
    快速创建系统用户 + 关联员工。

    POST /api/v2/users/quick-create/
    """

    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = QuickEmployeeUserCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data

        result = EmployeeUserProvisioningService.quick_create_employee_user(
            username=data["username"],
            password=data["password"],
            display_name=data["display_name"],
            merchant_id=data["merchant_id"],
            email=data.get("email"),
            mobile=data.get("mobile"),
            area=data.get("area"),
            description=data.get("description"),
            status=data.get("status"),
            role_id=data.get("role_id"),
        )

        return Response(
            result.to_dict(),
            status=status.HTTP_201_CREATED,
        )
