from dbsynce.models import Orders
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import UserPassesTestMixin
from django.http import JsonResponse
from django.utils.translation import gettext as _
from django_tables2 import SingleTableView
from sharix_admin.tables import OrdersTable
from sharix_admin.views import OrdersListView, OrderCreateView, OrderDetailView, OrderEditView
from sharix_admin.utils import group_required
from datetime import datetime, timedelta
from dbsynce.lib.core import parse_requirements, get_admin_url
from dbsynce.models import Documents
from django.contrib import messages
from django.db import transaction
from django.urls import reverse_lazy
from django.views.generic.edit import FormView
from django.views.generic import DetailView
from tickets.models import Ticket, TicketList
from sharix_admin.forms import OrderForm
from sharix_admin.utils import *
from dbsynce.lib.data import *
from sharix_admin.views import BaseView
from django.db.models import Q
from django.contrib.auth import get_user_model

class OrdersLocalListView(OrdersListView):
#class OrdersListView(UserPassesTestMixin, SingleTableView):
#    table_class = OrdersTable
#    queryset = Orders.objects.all()
    template_name = 'webservice_running/local/order_local_list.html'
#    page_title = 'Заказы'
    page_name = 'orders_local'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'title': _('Orders'),
            'object_list': context['object_list'],
        })
        return context

    def get_queryset(self):
        queryset = super().get_queryset()
        search_query = self.request.GET.get('q', '').strip()
        if search_query:
            queryset = queryset.filter(
                Q(id__icontains=search_query) |
                Q(user__first_name__icontains=search_query) | 
                Q(user__first_name__icontains=search_query) |
                Q(status__icontains=search_query)
            ).distinct()
        return queryset

    def testing(self, queryset, is_descending):
        queryset = queryset.annotate.order_by("-" if is_descending else "")
        return (queryset, True)

    def test_func(self) -> bool or None:
        return True

@login_required
@group_required('PARTNER-SUPERVISOR')
def change_order_local_status(request):
    if request.method == 'POST':
        order_id = request.POST.get('order_local') 
        new_status = request.POST.get('new_status')

        try:
            order = Orders.objects.get(pk=order_id)
            order.status = new_status
            order.save()
            return JsonResponse({'status': 'success'})
        except Orders.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': 'Order not found'}, status=404)
    return JsonResponse({'status': 'error'}, status=400)

class OrderLocalEditView(OrderEditView):
#    form_class = OrderForm
    template_name = "webservice_running/local/order_local.html"
    success_url = reverse_lazy("webservice_running:orders_local")
#    page_title = 'Изменить заказ'
    page_name = 'order_local_edit'

    def test_func(self):
        return "METASERVICE-CLIENT" in self.user_groups

    def form_valid(self, form):
        with transaction.atomic():
            instance = form.save(commit=False)
            instance.repr = self.request.user
            instance.save()
            instance.save()
            doc_codes = parse_requirements(instance.requirements)
        messages.success(self.request, 'Заказ успешно обновлён!')
        return super().form_valid(form)

class OrderLocalCreateView(OrderCreateView):
    template_name = "webservice_running/local/order_local.html"
    success_url = reverse_lazy("webservice_running:orders_local")
    page_name = 'order_local/add/'

    def test_func(self):
        return "METASERVICE-CLIENT" in self.user_groups
        #return not "METASERVICE-CLIENT" in self.user_groups

    def form_valid(self, form):
        with transaction.atomic():
            instance = form.save(commit=False)
            instance.repr = self.request.user
            instance.save()
            instance.ticket_status = create_ticket_order(self.request.user, instance)
            instance.save()
        messages.success(self.request, 'Заказ успешно создан!')
        return super().form_valid(form)

class OrderLocalDetailView(OrderDetailView):
#    model = Orders
    template_name = 'webservice_running/local/order_local.html'
    context_object_name = 'order_local'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = _('Order Local Details')
        return context
