from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.urls import reverse

from .models import Announcement
from .forms import AnnouncementForm
from app01.models import Role  # 引入 app01 中的 Role 模型

# 检查是否为管理员
def is_admin(user):
    return user.is_authenticated and user.roles.filter(users=user, caption='管理员').exists()

# 发布公告（仅管理员）
@login_required
def publish_announcement(request):
    if not request.user.is_superuser:
        return render(request, 'announcement/permission_denied.html')
    if request.method == 'POST':
        form = AnnouncementForm(request.POST)
        if form.is_valid():
            announcement = form.save(commit=False)
            announcement.created_by = request.user
            announcement.save()
            return redirect(reverse('announcement:announcement_list'))
    else:
        form = AnnouncementForm()
    return render(request, 'announcement/publish.html', {'form': form})

# 删除公告（仅管理员）
@login_required
def delete_announcement(request, announcement_id):
    if not request.user.is_superuser:
        return render(request, 'announcement/permission_denied.html')
    announcement = get_object_or_404(Announcement, id=announcement_id)
    announcement.status = 'delete'
    announcement.save()
    return redirect('announcement:announcement_list')

# 公告列表（所有用户）
@login_required
def announcement_list(request):
    announcements = Announcement.objects.filter(status='active')
    return render(request, 'announcement/list.html', {'announcements': announcements})