from django.shortcuts import render, HttpResponse, redirect
from django.forms import ModelForm
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger  # 分页组件
from app01 import models

# Create your views here.
def index(request):
    return render(request, 'homepage.html')

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html', )

    if request.method == 'POST':
        role = request.POST.get('role')
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')

        if role == '0': # 如果身份是学生
            result = models.StuInfo.objects.filter(username=username, password=pwd)

            if result.exists():
                return redirect('student_index', sid=result.first().id)
            else:
                return HttpResponse('failed')
            
        elif role == '1': # 如果身份是管理员
            result = models.AdminInfo.objects.filter(username=username, password=pwd)
            if result.exists():
                return redirect('/manage/homepage/')
            else:
                return HttpResponse('failed')

def manage_homepage(request):
    return render(request, 'homepage_admin.html')

def manage_student(request):
    search_key = request.GET.get('key', '')
    students = models.StuInfo.objects.filter(name__contains=search_key).all()
    # 获取当前页数
    page = request.GET.get('page')
    paginator = Paginator(students, 10)
    try:
        students = paginator.page(page)
    except PageNotAnInteger:
        students = paginator.page(1)
    except EmptyPage:
        students = paginator.page(paginator.num_pages)
    return render(request, 'student_manage.html', locals())

def manage_course(request):
    search_key = request.GET.get('key', '')
    courses = models.CourseInfo.objects.filter(course_name__contains=search_key).all()
    # 获取当前页数
    page = request.GET.get('page')
    paginator = Paginator(courses, 10)
    try:
        courses = paginator.page(page)
    except PageNotAnInteger:
        courses = paginator.page(1)
    except EmptyPage:
        courses = paginator.page(paginator.num_pages)
    return render(request, 'course_manage.html',locals())

class StuForm(ModelForm):
    class Meta:
        model = models.StuInfo
        fields = ['username', 'password', 'name', 'gender', 'department']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

def add_student(request):
    if request.method == 'GET':
        form = StuForm()
        return render(request, 'student_add.html', {'form': form})

    if request.method == 'POST':
        form = StuForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/manage/stu/list/')
        else:
            return render(request, 'student_add.html', {'form': form})

def edit_student(request, sid):
    queryset = models.StuInfo.objects.filter(id=sid).first()
    if request.method == 'GET':
        form = StuForm(instance=queryset)
        return render(request, 'student_edit.html', {'form': form})

    if request.method == 'POST':
        form = StuForm(data=request.POST, instance=queryset)
        if form.is_valid():
            form.save()
            return redirect('/manage/stu/list/')
        else:
            return render(request, 'student_edit.html', {'form': form})


def delete_student(request, sid):
    models.StuInfo.objects.filter(id=sid).first().delete()
    return redirect('/manage/stu/list/')


class CourseForm(ModelForm):
    class Meta:
        model = models.CourseInfo
        fields = ['course_name', 'course_brief', 'class_hour', 'points']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'


def add_course(request):
    if request.method == 'GET':
        form = CourseForm()
        return render(request, 'course_add.html', {'form': form})

    if request.method == 'POST':
        form = CourseForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/manage/course/list/')
        else:
            return render(request, 'course_add.html', {'form': form})

def edit_course(request, cid):
    queryset = models.CourseInfo.objects.filter(id=cid).first()
    if request.method == 'GET':
        form = CourseForm(instance=queryset)
        return render(request, 'course_edit.html', {'form': form})

    if request.method == 'POST':
        form = CourseForm(data=request.POST, instance=queryset)
        if form.is_valid():
            form.save()
            return redirect('/manage/course/list/')
        else:
            return render(request, 'course_edit.html', {'form': form})

def delete_course(request, cid):
    models.CourseInfo.objects.filter(id=cid).first().delete()
    return redirect('/manage/course/list/')

def manage_select(request):
    # 获取当前页数
    selects = models.Select.objects.all()
    print(selects)
    page = request.GET.get('page')
    paginator = Paginator(selects, 10)
    try:
        selects = paginator.page(page)
    except PageNotAnInteger:
        selects = paginator.page(1)
    except EmptyPage:
        selects = paginator.page(paginator.num_pages)
    return render(request, 'select_manage.html', locals())

def delete_select(request, id):
    models.Select.objects.filter(id=id).first().delete()
    return redirect('/manage/select/list/')


def student_index(request, sid):
    if request.method == 'GET':
        queryset = models.CourseInfo.objects.all()
        return render(request, 'student_index.html', {'courses': queryset, 'sid': sid})

    if request.method == 'POST':
        course_id = request.POST.get('cid')
        student_id = request.POST.get('sid')
        course_obj = models.CourseInfo.objects.get(pk=course_id)
        student_obj = models.StuInfo.objects.get(pk=student_id)
        # 添加选课信息
        student_obj.course.add(course_obj)
        return HttpResponse('success')


def student_selected(request, sid):
    if request.method == 'GET':
        student_obj = models.StuInfo.objects.filter(pk=sid).first()
        queryset = student_obj.course.all()
        for q in queryset:
            print(q)
        return render(request, 'student_select.html', {'courses': queryset, 'sid': sid})
    # 新增退课
    if request.method == 'POST':
        course_id = request.POST.get('cid')
        student_id = request.POST.get('sid')
        models.Select.objects.filter(student_id=student_id,course_id=course_id).delete()
        messages.success(request,'退选成功')
        return redirect('student_selected', sid=sid)