"""身份装饰标签：后台管理 + 小程序 my-tags。"""
import json

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.models import IdentityTag, IdentityTagBind
from jituan.services.club_context import resolve_effective_club_id
from jituan.services.display_config import list_response_meta
from jituan.services.identity_tag import (
    SHENFEN_DASHOU,
    SHENFEN_GUANSHI,
    SHENFEN_SHANGJIA,
    SHENFEN_ZUZHANG,
    format_tag_item,
    get_my_identity_tags,
)
from users.business_models import User

IDENTITY_TAG_PERM = 'sfbq666'

SHENFEN_LABELS = {
    SHENFEN_DASHOU: '打手',
    SHENFEN_GUANSHI: '管事',
    SHENFEN_SHANGJIA: '商家',
    SHENFEN_ZUZHANG: '组长',
}


def _build_texiao_json(color, flash_enabled):
    return json.dumps({
        'color': color or '#000000',
        'flash': bool(flash_enabled),
    }, ensure_ascii=False)


class IdentityTagMyTagsView(APIView):
    """小程序：当前用户各身份装饰标签 POST /jituan/identity-tag/my-tags"""
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    def post(self, request):
        user = request.user
        club_id = resolve_effective_club_id(request, user)
        data = get_my_identity_tags(user, club_id)
        return Response({'code': 200, 'msg': '成功', 'data': data})


class IdentityTagListView(APIView):
    """后台：标签定义列表 POST /jituan/houtai/identity-tag/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': '缺少客服账号'})
        kefu, permissions = verify_kefu_permission(request, phone)
        if kefu is None:
            return permissions
        if IDENTITY_TAG_PERM not in permissions:
            return Response({'code': 403, 'msg': '无权限管理身份装饰标签'})

        club_id = resolve_effective_club_id(request, request.user)
        rows = IdentityTag.query.filter(club_id=club_id).order_by('sort_order', 'id')
        return Response({
            'code': 0,
            'data': {
                'list': [
                    {
                        'id': r.id,
                        'name': r.name,
                        'color': r.color,
                        'flash_enabled': r.flash_enabled,
                        'sort_order': r.sort_order,
                        'status': r.status,
                    }
                    for r in rows
                ],
                **list_response_meta(request),
            },
        })


class IdentityTagManageView(APIView):
    """后台：新增/编辑/删除标签 POST /jituan/houtai/identity-tag/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': '缺少客服账号'})
        kefu, permissions = verify_kefu_permission(request, phone)
        if kefu is None:
            return permissions
        if IDENTITY_TAG_PERM not in permissions:
            return Response({'code': 403, 'msg': '无权限管理身份装饰标签'})

        club_id = resolve_effective_club_id(request, request.user)
        action = (request.data.get('action') or '').strip()

        if action == 'delete':
            tag_id = request.data.get('id')
            if not tag_id:
                return Response({'code': 400, 'msg': '缺少标签ID'})
            IdentityTag.query.filter(id=tag_id, club_id=club_id).delete()
            return Response({'code': 0, 'msg': '删除成功'})

        name = (request.data.get('name') or '').strip()
        if not name:
            return Response({'code': 400, 'msg': '标签名不能为空'})
        color = (request.data.get('color') or '#000000').strip()
        flash_enabled = bool(request.data.get('flash_enabled', False))
        sort_order = int(request.data.get('sort_order', 0) or 0)
        status = int(request.data.get('status', 1) or 1)
        texiao_json = _build_texiao_json(color, flash_enabled)

        tag_id = request.data.get('id')
        if tag_id:
            row = IdentityTag.query.filter(id=tag_id, club_id=club_id).first()
            if not row:
                return Response({'code': 404, 'msg': '标签不存在'})
            row.name = name
            row.color = color
            row.flash_enabled = flash_enabled
            row.sort_order = sort_order
            row.status = status
            row.texiao_json = texiao_json
            row.save()
            return Response({'code': 0, 'msg': '更新成功', 'data': {'id': row.id}})

        row = IdentityTag.query.create(
            club_id=club_id,
            name=name,
            color=color,
            flash_enabled=flash_enabled,
            sort_order=sort_order,
            status=status,
            texiao_json=texiao_json,
        )
        return Response({'code': 0, 'msg': '创建成功', 'data': {'id': row.id}})


class IdentityTagBindListView(APIView):
    """后台：绑定列表 POST /jituan/houtai/identity-tag/bind-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': '缺少客服账号'})
        kefu, permissions = verify_kefu_permission(request, phone)
        if kefu is None:
            return permissions
        if IDENTITY_TAG_PERM not in permissions:
            return Response({'code': 403, 'msg': '无权限管理身份装饰标签'})

        club_id = resolve_effective_club_id(request, request.user)
        keyword = (request.data.get('keyword') or '').strip()
        shenfen = request.data.get('shenfen')
        page = max(1, int(request.data.get('page', 1) or 1))
        page_size = min(50, max(1, int(request.data.get('page_size', 20) or 20)))

        qs = IdentityTagBind.query.filter(club_id=club_id).select_related('tag')
        if shenfen is not None and str(shenfen) != '':
            qs = qs.filter(shenfen=int(shenfen))
        if keyword:
            qs = qs.filter(yonghuid__icontains=keyword)

        total = qs.count()
        rows = qs.order_by('-id')[(page - 1) * page_size:page * page_size]
        items = []
        for b in rows:
            items.append({
                'id': b.id,
                'yonghuid': b.yonghuid,
                'shenfen': b.shenfen,
                'shenfen_label': SHENFEN_LABELS.get(b.shenfen, str(b.shenfen)),
                'tag_id': b.tag_id,
                'tag_name': b.tag.name if b.tag else '',
            })
        return Response({
            'code': 0,
            'data': {
                'list': items,
                'total': total,
                'page': page,
                'page_size': page_size,
                **list_response_meta(request),
            },
        })


class IdentityTagBindView(APIView):
    """后台：绑定/解绑 POST /jituan/houtai/identity-tag/bind"""
    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': '缺少客服账号'})
        kefu, permissions = verify_kefu_permission(request, phone)
        if kefu is None:
            return permissions
        if IDENTITY_TAG_PERM not in permissions:
            return Response({'code': 403, 'msg': '无权限管理身份装饰标签'})

        club_id = resolve_effective_club_id(request, request.user)
        action = (request.data.get('action') or 'bind').strip()

        if action == 'unbind':
            bind_id = request.data.get('id')
            if not bind_id:
                return Response({'code': 400, 'msg': '缺少绑定ID'})
            IdentityTagBind.query.filter(id=bind_id, club_id=club_id).delete()
            return Response({'code': 0, 'msg': '解绑成功'})

        yonghuid = (request.data.get('yonghuid') or '').strip()
        tag_id = request.data.get('tag_id')
        shenfen = request.data.get('shenfen')
        if not yonghuid or not tag_id or shenfen is None:
            return Response({'code': 400, 'msg': '参数不完整'})
        if not User.query.filter(UserUID=yonghuid).exists():
            return Response({'code': 404, 'msg': '用户不存在'})
        tag = IdentityTag.query.filter(id=tag_id, club_id=club_id, status=1).first()
        if not tag:
            return Response({'code': 404, 'msg': '标签不存在'})

        IdentityTagBind.query.get_or_create(
            club_id=club_id,
            yonghuid=yonghuid,
            shenfen=int(shenfen),
            tag=tag,
        )
        return Response({'code': 0, 'msg': '绑定成功'})
