from rest_framework import viewsets as meviewsets
from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer
from app.entities.models import (
    ChangeRequestFormHeader,
    ChangeRequestFormApprovers,
    ChangeRequestFormStakeHolders,
    AllowedCompany
)
# from app.applicationlayer.form_listing_ import headers
from app.applicationlayer.cms.form.download.serializers import headers
from django.db.models import CharField, Value
from django.db.models import Q
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
# from cms.applicationlayer.utilities import logged_user


class DownloadRequest(XLSXFileMixin, ReadOnlyModelViewSet):
    queryset = ChangeRequestFormHeader.objects.all()
    serializer_class = headers
    renderer_classes = (XLSXRenderer,)
    filename = 'Change Request Form.xlsx'
    permission_classes = (AllowAny,)

    def list(self, request, *args, **kwargs):
        id_number = request.user.code
        # data = ChangeRequestFormHeader.objects.filter(
        #     Q(frm_approvers__user__code=id_number) |
        #     Q(requested_by_user=id_number) |
        #     Q(frm_stakes__user__code=id_number)
        # ).distinct()


        priviledgeCrs = AllowedCompany.objects.filter(
            Q(id_number=id_number) &
            Q(view_all_change_request=True)
        ).values('group_pivots')
        
        data = ChangeRequestFormHeader.objects.filter(
            (Q(frm_approvers__user__code=id_number) |
            Q(frm_stakes__user__code=id_number) |
            Q(requested_by_user=id_number) |
            Q(requested_to_department__in=priviledgeCrs)) &
            Q(is_active=True)
        ).exclude(
                Q(status__icontains='Draft') &
                ~Q(requested_by_user=id_number)
        ).distinct()

        serializer = headers(data=data, many=True, context={'request': request})
        serializer.is_valid(raise_exception=False)
        return Response(serializer.data)

    column_header = {
        'titles': [
            "Cr Number",
            "Name",
            "Company Request To",
            "Department Requested To",
            "Requested By",
            "Status",
            "Priority Level",
            "Date Modified",
            "Date Required"
            "Action",
        ],
        'column_width': [17, 30, 17],
        'height': 25,
        'style': {
            'alignment': {
                'horizontal': 'center',
                'vertical': 'center',
                'wrapText': False,
                'shrink_to_fit': True,
            },
            'border_side': {
                'border_style': 'thin',
                'color': 'FF000000',
            },
            'font': {
                'name': 'Arial',
                'size': 14,
                'bold': True,
                'color': 'FF000000',
            },
        },
    }
