import os
from openpyxl import load_workbook
# Create your views here.
import random
from django.http import JsonResponse

from .models import Student

def save_file(file, save_directory):
    file_path = os.path.join(save_directory, file.name)
    with open(file_path, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    return file_path

def getinformation(request):
    if request.method == 'POST':
        try:
            class_name = request.POST.get('class_name')
            file = request.FILES.get('file')
            if file and class_name:
                if Student.objects.filter(class_name=class_name).first():  # 如果表中已经有该班级
                    response_data = {'message': 0, 'error': '该班级已创建'}
                    return JsonResponse(response_data,json_dumps_params={'ensure_ascii': False})
                else:
                    current_dir = os.path.dirname(os.path.abspath(__file__))
                    save_directory = os.path.join(current_dir, 'excelfile')
                    if not os.path.exists(save_directory):
                        os.makedirs(save_directory)
                    file_path = save_file(file, save_directory)
                    wb = load_workbook(file_path)
                    ws = wb.active
                    for row in ws.iter_rows(min_row=2, values_only=True):
                        sid, name = row[0], row[1]
                        Student.objects.create(sid=sid, name=name, class_name=class_name, credit=0.0,
                                               probability=1.0,max = 0 , min = 0)
                    response_data = {'message': 1 , 'total': ws.max_row-1}
                    return JsonResponse(response_data,json_dumps_params={'ensure_ascii': False})
            else:
                response_data = {
                    'message': 0,
                    'error': '缺少必要的参数'
                }
                return JsonResponse(response_data,json_dumps_params={'ensure_ascii': False})
        except Exception as e:
            response_data = {
                'message': 0,
                'error': str(e)
            }
            return JsonResponse(response_data)
    else:
        response_data = {
            'message': 0,
            'error': '请求方法错误'
        }
        return JsonResponse(response_data,json_dumps_params={'ensure_ascii': False})


def call_students(request):  #前端点击点名按钮向后端发送请求
    if request.method == 'POST':
        try:
            class_name = request.POST.get('class_name')  #班级名称
            num0 = request.POST.get('num')  #本次点名的人数
            mode0 = request.POST.get('mode')
            result = {}
            if class_name and num0 and mode0:
                num = int(num0)
                mode = int(mode0)
                s = Student()  # 创建一个实例
                result = s.callstu(class_name, num, mode)
                response_data = result #成功返回
            else:
                response_data = {
                    'message': 0,
                    'error': '缺少必要的参数'
                }
        except Exception as e:
            response_data = {
                'message': 0,
                'error': str(e)
            }
    else:
        response_data = {
            'message': 0,
            'error': '请求方法错误'
        }
    return JsonResponse(response_data)

def updatetable(request):
    if request.method == 'POST':
        try:
            point = float(request.POST.get('point'))
            class_name = request.POST.get('class_name')  #班级名称
            sid = request.POST.get('sid')   #本次点名的学生学号
            style = int(request.POST.get('style'))
            if point and class_name and sid and style:
                s = Student()  # 创建一个实例
                s.updateinfor(point, class_name,sid, style)
                response_data = {'message': 1}
            else:
                response_data = {'message': 0,'error': '缺少必要的参数'}
        except Exception as e:
            response_data = {'message': 0,'error': str(e)}
    else:
        response_data = {'message': 0,'error': '请求方法错误'}
    return JsonResponse(response_data)

import random
from django.http import JsonResponse

def choosestyle(request):
    if request.method == 'POST':
        random_number = random.choice([1, 2, 3, 4, 5, 6])
        return JsonResponse({'number': random_number})  # 将数字包装在字典中
    else:
        response_data = {'error': '请求方法错误'}
        return JsonResponse(response_data)

from django.db.models import Window, F
from django.db.models.functions import Rank


def show_information (request):
    if request.method == 'POST':
        try:
            class_name = request.POST.get('class_name')  # 班级名称
            sid = request.POST.get('sid')  # 本次想查询的学生学号
            order = request.POST.get('order')  #前端返回的序号
            response_data = {'message': 0}
            if class_name and sid:
                class_students = Student.objects.filter(class_name=class_name).annotate(
                    rank=Window(
                        expression=Rank(),
                        order_by=F('credit').desc()
                    )
                ).order_by('credit')
                # 查找特定学生的排名
                student_rank = None
                name = None
                for student in class_students:
                    if student.sid == sid:
                        student_rank = student.rank
                        name = student.name
                        break
                response_data = {'order':order,'class_name': class_name,'name':name,'sid':sid,'student_rank':student_rank}
            else:
                response_data = {'message':0,'error':'缺少必要的参数'}
        except Exception as e:
            response_data = {'message': 0, 'error': str(e)}
    else:
        response_data = {'message': 0, 'error': '请求方法错误'}
    return JsonResponse(response_data)