from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import HttpResponse

from django.conf import settings
from .models import *


# paсkages for generating docx files
from django.http import FileResponse
from .gen_doc import *

# from docxtpl import DocxTemplate

from datetime import datetime, timedelta

menu = [{'title': 'Главная', 'url_name': '', 'data_feather': 'home'},
        {'title': 'Студенты', 'url_name': 'students', 'data_feather': 'user'},
        {'title': 'Группы', 'url_name': 'groups', 'data_feather': 'users'},
        {'title': 'Договоры', 'url_name': 'contracts', 'data_feather': 'file-text'},
        {'title': 'Приказы', 'url_name': 'orders', 'data_feather': 'file-text'},
        {'title': 'Справки', 'url_name': 'sertificates', 'data_feather': 'file-text'},
        {'title': 'Пропуска', 'url_name': 'access', 'data_feather': 'file-text'},
        {'title': 'Темы ВКР', 'url_name': 'graduation_works', 'data_feather': 'file-text'},
        ]


# Create your views here.


def index(request):
    groups = Groups.objects.filter(graduation_date__gte=datetime.now()).order_by('graduation_date')
    # objects = Contracts.objects.order_by('group')
    context = {
        'title': 'Главная страница',
        'objects': groups,
        'data': datetime.now(),
        'menu': menu,
        'active': 1,
    }
    return render(request, 'main/index.html', context=context)


# Вьюха вывода списка студентов
@login_required
def students_page(request):
    students = Students.objects.order_by('surname', 'name', 'patronymic')
    context = {
        'objects': students,
        'title': ' - Студенты',
        't_title': 'Список студентов',
        'menu': menu,
        'active': 2,
    }
    return render(request, 'main/students_old.html', context=context)


# Вьюха вывода отдельного студента
@login_required
def get_student(request, student_id):
    student = Students.objects.get(id=student_id)
    contracts = Contracts.objects.filter(client=student_id)
    orders = Orders.objects.filter(contracts__client=student_id)
    sertificates = Sertificates.objects.filter(contract__client=student_id)
    context = {
        'object': student,
        'contracts': contracts,
        'orders': orders,
        'sertificates': sertificates,
        'title': f' - {student.surname_cases.genitive} {student.name[:1]}. {student.patronymic[:1]}',
        't_title': '',
        'menu': menu,
        'active': 0,
    }
    return render(request, 'main/get_student.html', context=context)


@login_required
def get_customer(request, customer_id):
    pass


# -----------------  Контроллеры для групп  ------------------
# Контроллер вывода списка групп
@login_required
def groups_page(request):
    groups = Groups.objects.order_by('-graduation_date', '-title')
    context = {
        'objects': groups,
        'title': ' - Группы',
        't_title': 'Список групп',
        'menu': menu,
        'active': 3,
    }
    return render(request, 'main/list_groups.html', context=context)


@login_required
def get_group(request, group_id):
    """Контроллер вывода отдельной группы"""
    contracts = Contracts.objects.filter(group=group_id)
    group = Groups.objects.get(pk=group_id)
    context = {
        'group_id': group_id,
        'objects': contracts,
        'title': f' - {group.title}',
        't_title': f'Список студентов группы {group.title}',
        'menu': menu,
        'active': 0,
    }
    return render(request, 'main/list_students.html', context=context)


@login_required
def gen_list_sdo(request, group_id):
    """Контроллер для вывода списка под внсение в систему SDO"""
    contracts = Contracts.objects.filter(group=group_id)
    group = Groups.objects.get(pk=group_id)
    context = {
        'group_id': group_id,
        'title': f' - список для SDO',
        'objects': contracts,
        'menu': menu,
        't_title': f'Список группы {group.title} для платформы SDO',
        'active': 0,
    }
    
    return render(request, template_name='main/list_for_sdo.html', context=context)


# -----------------  Контроллеры для договоров  ------------------
@login_required
def contracts_page(request):
    """Вывод списка договоров"""
    contracts = Contracts.objects.all()
    context = {
        'objects': contracts,
        'title': ' - Договоры',
        't_title': f'Договоры',
        'menu': menu,
        'active': 4,
    }
    return render(request, template_name='main/contracts.html', context=context)


@login_required
def get_contract(request, contract_id):
    """Вывод отдельного договора"""
    contract = Contracts.objects.get(pk=contract_id)
    context = {
        'object': contract,
        'title': f' - {contract.number}',
        't_title': f'Договоры',
        'menu': menu,
        'active': 0,
    }
    return render(request, 'main/get_contract.html', context=context)


# -----------------  Контроллеры для пропусков  ------------------
@login_required
def access_page(request):
    """Вывод списка служебок под пропуска"""
    access_list = Access_lists.objects.all()
    context = {
        'objects': access_list,
        'title': ' - Пропуски',
        't_title': f'Пропуски',
        'menu': menu,
        'active': 7,
    }
    return render(request, 'main/access.html', context=context)


@login_required
def get_acces(request, acces_id):
    """вывод списка служебных записок под пропуска"""
    acces = Access_lists.objects.get(pk=acces_id)
    contracts = Contracts.objects.filter(access_lists__pk=acces_id).order_by('client__surname', 'client__name',
                                                                             'group__graduation_date', )
    # print(contracts)
    context = {
        'objects': contracts,
        'object': acces,
        # 'title' : f' - {contract.number}',
        't_title': f'Пропуска',
        'menu': menu,
        'active': 0,
    }
    return render(request, 'main/get_acces.html', context=context)


@login_required
def gen_acces(required, acces_id):
    """генерация служебки на пропуска"""
    acces = Access_lists.objects.get(pk=acces_id)

    filename = f'{acces.registration_date:%y%m%d} служебка на пропуска.docx'

    return FileResponse(memo_by_order(acces_id=acces_id), as_attachment=True, filename=filename)


@login_required
def get_extract(request, extract_id):
    """Отображение выписки из протокола кафедры"""
    # extract = Extracts.objects.get(pk=extract_id)
    order = Orders.objects.get(extract__pk=extract_id)
    contracts = Orders.objects.get(pk=order.pk).contracts.all().order_by('client')
    context = {
        'object': order,
        # 'extract': extract,
        'contracts': contracts,
        'menu': menu,
        'title': f'{order.extract}',
    }
    return render(request, 'main/get_extract.html', context=context)


# TODO добавить в текст выбор докладчика из базы.
@login_required
def gen_extract(request, extract_id):
    """Генерация файла выписки"""
    object = Orders.objects.get(extract__pk=extract_id)
    contracts = Orders.objects.get(pk=object.pk).contracts.all().order_by('client')

    filename = f'{object.extract.date:%y%m%d} Выписка.docx'

    return FileResponse(extract_department_meeting(object, contracts), as_attachment=True, filename=filename)


@login_required
def print_extract(request, extract_id):
    # extract = Extracts.objects.get(pk=extract_id)
    order = Orders.objects.get(extract__pk=extract_id)
    contracts = Orders.objects.get(pk=order.pk).contracts.all().order_by('client')
    context = {
        'object': order,
        # 'extract': extract,
        'contracts': contracts,
        'title': f'{order.extract}',
    }
    return render(request, 'main/print_extract.html', context=context)


# Вывод на печать договора
@login_required
def print_contract(request, contract_id):
    contract = Contracts.objects.get(pk=contract_id)
    context = {
        'object': contract,
        'title': f'договор № {contract.number}',

    }
    if contract.customer:
        return render(request, 'main/print_contract_with_customer.html', context=context)
    else:
        return render(request, 'main/print_contract.html', context=context)


# -----------------  Контроллеры для приказов  ------------------
@login_required
def orders_page(request):
    """Вывод списка приказов"""
    orders = Orders.objects.order_by('-registered')
    context = {
        'objects': orders,
        'title': ' - Приказы',
        't_title': 'Список приказов',
        'menu': menu,
        'active': 5,
    }
    return render(request, 'main/list_orders.html', context=context)


@login_required
def get_order(request, order_id):
    """Вывод списка приказов"""
    order = Orders.objects.get(pk=order_id)
    contracts = Orders.objects.get(pk=order_id).contracts.all().order_by('client')
    is_single = True if contracts.count() == 1 else False

    context = {
        'object': order,
        'contracts': contracts,
        'menu': menu,
        'is_single': is_single,
        'title': f'{order.type_order}',
    }

    return render(request, 'main/get_order.html', context=context)


@login_required
def for_registry(request, order_id):
    order = Orders.objects.get(pk=order_id)
    contracts = Orders.objects.get(pk=order_id).contracts.all().order_by('client')

    context = {
        'object': order,
        'contracts': contracts,
        'menu': menu,
        # 'is_single':is_single,
        'title': f'Реестр в отдел кадров',
    }

    return render(request, 'main/for_registry.html', context=context)


@login_required
def gen_for_registry(request, order_id):
    filename = f'для реестра {datetime.now():%y%m}.xlsx'

    return FileResponse(filefor_registry(order_id=order_id), as_attachment=True, filename=filename)


@login_required
def print_order(request, order_id):
    order = Orders.objects.get(pk=order_id)
    contracts = Orders.objects.get(pk=order_id).contracts.all().order_by('client')

    # https://ru.stackoverflow.com/questions/842937/django-Получить-связанные-объекты
    # https://django.fun/ru/articles/tutorials/select_related-i-prefetch_related-v-django/
    is_single = True if contracts.count() == 1 else False
    context = {
        'object': order,
        'contracts': contracts,
        'is_single': is_single,
        'title': f'{order.type_order}',
    }
    if order.type_order.title == 'о зачислении':
        return render(request, 'main/print_order_on_enrollment.html', context=context)
    elif order.type_order.title == 'на темы':
        return render(request, 'main/print_order_on_theme.html', context=context)
    else:
        return render(request, 'main/index.html', context=context)


@login_required
def sertificates_page(request):
    """Вывод списка справок"""
    sertificates = Sertificates.objects.all()
    context = {
        'objects': sertificates,
        'title': ' - Справки',
        't_title': 'Список справок',
        'menu': menu,
        'active': 6,

    }
    return render(request, 'main/sertificates.html', context=context)


@login_required
def get_sertificates(request, sertificate_id):
    """Вывод справки"""
    sertificate = Sertificates.objects.get(pk=sertificate_id)
    is_now = sertificate.contract.start_date < sertificate.registered < sertificate.contract.end_date
    context = {
        'is_now': is_now,
        'object': sertificate,
        'title': f' - {sertificate.contract.client}',
        'menu': menu,
        'active': 0,
    }

    return render(request, 'main/get_sertificate.html', context=context)


@login_required
def print_sertificate(request, sertificate_id):
    sertificate = Sertificates.objects.get(pk=sertificate_id)
    is_now = sertificate.contract.start_date < sertificate.registered < sertificate.contract.end_date
    context = {
        'is_now': is_now,
        'object': sertificate,
        'title': f' - {sertificate.contract.client}',
        'menu': menu,
        'active': 0,
    }

    return render(request, 'main/print_sertificate.html', context=context)


# Протоколы
@login_required
def get_protocol(request, protocol_pk):
    """Вывод списка протоколов"""
    # protocol = Protocols.objects.prefetch_related('questions').get(pk=protocol_pk)
    protocol = Protocols.objects.prefetch_related('questions')
    context = {
        'object': protocol,
        # 'title' : f' - № {protocol.number}',
        'menu': menu,
        'active': 0,
    }

    return render(request, 'main/get_protocol.html', context=context)


@login_required
def gen_order(request, order_id):
    """Возвращает файл приказа по его айди"""
    order = Orders.objects.get(pk=order_id)
    contracts = Orders.objects.get(pk=order_id).contracts.all().order_by('client')

    # https://ru.stackoverflow.com/questions/842937/django-Получить-связанные-объекты
    # https://django.fun/ru/articles/tutorials/select_related-i-prefetch_related-v-django/

    filename = f'{order.event_date:%y%m%d} {order.type_order}.docx'

    if order.type_order.title == 'о зачислении--==':
        return FileResponse(order_on_enrollment(order, contracts), as_attachment=True, filename=filename)
    elif order.type_order.title == 'на темы':
        return FileResponse(order_on_theme(order, contracts), as_attachment=True, filename=filename)
    else:
        return FileResponse(order_by_id(order.pk), as_attachment=True, filename=filename)


@login_required
def gen_list_students(request, group_id):
    contracts = Contracts.objects.filter(group=group_id).order_by('client__surname', 'client__name')
    response = HttpResponse(content_type='text/plain')
    response['Content_Disposition'] = 'attachment; filename = list_group.txt'
    lines = []
    for item in contracts:
        lines.append(f'{item.client.surname} {item.client.name[0]}. {item.client.patronymic[0]}. \n')

    response.writelines(lines)
    return response


@login_required
def gen_protocol(request, contract_id):
    """генератор протокола защиты"""
    contract = Contracts.objects.get(pk=contract_id)

    filename = f'{contract.degree_work.protocol.date_time:%y%m%d} {contract.degree_work.protocol.number}.docx'

    return FileResponse(protocol_by_id(contract_id=contract_id), as_attachment=True, filename=filename)


@login_required
def gen_protocols(request, order_id):
    """ генератор протоколов защит по приказу"""
    order = Orders.objects.get(pk=order_id)

    filename = f'{order.event_date:%y%m%d} протоколы защит.docx'

    return FileResponse(protocol_by_order(order_id=order_id), as_attachment=True, filename=filename)


# TODO: Подправить вывод ибо выдает в непонятных символах
@login_required
def gen_group_list(request, group_id):
    """ генератор списка студентов группы для запроса данных о оплате у Свечкарёвой """
    contracts = Contracts.objects.filter(group=group_id).order_by('client__surname', 'client__name')
    response = HttpResponse(content_type='text/plain')
    response['Content_Disposition'] = 'attachment; filename = list_group.txt'
    lines = []
    for item in contracts:
        lines.append(f'{item.number} - {item.client.surname} {item.client.name} {item.client.patronymic} \n')

    response.writelines(lines)
    return response

@login_required
def gen_diplma_form(request, contract_id):
    """ генерация бланка диплома для печати """
    contract = Contracts.objects.get(pk=contract_id)
    form = True
    # return HttpResponse(gen_diploma_supplement(contract_id))
    return FileResponse(gen_diploma(contract, form), as_attachment=True, filename=f'{contract.client.surname} - диплом.docx')


@login_required
def gen_diploma_supplement(request, contract_id):
    """ Генерация приложения диплома для печати """
    contract = Contracts.objects.get(pk=contract_id)
    form = False
    return FileResponse(gen_diploma(contract, form), as_attachment=True, filename=f'{contract.client.surname} - приложение.docx')

@login_required
def graduation_works(request):
    """ Вывод списка тем """
    # works = Degree_works.objects.exclude(title='')
    contracts = Contracts.objects.exclude(degree_work=None)
    # contracts = Contracts.objects.all()
    works = Degree_works.objects.all()
    # print(works)
    context = {
        'objects': contracts,
        'title': f' - ВКР',
        't_title': 'Список тем ВКР',
        'menu': menu,
        'active': 8,
    }

    return render(request, template_name='main/list_graduation_works.html', context=context)

    pass

