"""为后台客服账号初始化 admin_assignment（数据范围，非功能权限）。"""
import logging

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from jituan.constants import CLUB_ID_DEFAULT, DATA_SCOPE_SINGLE, ADMIN_ROLE_LABELS
from jituan.models import AdminAssignment
from users.business_models import User

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = '为 kefu 账号创建默认子公司任职（club=xq, CLUB_ADMIN）；超管可不建 assignment'

    def add_arguments(self, parser):
        parser.add_argument(
            '--club-id', default=CLUB_ID_DEFAULT, help='目标俱乐部 ID，默认 xq',
        )
        parser.add_argument(
            '--role-code', default='CLUB_ADMIN', help='任职角色码（仅展示标签，不控制菜单功能权限）',
        )
        parser.add_argument(
            '--phone', type=str, default='', help='仅给该手机号客服添加任职（推荐）',
        )
        parser.add_argument(
            '--all-kefu',
            action='store_true',
            help='给全部客服账号批量添加（慎用，会扫所有有 KefuProfile 的账号）',
        )
        parser.add_argument(
            '--dry-run', action='store_true', help='只打印不写入',
        )

    def handle(self, *args, **options):
        club_id = options['club_id']
        role_code = options['role_code']
        dry_run = options['dry_run']
        target_phone = (options.get('phone') or '').strip()
        all_kefu = options.get('all_kefu')

        if not target_phone and not all_kefu:
            raise CommandError(
                '请指定 --phone 13800138000（只配一个人）或 --all-kefu（批量全部客服）。'
                '默认不会自动给所有人加任职。'
            )

        if target_phone:
            target = User.query.filter(Phone=target_phone).first()
            if not target:
                raise CommandError(f'未找到手机号 {target_phone}')
            kefu_users = [target]
        else:
            kefu_users = list(
                User.query.filter(KefuProfile__isnull=False).select_related('KefuProfile')
            )
        created = 0
        skipped = 0

        with transaction.atomic():
            for u in kefu_users:
                if u.IsSuperuser:
                    skipped += 1
                    continue
                exists = AdminAssignment.query.filter(
                    yonghuid=u.UserUID, club_id=club_id, role_code=role_code,
                ).exists()
                if exists:
                    skipped += 1
                    continue
                if dry_run:
                    self.stdout.write(f'would assign {u.UserUID} -> {club_id} {role_code}')
                    created += 1
                    continue
                AdminAssignment.query.create(
                    yonghuid=u.UserUID,
                    club_id=club_id,
                    role_code=role_code,
                    data_scope=DATA_SCOPE_SINGLE,
                    is_primary=True,
                    status=1,
                )
                created += 1

        label = ADMIN_ROLE_LABELS.get(role_code, role_code)
        self.stdout.write(self.style.SUCCESS(
            f'完成：新建 {created} 条，跳过 {skipped} 条（club={club_id}, role={label}）'
        ))
