"""假单后台管理 API。"""
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from backend.view import verify_kefu_permission

PRODUCT_PERMS = ('2200a',)


def _check_product_perm(request, phone):
    kefu, permissions = verify_kefu_permission(request, phone)
    if kefu is None:
        return None, permissions
    if not any(p in permissions for p in PRODUCT_PERMS):
        return None, Response({'code': 403, 'msg': '无商品管理权限'})
    return kefu, None


class FakeGrabOrderListView(APIView):
    """POST /jituan/houtai/fake-grab-order-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': '缺少客服账号'})
        _, err = _check_product_perm(request, phone)
        if err:
            return err

        from jituan.services.fake_grab_order_admin import build_fake_order_list_payload

        payload = build_fake_order_list_payload(
            request,
            leixing_id=request.data.get('leixing_id'),
            page=request.data.get('page', 1),
            page_size=request.data.get('page_size', 20),
        )
        return Response({'code': 0, 'data': payload})


class FakeGrabOrderManageView(APIView):
    """POST /jituan/houtai/fake-grab-order-manage  action=create|update|delete"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        phone = (request.data.get('phone') or request.data.get('username') or '').strip()
        action = (request.data.get('action') or '').strip().lower()
        if not phone:
            return Response({'code': 401, 'msg': '缺少客服账号'})
        _, err = _check_product_perm(request, phone)
        if err:
            return err

        from jituan.services.fake_grab_order_admin import (
            create_fake_order,
            delete_fake_order,
            set_fake_grab_enabled,
            set_fake_yajin_threshold,
            update_fake_order,
        )

        if action == 'create':
            data, err_msg = create_fake_order(request, request.data)
            if err_msg:
                return Response({'code': 400, 'msg': err_msg})
            return Response({'code': 0, 'msg': '创建成功', 'data': data})

        if action == 'update':
            order_id = request.data.get('order_id') or request.data.get('dingdan_id')
            data, err_msg = update_fake_order(request, order_id, request.data)
            if err_msg:
                return Response({'code': 400, 'msg': err_msg})
            return Response({'code': 0, 'msg': '更新成功', 'data': data})

        if action == 'delete':
            order_id = request.data.get('order_id') or request.data.get('dingdan_id')
            data, err_msg = delete_fake_order(request, order_id)
            if err_msg:
                return Response({'code': 400, 'msg': err_msg})
            return Response({'code': 0, 'msg': '已删除', 'data': data})

        if action in ('set_enabled', 'enable', 'disable'):
            if action == 'enable':
                enabled = True
            elif action == 'disable':
                enabled = False
            else:
                raw = request.data.get('enabled', request.data.get('fake_grab_enabled'))
                if isinstance(raw, str):
                    enabled = raw.strip().lower() in ('1', 'true', 'yes', 'on')
                else:
                    enabled = bool(raw)
            data, err_msg = set_fake_grab_enabled(request, enabled)
            if err_msg:
                return Response({'code': 400, 'msg': err_msg})
            return Response({
                'code': 0,
                'msg': '假单功能已开启' if data.get('fake_grab_enabled') else '假单功能已关闭',
                'data': data,
            })

        if action in ('set_yajin_threshold', 'set_threshold'):
            raw = request.data.get('threshold', request.data.get('fake_yajin_hide_threshold'))
            data, err_msg = set_fake_yajin_threshold(request, raw)
            if err_msg:
                return Response({'code': 400, 'msg': err_msg})
            return Response({
                'code': 0,
                'msg': f'押金过滤门槛已设为 ≥ {data.get("fake_yajin_hide_threshold")}',
                'data': data,
            })

        return Response({'code': 400, 'msg': '无效的 action'})


class FakeGrabOrderAvatarUploadView(APIView):
    """POST /jituan/houtai/fake-grab-order-avatar"""
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):
        phone = (request.data.get('phone') or request.data.get('username') or '').strip()
        order_id = (request.data.get('order_id') or request.data.get('dingdan_id') or '').strip()
        file_obj = request.FILES.get('file')
        if not phone:
            return Response({'code': 401, 'msg': '缺少客服账号'})
        _, err = _check_product_perm(request, phone)
        if err:
            return err

        from jituan.services.fake_grab_order_admin import upload_fake_order_avatar

        data, err_msg = upload_fake_order_avatar(request, order_id, file_obj)
        if err_msg:
            return Response({'code': 400, 'msg': err_msg})
        return Response({'code': 0, 'msg': '上传成功', 'data': data})
