"""将指定手机号设为超级管理员（功能权限 + 集团视图）。"""
import uuid

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone

from gvsdsdk.models import Role, Permission, RolePermission, UserRole
from jituan.constants import SUPER_ADMIN_PHONES
from users.business_models import User


class Command(BaseCommand):
    help = '将 SUPER_ADMIN_PHONES 设为 IsSuperuser，并绑定「管理员」角色（含 000001）'

    def handle(self, *args, **options):
        admin_role = Role.objects.filter(RoleName='管理员', RoleStatus=1).first()
        super_perm = Permission.objects.filter(PermCode='000001', PermStatus=1).first()
        if admin_role and super_perm:
            if not RolePermission.objects.filter(
                RoleUUID=admin_role.RoleUUID, PermUUID=super_perm.PermUUID,
            ).exists():
                RolePermission.objects.create(
                    RolePermUUID=uuid.uuid4().bytes,
                    RoleUUID=admin_role.RoleUUID,
                    PermUUID=super_perm.PermUUID,
                    CreateTime=timezone.now(),
                )
                self.stdout.write(self.style.SUCCESS('已为「管理员」角色绑定 000001 权限'))

        updated = 0
        for phone in SUPER_ADMIN_PHONES:
            users = list(User.query.filter(Phone=phone))
            if not users:
                self.stdout.write(self.style.WARNING(f'未找到手机号 {phone}'))
                continue
            for user in users:
                with transaction.atomic():
                    user.IsSuperuser = True
                    user.IsStaff = True
                    user.save(update_fields=['IsSuperuser', 'IsStaff'])
                    if admin_role and not UserRole.objects.filter(
                        UserUUID=user.UserUUID, RoleUUID=admin_role.RoleUUID,
                    ).exists():
                        UserRole.objects.create(
                            UserRoleUUID=uuid.uuid4().bytes,
                            UserUUID=user.UserUUID,
                            RoleUUID=admin_role.RoleUUID,
                            CreateTime=timezone.now(),
                        )
                updated += 1
                self.stdout.write(self.style.SUCCESS(
                    f'已设置超管: {phone} (UserUID={user.UserUID})'
                ))
        self.stdout.write(self.style.SUCCESS(f'完成，更新 {updated} 个账号'))
