"""客服后台资金冻结 API。"""
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from backend.utils import verify_kefu_permission
from jituan.services import fund_freeze_admin as admin_svc

PERM_CFG = 'djcfg001'
PERM_LED = 'djled001'
PERM_RISK = 'djrisk001'


def _auth(request, perm_code: str):
    username = (request.data.get('username') or request.data.get('phone') or '').strip()
    if not username:
        return None, None, Response({'code': 400, 'msg': '缺少username'})
    kefu, permissions = verify_kefu_permission(request, username)
    if kefu is None:
        return None, None, permissions
    codes = set(permissions or [])
    user = getattr(request, 'user', None)
    if getattr(user, 'IsSuperuser', False) or '000001' in codes:
        return kefu, permissions, None
    if perm_code not in codes:
        return None, None, Response({'code': 403, 'msg': f'无权限（需要 {perm_code}）'})
    return kefu, permissions, None


class FundFreezeConfigView(APIView):
    """
    POST /jituan/houtai/fund-freeze-config
    action: get | save
    """
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        kefu, permissions, err = _auth(request, PERM_CFG)
        if err:
            return err
        action = (request.data.get('action') or 'get').strip().lower()
        if action == 'get':
            return Response({'code': 0, 'msg': 'ok', 'data': admin_svc.build_config_payload(request)})
        if action == 'save':
            operator = getattr(getattr(request, 'user', None), 'UserUID', '') or ''
            data, msg = admin_svc.save_config(request, request.data, operator=operator)
            if msg:
                return Response({'code': 400, 'msg': msg})
            return Response({'code': 0, 'msg': '已保存', 'data': data})
        return Response({'code': 400, 'msg': '无效 action'})


class FundFreezeLedgerView(APIView):
    """
    POST /jituan/houtai/fund-freeze-ledger
    action: list | events | unfreeze
    """
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        kefu, permissions, err = _auth(request, PERM_LED)
        if err:
            return err
        action = (request.data.get('action') or 'list').strip().lower()
        if action == 'list':
            return Response({'code': 0, 'msg': 'ok', 'data': admin_svc.list_ledgers(request, request.data)})
        if action == 'events':
            from jituan.services.fund_freeze_admin import _club
            try:
                lid = int(request.data.get('ledger_id') or 0)
            except (TypeError, ValueError):
                return Response({'code': 400, 'msg': 'ledger_id 无效'})
            return Response({
                'code': 0,
                'msg': 'ok',
                'data': {'list': admin_svc.list_unfreeze_events(lid, _club(request))},
            })
        if action == 'unfreeze':
            operator = getattr(getattr(request, 'user', None), 'UserUID', '') or ''
            data, msg = admin_svc.manual_unfreeze(request, request.data, operator=operator)
            if msg:
                return Response({'code': 400, 'msg': msg})
            return Response({'code': 0, 'msg': '解冻成功', 'data': data})
        return Response({'code': 400, 'msg': '无效 action'})


class FundFreezeRiskView(APIView):
    """
    POST /jituan/houtai/fund-freeze-risk
    action: list
    """
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        kefu, permissions, err = _auth(request, PERM_RISK)
        if err:
            return err
        action = (request.data.get('action') or 'list').strip().lower()
        if action == 'list':
            return Response({'code': 0, 'msg': 'ok', 'data': admin_svc.list_risk_users(request, request.data)})
        return Response({'code': 400, 'msg': '无效 action'})
