"""写入角色协议权限码，并可按俱乐部挂到角色。

权限码：
  xycfg001  角色协议配置

用法：
  python manage.py seed_role_agreement_perm
  python manage.py seed_role_agreement_perm --club-id lxs --role-name 管理员
"""
import uuid

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

from gvsdsdk.models import Permission, Role, RolePermission

from jituan.models import Club

PERMS = [
    ('xycfg001', '角色协议配置', '配置打手/管事/组长用户协议并发布版本', '小程序配置'),
]


class Command(BaseCommand):
    help = '写入角色协议权限码，并按俱乐部挂到角色'

    def add_arguments(self, parser):
        parser.add_argument('--club-id', default='', help='仅处理该俱乐部')
        parser.add_argument('--all-clubs', action='store_true')
        parser.add_argument('--role-name', default='', help='角色名；空则只确保权限码')
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        club_id = (options.get('club_id') or '').strip()
        all_clubs = options.get('all_clubs')
        role_name = (options.get('role_name') or '').strip()

        sample = Permission.objects.filter(PermStatus=1).first()
        tenant_uuid = sample.TenantUUID if sample else uuid.UUID(
            '00000000-0000-0000-0000-000000000001'
        ).bytes

        perm_objs = []
        for code, name, desc, cat in PERMS:
            perm = Permission.objects.filter(PermCode=code).first()
            if perm:
                self.stdout.write(f'  权限码已存在: {code}')
                if not dry_run:
                    changed = False
                    if perm.PermName != name:
                        perm.PermName = name
                        changed = True
                    if (perm.PermDesc or '') != desc:
                        perm.PermDesc = desc
                        changed = True
                    if (perm.PermCategory or '') != cat:
                        perm.PermCategory = cat
                        changed = True
                    if changed:
                        perm.save(update_fields=['PermName', 'PermDesc', 'PermCategory'])
            else:
                if dry_run:
                    self.stdout.write(f'would create perm {code}')
                else:
                    perm = Permission.objects.create(
                        PermUUID=uuid.uuid4().bytes,
                        TenantUUID=tenant_uuid,
                        PermCode=code,
                        PermName=name,
                        PermDesc=desc,
                        PermCategory=cat,
                        PermStatus=1,
                        CreateTime=timezone.now(),
                        UpdateTime=timezone.now(),
                    )
                    self.stdout.write(self.style.SUCCESS(f'  已创建权限码: {code}'))
            if perm:
                perm_objs.append(perm)

        if not role_name:
            self.stdout.write('未指定 --role-name，跳过挂角色')
            return

        clubs = []
        if all_clubs:
            clubs = list(Club.query.filter(status=1).values_list('club_id', flat=True))
        elif club_id:
            clubs = [club_id]
        else:
            self.stdout.write(self.style.WARNING('请指定 --club-id 或 --all-clubs'))
            return

        with transaction.atomic():
            for cid in clubs:
                roles = Role.objects.filter(RoleName=role_name, ClubID=cid, RoleStatus=1)
                if not roles.exists():
                    roles = Role.objects.filter(RoleName=role_name, RoleStatus=1)
                    roles = [r for r in roles if (getattr(r, 'ClubID', None) or '') == cid]
                for role in roles:
                    for perm in perm_objs:
                        exists = RolePermission.objects.filter(
                            RoleUUID=role.RoleUUID, PermUUID=perm.PermUUID,
                        ).exists()
                        if exists:
                            self.stdout.write(f'  已挂: {cid} {role_name} <- {perm.PermCode}')
                            continue
                        if dry_run:
                            self.stdout.write(f'would link {cid} {role_name} <- {perm.PermCode}')
                        else:
                            RolePermission.objects.create(
                                RoleUUID=role.RoleUUID,
                                PermUUID=perm.PermUUID,
                                CreateTime=timezone.now(),
                            )
                            self.stdout.write(self.style.SUCCESS(
                                f'  已挂: {cid} {role_name} <- {perm.PermCode}'
                            ))
