from io import BytesIO

from django.http import HttpResponse
from openpyxl import Workbook
from rest_framework import viewsets
from rest_framework.decorators import action

from apps.core.mixins.search_mixin import ExcelDynamicSearchMixin
from apps.livestock.models import LiveStock
from apps.livestock.web.api.v1.serializers import LiveStockSerializer
from common.helper_excel import create_header, excel_description, create_header_freez, create_value, shamsi_date, \
    convert_str_to_date


class LiveStockExcelViewSet(viewsets.ModelViewSet, ExcelDynamicSearchMixin):
    queryset = LiveStock.objects.all()
    serializer_class = LiveStockSerializer

    # noqa # دام ها
    @action(
        methods=['get'],
        detail=False,
        url_path='livestock_excel',
        url_name='livestock_excel',
        name='livestock_excel'
    )
    def livestock_excel(self, request):
        output = BytesIO()
        workbook = Workbook()
        worksheet = workbook.active
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        query = self.filter_query(self.queryset)

        ser_data = self.serializer_class(query, many=True).data

        excel_options = [
            "ردیف",
            "دام",
            "نوع دام",
            "تاریخ تولد",
            "جنسیت",
            "گونه",
            "نوع وزن",

        ]

        header_list = [
            "تعداد دام",

        ]

        create_header(worksheet, header_list, 5, 2, height=25, border_style='thin')
        excel_description(worksheet, 'B1', f'دام ها', row2='C3')
        create_header_freez(worksheet, excel_options, 1, 6, 7, height=25, width=20)

        l = 6
        m = 1
        if ser_data:
            for data in ser_data:
                gender = 'نر' if data.get('gender') == 1 else 'ماده'
                weight_type = 'سنگین' if data.get('weight_type') == 'H' else 'سبک'
                date = data.get('birthdate') or None
                if date is not None:
                    sh_date = str(shamsi_date(convert_str_to_date(date),in_value=True))
                else:
                    sh_date = '-'

                list1 = [
                    m,
                    (data.get('type') or {}).get('name') or '-',
                    (data.get('use_type') or {}).get('name') or '-',
                    sh_date,
                    gender,
                    (data.get('species') or {}).get('name') or '-',
                    weight_type,

                ]
                create_value(worksheet, list1, l + 1, 1, height=23, m=m)
                m += 1
                l += 1
        value_list = [
            len(query)
        ]

        create_value(worksheet, value_list, 3, 5, border_style='thin')
        workbook.save(output)
        output.seek(0)

        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response[
            'Content-Disposition'] = f'attachment; filename="دام ها.xlsx"'.encode(
            'utf-8')
        response.write(output.getvalue())
        return response
