"""子客服专用：派单模板 / 链接（独立路径；读模板用 merchant_id，写模板需 template_manage）。"""
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from config.views import (
    ShangjiaTianjiaMobanView,
    ShangjiaGengxinMobanView,
    ShangjiaShanchuMobanView,
)
from merchant_ops.helpers import proxy_as_merchant_user
from merchant_ops.services.authz import (
    StaffAuthError, require_active_staff_member, member_has_perm, staff_order_read_perm,
)
from merchant_ops.services.template_query import list_merchant_templates
from merchant_ops.services.link import staff_generate_link, staff_list_links
from merchant_ops.services.audit import audit_staff
from merchant_ops.views_manage import _err


def _require_staff(request):
    return require_active_staff_member(request.user)


def _can_read_templates(member):
    """派单/看单/管模板任一权限即可读模板列表。"""
    return staff_order_read_perm(member) or member_has_perm(member, 'template_manage')


class StaffTemplateListView(APIView):
    """读商家全部模板（UserID=merchant_id），有 order_dispatch 即可。"""

    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            member = _require_staff(request)
            if not _can_read_templates(member):
                raise StaffAuthError(403, '无权限查看模板')
            payload, http_status = list_merchant_templates(member.merchant_id, request.data)
            return Response(payload, status=http_status)
        except Exception as e:
            return _err(e)


class StaffTemplateCreateView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            member = _require_staff(request)
            if not member_has_perm(member, 'template_manage'):
                raise StaffAuthError(403, '无权限添加模板')
            resp = proxy_as_merchant_user(request, member, ShangjiaTianjiaMobanView, 'template_manage')
            if resp.status_code == 200 and resp.data.get('code') in (0, 200):
                audit_staff(member, 'TEMPLATE_CREATE', request,
                            resource_id=(resp.data.get('data') or {}).get('id', ''))
            return resp
        except Exception as e:
            return _err(e)


class StaffTemplateUpdateView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            member = _require_staff(request)
            if not member_has_perm(member, 'template_manage'):
                raise StaffAuthError(403, '无权限修改模板')
            moban_id = request.data.get('mobanId') or request.data.get('id') or ''
            resp = proxy_as_merchant_user(request, member, ShangjiaGengxinMobanView, 'template_manage')
            if resp.status_code == 200 and resp.data.get('code') in (0, 200):
                audit_staff(member, 'TEMPLATE_UPDATE', request, resource_id=str(moban_id))
            return resp
        except Exception as e:
            return _err(e)


class StaffTemplateDeleteView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            member = _require_staff(request)
            if not member_has_perm(member, 'template_manage'):
                raise StaffAuthError(403, '无权限删除模板')
            moban_id = request.data.get('mobanId') or request.data.get('id') or ''
            resp = proxy_as_merchant_user(request, member, ShangjiaShanchuMobanView, 'template_manage')
            if resp.status_code == 200 and resp.data.get('code') in (0, 200):
                audit_staff(member, 'TEMPLATE_DELETE', request, resource_id=str(moban_id))
            return resp
        except Exception as e:
            return _err(e)


class StaffLinkGenerateView(APIView):
    """POST /yonghu/merchant-staff/link/generate — 子客服独立实现，标记操作人身份。"""

    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            member = _require_staff(request)
            if not member_has_perm(member, 'order_dispatch'):
                raise StaffAuthError(403, '无派单/生成链接权限')
            ok, payload = staff_generate_link(member, request.user, request.data)
            if ok:
                audit_staff(
                    member, 'LINK_GENERATE', request,
                    resource_id=payload.get('data', {}).get('dingdanId'),
                    amount=payload.get('data', {}).get('jiage'),
                    remark=f"{member.role.role_name}:{member.display_name or member.staff_user_id}",
                )
            code = payload.get('code', 500)
            return Response(payload, status=status.HTTP_200_OK if code in (0, 200) else status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return _err(e)


class StaffLinkListView(APIView):
    """POST /yonghu/merchant-staff/link/list — 子客服链接列表，含操作人身份。"""

    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            member = _require_staff(request)
            if not member_has_perm(member, 'order_dispatch'):
                raise StaffAuthError(403, '无权限')
            ok, payload = staff_list_links(member, request.data)
            code = payload.get('code', 500)
            return Response(payload, status=status.HTTP_200_OK if code in (0, 200) else status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return _err(e)
