"""清理重复任职 + 可选为星之界创建组长邀请链。"""
import time

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

from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import Club, ClubHuiyuanPrice
from jituan.services.admin_assignments import dedupe_active_assignments
from jituan.services.club_user import ensure_user_club_id
from users.business_models import User
from users.models import UserGuanshi, UserZuzhang


class Command(BaseCommand):
    help = '清理重复 admin_assignment；可选为 xzj 用户创建组长并输出邀请码'

    def add_arguments(self, parser):
        parser.add_argument('--dedupe-only', action='store_true', help='只清理重复有效任职')
        parser.add_argument('--club-id', default='xzj', help='目标俱乐部')
        parser.add_argument('--phone', type=str, default='', help='用户手机号（须已微信登录过）')
        parser.add_argument('--make-zuzhang', action='store_true', help='将该用户设为 xzj 组长并生成邀请码')

    def handle(self, *args, **options):
        removed = dedupe_active_assignments()
        self.stdout.write(self.style.SUCCESS(f'已停用重复任职 {removed} 条'))

        if options.get('dedupe_only'):
            return

        club_id = (options.get('club_id') or 'xzj').strip()
        if not Club.query.filter(club_id=club_id).exists():
            raise CommandError(f'俱乐部 {club_id} 不存在')

        price_cnt = ClubHuiyuanPrice.query.filter(club_id=club_id).count()
        self.stdout.write(f'club_huiyuan_price({club_id}) 共 {price_cnt} 条（创建俱乐部时从 xq 复制，价相同需后台单独改）')

        phone = (options.get('phone') or '').strip()
        if options.get('make_zuzhang'):
            if not phone:
                raise CommandError('请指定 --phone')
            user = User.query.filter(Phone=phone).first()
            if not user:
                raise CommandError(f'未找到手机号 {phone}，请先在星之界小程序登录一次')
            ensure_user_club_id(user, club_id)
            user.ClubID = club_id
            user.save(update_fields=['ClubID'])

            if hasattr(user, 'ZuzhangProfile'):
                z = user.ZuzhangProfile
                self.stdout.write(self.style.SUCCESS(
                    f'已是组长，邀请码: {z.yaoqingma}（管事注册用组长码）'
                ))
                return

            yaoqingma = f'ZZ{int(time.time())}{str(user.UserUID)[-4:]}'
            with transaction.atomic():
                UserZuzhang.query.create(
                    user=user,
                    yaoqingma=yaoqingma,
                    zhuangtai=1,
                )
            self.stdout.write(self.style.SUCCESS(
                f'已创建 xzj 组长 UserUID={user.UserUID}，组长邀请码: {yaoqingma}\n'
                f'管事注册: 小程序内 guanshizhuce，inviteCode={yaoqingma}'
            ))
        else:
            self.stdout.write(
                '查邀请码 SQL（表名 User 大写）：\n'
                f"SELECT u.UserUID,u.Phone,z.yaoqingma FROM `User` u "
                f"JOIN user_zuzhang z ON z.UserUUID=u.UserUUID WHERE u.ClubID='{club_id}';\n"
                f"SELECT u.UserUID,u.Phone,g.yaoqingma FROM `User` u "
                f"JOIN user_guanshi g ON g.UserUUID=u.UserUUID WHERE u.ClubID='{club_id}';\n"
                '创建组长: python manage.py bootstrap_xzj_invite --phone 手机号 --make-zuzhang'
            )
