from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView
from django.db.models import Q, Sum
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from .models import Artwork, About, Comment
from .forms import CommentForm


def index(request):
    """首页视图 - 展示所有作品"""
    artworks = Artwork.objects.all().order_by('order', '-created_at')
    total_views = artworks.aggregate(total=Sum('view_count'))['total'] or 0
    context = {
        'artworks': artworks,
        'total_views': total_views,
        'page_title': 'YITAO-REN GALLERY',
    }
    return render(request, 'gallery/index.html', context)


class ArtworkDetailView(DetailView):
    """作品详情页视图"""
    model = Artwork
    template_name = 'gallery/detail.html'
    context_object_name = 'artwork'
    slug_field = 'slug'
    slug_url_kwarg = 'slug'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        artwork = self.object

        # 增加浏览次数
        artwork.increment_view_count()

        # 获取评论（仅激活状态）
        comments = Comment.objects.filter(
            artwork=artwork,
            is_active=True
        ).select_related('user').order_by('-created_at')

        # 分页处理
        paginator = Paginator(comments, 10)  # 每页10条
        page_number = self.request.GET.get('page')
        page_obj = paginator.get_page(page_number)

        context['comments'] = page_obj
        context['comment_form'] = CommentForm() if self.request.user.is_authenticated else None
        context['comment_count'] = comments.count()

        # 获取相邻作品
        artworks = Artwork.objects.all().order_by('order', '-created_at')
        current_index = list(artworks).index(artwork)

        # 前一个作品
        if current_index > 0:
            context['prev_artwork'] = artworks[current_index - 1]
        else:
            context['prev_artwork'] = None

        # 后一个作品
        if current_index < len(artworks) - 1:
            context['next_artwork'] = artworks[current_index + 1]
        else:
            context['next_artwork'] = None

        # 获取相关作品（同分类）
        if artwork.category:
            related_artworks = artwork.category.artwork_set.exclude(
                id=artwork.id
            ).order_by('order', '-created_at')[:4]
            context['related_artworks'] = related_artworks
        else:
            context['related_artworks'] = Artwork.objects.none()

        context['page_title'] = f'{artwork.title} - YITAO-REN GALLERY'
        return context


def about(request):
    """关于页面视图"""
    about_page = About.objects.first()
    context = {
        'about': about_page,
        'page_title': '关于 - YITAO-REN GALLERY',
    }
    return render(request, 'gallery/about.html', context)


def search(request):
    """搜索视图"""
    query = request.GET.get('q', '')
    artworks = Artwork.objects.all()

    if query:
        artworks = artworks.filter(
            Q(title__icontains=query) |
            Q(description__icontains=query) |
            Q(category__name__icontains=query)
        )

    context = {
        'artworks': artworks,
        'query': query,
        'page_title': f'搜索: {query} - YITAO-REN GALLERY',
    }
    return render(request, 'gallery/search.html', context)


def category_view(request, slug):
    """分类视图"""
    from .models import Category
    category = get_object_or_404(Category, slug=slug)
    artworks = Artwork.objects.filter(category=category).order_by('order', '-created_at')

    context = {
        'category': category,
        'artworks': artworks,
        'page_title': f'{category.name} - YITAO-REN GALLERY',
    }
    return render(request, 'gallery/category.html', context)


def login_view(request):
    """处理用户登录"""
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, '登录成功！')
            return redirect('index')
        else:
            messages.error(request, '用户名或密码错误')

    return render(request, 'gallery/auth/login.html')


@login_required
def logout_view(request):
    """处理用户登出"""
    logout(request)
    messages.success(request, '已成功登出')
    return redirect('index')


@login_required
def add_comment(request, artwork_slug):
    """添加评论到指定作品"""
    artwork = get_object_or_404(Artwork, slug=artwork_slug)

    if request.method == 'POST':
        form = CommentForm(request.POST, request.FILES)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.artwork = artwork
            comment.user = request.user
            comment.save()
            messages.success(request, '评论已发布')
        else:
            for error in form.errors.values():
                messages.error(request, error)

    return redirect('artwork_detail', slug=artwork_slug)


@login_required
def delete_comment(request, pk):
    """删除评论（软删除）"""
    comment = get_object_or_404(Comment, pk=pk, user=request.user)
    comment.is_active = False
    comment.save()
    messages.success(request, '评论已删除')
    return redirect('artwork_detail', slug=comment.artwork.slug)