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.herd.models import Herd, Rancher
from apps.herd.web.api.v1.serializers import HerdSerializer, RancherSerializer
from common.helper_excel import create_header, excel_description, create_header_freez, create_value


class HerdExcelViewSet(viewsets.ModelViewSet, ExcelDynamicSearchMixin):
    queryset = Herd.objects.all()
    serializer_class = HerdSerializer

    # noqa # دامداران
    @action(
        methods=['get'],
        detail=False,
        url_path='rancher_excel',
        url_name='rancher_excel',
        name='rancher_excel'
    )
    def rancher_excel(self, request):
        output = BytesIO()
        workbook = Workbook()
        worksheet = workbook.active
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        ranchers = Rancher.objects.all().order_by('-modify_date')
        rancher_search_fields = [
            "ranching_farm",
            "first_name",
            "last_name",
            "mobile",
            "national_code",
            "birthdate",
            "nationality",
            "address",
            "province__name",
            "city__name",
        ]
        query = self.filter_query(ranchers, search_list=rancher_search_fields)

        ser_data = RancherSerializer(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:
                without_herd = 'بدون دام' if data.get('without_herd') == True else 'دام عادی'

                list1 = [
                    m,
                    data.get('ranching_farm') or '-',
                    data.get('first_name') or '-',
                    data.get('last_name') or '-',
                    data.get('national_code') or '-',
                    data.get('mobile') or '-',
                    (data.get('province') or {}).get('name') or '-',
                    (data.get('city') or {}).get('name') or '-',
                    data.get('address') or '-',
                    without_herd,

                ]
                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

        # noqa # دامداران

    @action(
        methods=['get'],
        detail=False,
        url_path='herd_excel',
        url_name='herd_excel',
        name='herd_excel'
    )
    def herd_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:
                if data.get('activity') == 'I':
                    activity = 'صنعتی'
                elif data.get('activity') == 'V':
                    activity = 'روستایی'
                else:
                    activity = 'عشایری'
                operating_license_state='ندارد' if data.get('operating_license_state') == False else 'دارد'
                activity_state='ندارد' if data.get('activity_state') == False else 'دارد'

                list1 = [
                    m,
                    data.get('unit_unique_id') or '-',
                    data.get('name') or '-',
                    (data.get('cooperative') or {}).get('name') or '-',
                    (data.get('contractor') or {}).get('name') or '-',
                    data.get('capacity') or 0,
                    activity,
                    data.get('epidemiologic') or '-',
                    data.get('light_livestock_number') or 0,
                    data.get('heavy_livestock_number') or 0,
                    (data.get('province') or {}).get('name') or '-',
                    (data.get('city') or {}).get('name') or '-',
                    operating_license_state,
                    activity_state,
                    data.get('postal') or '-',

                ]
                create_value(worksheet, list1, l + 1, 1, height=23, m=m)
                m += 1
                l += 1

        capacity = sum((data['capacity'] or 0) for data in ser_data)
        light_livestock_number = sum((data['light_livestock_number'] or 0) for data in ser_data)
        heavy_livestock_number = sum((data['heavy_livestock_number'] or 0) for data in ser_data)

        value_list = [
            len(query),
            capacity,
            light_livestock_number,
            heavy_livestock_number,
        ]

        create_value(worksheet, value_list, 3, 5, border_style='thin')

        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            '',
            capacity,
            '',
            '',
            light_livestock_number,
            heavy_livestock_number,
            '',
            '',
            '',
            '',
            ''
        ]
        create_value(worksheet, list2, l + 3, 1, color='gray', height=23)
        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