"""小程序角色协议只读/签署（勾选确认，无手写）。"""
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from jituan.services.club_user import get_user_club_id
from jituan.services import role_agreement as svc


class RoleAgreementCurrentView(APIView):
    """
    POST /yonghu/role-agreement/current
    body: { role, gate?, view? }
    gate: qiangdan|register|tixian|invite — 按卡点判断是否需签
    view: 1/true — 只读查看，不强制签署
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        role = (request.data.get('role') or '').strip().lower()
        if not role:
            return Response({'code': 400, 'msg': '缺少 role', 'data': None})
        gate = (request.data.get('gate') or '').strip().lower()
        view_raw = request.data.get('view') or request.data.get('view_only')
        view_only = view_raw in (True, 'true', '1', 1, 'True')
        club_id = get_user_club_id(request.user) or ''
        data = svc.get_current_for_user(
            club_id, request.user.UserUID, role, gate=gate, view_only=view_only,
        )
        return Response({'code': 200, 'msg': 'ok', 'data': data})


class RoleAgreementMineView(APIView):
    """
    POST /yonghu/role-agreement/mine
    body: { roles?: ['dashou','guanshi'] } — 我的协议列表（按俱乐部）
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        roles = request.data.get('roles')
        if isinstance(roles, str):
            roles = [x.strip() for x in roles.split(',') if x.strip()]
        if not isinstance(roles, list):
            roles = None
        club_id = get_user_club_id(request.user) or ''
        data = svc.list_for_user(club_id, request.user.UserUID, roles=roles)
        return Response({'code': 200, 'msg': 'ok', 'data': data})


class RoleAgreementSignView(APIView):
    """
    POST /yonghu/role-agreement/sign
    JSON: { role, agreed, client_meta? }
    """
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser, FormParser, MultiPartParser]

    def post(self, request):
        role = (request.data.get('role') or '').strip().lower()
        agreed_raw = request.data.get('agreed')
        agreed = agreed_raw in (True, 'true', '1', 1, 'True')
        club_id = get_user_club_id(request.user) or ''

        meta = request.data.get('client_meta')
        if isinstance(meta, str):
            try:
                import json
                meta = json.loads(meta)
            except Exception:
                meta = {'raw': meta}
        if not isinstance(meta, dict):
            meta = {}

        data, msg = svc.sign_agreement(
            club_id,
            request.user.UserUID,
            role,
            client_meta=meta,
            agreed=agreed,
        )
        if msg:
            return Response({'code': 400, 'msg': msg, 'data': None})
        return Response({'code': 200, 'msg': '签署成功', 'data': data})
