"""
系统模块视图
"""
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny
from drf_spectacular.utils import extend_schema

from utils.response import success, error
from apps.admins.authentication import AppJWTAuthentication, AdminJWTAuthentication
from apps.admins.permissions import IsAdminUser
from .models import Feedback, AppVersion
from .serializers import FeedbackSerializer, AppVersionSerializer


@extend_schema(tags=['系统'])
class FeedbackViewSet(viewsets.ViewSet):
    """意见反馈视图集（App端）"""

    authentication_classes = [AppJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def create(self, request):
        """
        提交反馈
        POST /api/v1/feedback/
        """
        serializer = FeedbackSerializer(data=request.data)
        if not serializer.is_valid():
            return error(message=str(serializer.errors))

        serializer.save(user=request.user)
        return success(data=serializer.data, message='反馈已提交，感谢您的意见')


@extend_schema(tags=['系统'])
class VersionViewSet(viewsets.ViewSet):
    """版本检查视图集（App端）"""

    permission_classes = [AllowAny]

    @action(detail=False, methods=['get', 'post'])
    def check(self, request):
        """
        检查版本更新
        GET /api/v1/version/check/?platform=ios&current_version=1.0.0
        POST /api/v1/version/check/  body: {"platform": "ios", "current_version": "1.0.0"}
        """
        if request.method == 'POST':
            platform = request.data.get('platform', 'ios')
            current_version = request.data.get('current_version', '')
        else:
            platform = request.query_params.get('platform', 'ios')
            current_version = request.query_params.get('current_version', '')

        latest = AppVersion.objects.filter(
            platform=platform
        ).order_by('-created_at').first()

        if not latest:
            return success(data={'has_update': False})

        has_update = latest.version != current_version

        return success(data={
            'has_update': has_update,
            'latest_version': AppVersionSerializer(latest).data if has_update else None,
        })


@extend_schema(tags=['管理员-意见反馈'])
class AdminFeedbackViewSet(viewsets.ViewSet):
    """意见反馈管理视图集（管理端）"""

    authentication_classes = [AdminJWTAuthentication]
    permission_classes = [IsAdminUser]

    def list(self, request):
        """
        反馈列表
        GET /api/admin/feedbacks/
        """
        queryset = Feedback.objects.select_related('user').all()

        # 搜索条件
        phone = request.query_params.get('phone')
        if phone:
            queryset = queryset.filter(user__phone__contains=phone)

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        start = (page - 1) * page_size
        end = start + page_size

        total = queryset.count()
        feedbacks = queryset[start:end]

        items = [
            {
                'id': fb.id,
                'user_phone': fb.user.phone,
                'user_nickname': fb.user.nickname,
                'content': fb.content,
                'contact': fb.contact,
                'created_at': fb.created_at,
            }
            for fb in feedbacks
        ]

        return success(data={'total': total, 'items': items})

    def retrieve(self, request, pk=None):
        """
        反馈详情
        GET /api/admin/feedbacks/{id}/
        """
        try:
            fb = Feedback.objects.select_related('user').get(pk=pk)
        except Feedback.DoesNotExist:
            return error(message='反馈不存在')

        return success(data={
            'id': fb.id,
            'user_phone': fb.user.phone,
            'user_nickname': fb.user.nickname,
            'content': fb.content,
            'contact': fb.contact,
            'created_at': fb.created_at,
        })
