from collections import defaultdict

from django.http import JsonResponse
from django.views import View

from Model.models import Device_User, Device_Info
from Object.HMACValidatorObject import HMACValidatorObject


class AdDepartmentView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        request_dict = request.GET
        return self.validation(request, request_dict, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        request_dict = request.POST
        return self.validation(request, request_dict, operation)

    def validation(self, request, request_dict, operation):
        if operation == 'getUserList':
            return self.get_user_list(request_dict)
        else:
            return JsonResponse({'code': 400, 'msg': 'operation not found'})

    @staticmethod
    def get_user_list(request_dict):
        # 手机号或者邮箱查询
        phone = request_dict.get('phone', '')
        email = request_dict.get('email', '')
        provided_signature = request_dict.get('signature', '')
        pageNo = int(request_dict.get('pageNo', 1))  # 默认第一页
        pageSize = int(request_dict.get('pageSize', 10))  # 默认每页10条
        timestamp = request_dict.get('timestamp', None)

        # 判断时间戳是否存在
        if not all([provided_signature, timestamp]):
            return JsonResponse(status=400, data={"error": "缺少关键参数"})

        # 生成用于签名的数据
        data = f"phone={phone}&email={email}&timestamp={timestamp}"

        # 创建HMAC验证器对象
        validator = HMACValidatorObject()

        # 验证签名是否正确
        is_signature_valid = validator.verify(data, provided_signature)

        # 验证时间戳是否在有效范围内，防止重放攻击
        is_timestamp_valid = validator.validate_timestamp(timestamp)

        # 如果签名和时间戳均有效
        if is_signature_valid and is_timestamp_valid:
            # 获取所有用户查询集
            device_user_qs = Device_User.objects.all()

            # 条件查询：手机号
            if phone:
                device_user_qs = device_user_qs.filter(phone__icontains=phone)

            # 条件查询：邮箱
            if email:
                device_user_qs = device_user_qs.filter(userEmail__icontains=email)

            total = device_user_qs.count()

            if int(pageSize) > 200:
                pageSize = 200

            # 分页处理
            start_index = (pageNo - 1) * pageSize
            end_index = start_index + pageSize
            paginated_users = device_user_qs[start_index:end_index]

            # 使用 prefetch_related 预加载设备信息，避免 N+1 查询
            paginated_users = paginated_users.prefetch_related('device_info_set')

            # 构造返回的用户信息列表
            user_info_list = []
            for user in paginated_users:
                device_list = []
                for device in user.device_info_set.all():
                    device_list.append({
                        "uid": device.UID,
                        "serialNumber": device.serial_number,
                        "addTime": device.data_joined,
                        "isShared": device.isShare,
                        "isPrimaryUser": user.userID == device.vodPrimaryUserID or user.userID == device.primaryUserID,
                    })

                user_info_list.append({
                    "username": user.username,
                    "email": user.userEmail,
                    "phone": user.phone,
                    "registrationTime": user.data_joined,
                    "devices": device_list
                })

            # 构造最终的返回数据
            user_info = {
                "total": total,  # 总数
                "pageNo": pageNo,
                "pageSize": pageSize,
                "users": user_info_list
            }

            return JsonResponse(status=200, data=user_info)

        # 如果签名或时间戳验证失败
        return JsonResponse(status=400, data={"error": "认证失败"})

