from io import BytesIO

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

from apps.core.mixins.search_mixin import ExcelDynamicSearchMixin
from apps.warehouse import models as warehouse_models
from apps.warehouse.web.api.v1 import serializers as warehouse_serializers
from common.helper_excel import create_header, excel_description, create_header_freez, create_value, shamsi_date, \
    convert_str_to_date
from common.helpers import get_organization_by_user


class WareHouseExcelViewSet(viewsets.ModelViewSet, ExcelDynamicSearchMixin):
    queryset = warehouse_models.InventoryEntry.objects.all()
    serializer_class = warehouse_serializers.InventoryEntrySerializer
    search_fields = [
        "distribution__distribution_id",
        "organization__name",
        "weight",
        "balance",
        "lading_number",
        "is_confirmed",
    ]
    date_field = "create_date"

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

        entries = queryset.filter(organization=get_organization_by_user(request.user))
        ser_data = self.serializer_class(entries, 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:
                document = data.get('document')
                if document:
                    if str(document).startswith(('http://', 'https://')):
                        document_value = f'=HYPERLINK("{document}", "دانلود")'
                    else:
                        full_path = f"https://yourdomain.com/{document}"
                        document_value = f'=HYPERLINK("{full_path}", "دانلود")'

                else:
                    document_value = 'ندارد'
                list1 = [
                    m,
                    str(shamsi_date(convert_str_to_date(data['create_date']), in_value=True)) if data.get(
                        'create_date') else '',
                    str(data[
                            'distribution'].get('distribution')) or '-',
                    data.get('weight') or 0,
                    data.get('lading_number') or '-',
                    data.get('delivery_address') or '-',
                    document_value,
                    data.get('notes') or '',
                ]
                create_value(worksheet, list1, l + 1, 1, height=23, m=m)
                if document:
                    worksheet.cell(row=l + 1, column=7).font = Font(color="0563C1", underline='single', bold=True)
                m += 1
                l += 1

        weight = sum((data['weight'] or 0) for data in ser_data)

        value_list = [
            weight
        ]

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

        list2 = [
            'مجموع==>',
            '',
            '',
            weight,
            '',
            '',
            '',
            ''
        ]
        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
