"""小程序：管事更换组长。"""
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from users.services.change_leader import build_change_leader_info, change_leader_by_invite


class GuanshiChangeZuzhangInfoView(APIView):
    """
    POST /yonghu/gs_huan_zuzhang_info
    当前组长 + 剩余更换次数
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        result = build_change_leader_info(request, request.user)
        if not result.get('ok'):
            return Response({
                'code': result.get('code', 403),
                'msg': result.get('msg', '失败'),
                'data': None,
            })
        return Response({
            'code': 200,
            'msg': result.get('msg', 'ok'),
            'data': result.get('data'),
        })


class GuanshiChangeZuzhangView(APIView):
    """
    POST /yonghu/gs_huan_zuzhang
    body: { inviteCode: 组长邀请码 }
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        invite = (
            request.data.get('inviteCode')
            or request.data.get('yaoqingma')
            or ''
        )
        result = change_leader_by_invite(
            request,
            request.user,
            invite,
            source='miniapp',
            operator=getattr(request.user, 'UserUID', '') or '',
        )
        if not result.get('ok'):
            return Response({
                'code': result.get('code', 400),
                'msg': result.get('msg', '更换失败'),
                'data': None,
            })
        return Response({
            'code': 200,
            'msg': result.get('msg', '更换组长成功'),
            'data': result.get('data'),
        })
