"""打手考试：后台管理 + 小程序接口。"""
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 backend.utils import verify_kefu_permission
from jituan.services.dashou_exam import has_exam_manage_perm

EXAM_PERM_HINT = '无权限（需 dsks666 打手接单考试管理，或 8080a 小程序配置）'


def _check_exam_perm(request, phone):
    kefu, permissions = verify_kefu_permission(request, phone)
    if kefu is None:
        return None, permissions
    if not has_exam_manage_perm(permissions):
        return None, Response({'code': 403, 'msg': EXAM_PERM_HINT})
    return request.user, None


class DashouExamStatusView(APIView):
    """小程序：考试状态（抢单前检查） POST /jituan/dashou-exam/status"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        from jituan.services.dashou_exam import get_exam_status
        data = get_exam_status(request, request.user)
        return Response({'code': 200, 'msg': '成功', 'data': data})


class DashouExamBundleView(APIView):
    """小程序：拉取整套考题（含答案与解析，前端本地判分） POST /jituan/dashou-exam/bundle"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        from jituan.services.dashou_exam import build_exam_bundle
        data, err = build_exam_bundle(request, request.user)
        if err:
            return Response({'code': 400, 'msg': err})
        return Response({'code': 200, 'msg': '成功', 'data': data})


class DashouExamMarkPassedView(APIView):
    """小程序：前端判分通过后登记 POST /jituan/dashou-exam/mark-passed"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        from jituan.services.dashou_exam import mark_exam_passed
        data, err = mark_exam_passed(request, request.user)
        if err:
            return Response({'code': 400, 'msg': err})
        return Response({'code': 200, 'msg': '考试通过', 'data': data})


class DashouExamConfigAdminView(APIView):
    """后台：考试配置 GET/SAVE POST /jituan/houtai/dashou-exam-config"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        phone = (request.data.get('phone') or request.data.get('username') or '').strip()
        if not phone:
            return Response({'code': 401, 'msg': '缺少客服账号'})
        user, err_resp = _check_exam_perm(request, phone)
        if err_resp:
            return err_resp
        action = (request.data.get('action') or 'get').strip()
        from jituan.services.dashou_exam import (
            build_admin_config_payload,
            build_group_exam_overview,
            save_admin_config,
        )
        if action == 'overview':
            data, err = build_group_exam_overview(request)
            if err:
                return Response({'code': 400, 'msg': err})
            return Response({'code': 0, 'data': data})
        if action == 'save':
            data, err = save_admin_config(request, user, request.data)
            if err:
                return Response({'code': 400, 'msg': err})
            return Response({'code': 0, 'msg': '保存成功', 'data': {'config': data}})
        payload = build_admin_config_payload(request, user, request.data)
        return Response({'code': 0, 'data': payload})


class DashouExamQuestionListView(APIView):
    """后台：题库列表 POST /jituan/houtai/dashou-exam-question-list"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        phone = (request.data.get('phone') or request.data.get('username') or '').strip()
        if not phone:
            return Response({'code': 401, 'msg': '缺少客服账号'})
        user, err_resp = _check_exam_perm(request, phone)
        if err_resp:
            return err_resp
        from jituan.services.dashou_exam import list_admin_questions
        return Response({'code': 0, 'data': list_admin_questions(request, user, request.data)})


class DashouExamQuestionManageView(APIView):
    """后台：题目增删改 POST /jituan/houtai/dashou-exam-question-manage"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        phone = (request.data.get('phone') or request.data.get('username') or '').strip()
        if not phone:
            return Response({'code': 401, 'msg': '缺少客服账号'})
        user, err_resp = _check_exam_perm(request, phone)
        if err_resp:
            return err_resp
        action = (request.data.get('action') or '').strip()
        qid = request.data.get('question_id') or request.data.get('id')
        from jituan.services.dashou_exam import (
            create_question,
            delete_question,
            update_question,
        )
        if action == 'create':
            data, err = create_question(request, user, request.data)
        elif action == 'update':
            if not qid:
                return Response({'code': 400, 'msg': '缺少题目ID'})
            data, err = update_question(request, user, int(qid), request.data)
        elif action == 'delete':
            if not qid:
                return Response({'code': 400, 'msg': '缺少题目ID'})
            data, err = delete_question(request, user, int(qid), request.data)
        else:
            return Response({'code': 400, 'msg': '无效 action'})
        if err:
            return Response({'code': 400, 'msg': err})
        return Response({'code': 0, 'msg': '成功', 'data': data})


class DashouExamImageManageView(APIView):
    """后台：题目图片 POST /jituan/houtai/dashou-exam-image-manage"""
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):
        phone = (request.data.get('phone') or request.data.get('username') or '').strip()
        if not phone:
            return Response({'code': 401, 'msg': '缺少客服账号'})
        user, err_resp = _check_exam_perm(request, phone)
        if err_resp:
            return err_resp
        action = (request.data.get('action') or 'upload').strip()
        from jituan.services.dashou_exam import delete_question_image, upload_question_image
        if action == 'delete':
            image_id = request.data.get('image_id')
            if not image_id:
                return Response({'code': 400, 'msg': '缺少 image_id'})
            data, err = delete_question_image(request, user, int(image_id), request.data)
        else:
            qid = request.data.get('question_id')
            file_obj = request.FILES.get('file')
            if not qid or not file_obj:
                return Response({'code': 400, 'msg': '缺少题目或图片'})
            data, err = upload_question_image(request, user, int(qid), file_obj, request.data)
        if err:
            return Response({'code': 400, 'msg': err})
        return Response({'code': 0, 'msg': '成功', 'data': data})
