# coding: utf-8

from django.template import loader
from django.utils.translation import gettext_lazy as _

from procu.api import models
from procu.api.common.fields import AttachmentField
from procu.rest import serializers


class Product(serializers.ModelSerializer):
    class Meta:
        model = models.EnquiryProduct
        fields = ('name', 'qty', 'comment')


class TicketRetrieve(serializers.ModelSerializer):
    summary = serializers.CharField(source='subject')
    description = serializers.SerializerMethodField()
    attachments = AttachmentField(many=True)

    class Meta:
        model = models.Enquiry
        fields = ('summary', 'description', 'attachments')

    @staticmethod
    def get_description(obj: models.Enquiry):

        enquiry_fields = [
            ('Инициатор', f'кто:{obj.author.username}'),
            ('Предмет закупки', obj.subject),
            ('Описание', obj.internal_comment),
            (
                'Юрлицо',
                f'{obj.legal_entity.title}' if obj.legal_entity else None,
            ),
            ('Адрес доставки', f'{obj.address.text}' if obj.address else None),
            (
                'Срок выполнения',
                f'{obj.due_at.strftime("%d.%m.%Y")}' if obj.due_at else None,
            ),
            ('ЦФО', f'{obj.cfo.key}: {obj.cfo.name}' if obj.cfo else None),
            (
                'Программа',
                f'{obj.program.key}: {obj.program.name}'
                if obj.program
                else None,
            ),
            (
                'Проект',
                f'{obj.project.key}: {obj.project.name}'
                if obj.project
                else None,
            ),
            (
                'Задача',
                f'{obj.task.key}: {obj.task.name}' if obj.task else None,
            ),
            (
                'Сервис',
                f'{obj.service.key}: {obj.service.name}'
                if obj.service
                else None,
            ),
            ('МВП', f'{obj.mvp.key}: {obj.mvp.name}' if obj.mvp else None),
            (
                'Бюджетная линия',
                f'{obj.budget_line.key}: {obj.budget_line.name}'
                if obj.budget_line
                else None,
            ),
            (
                'Система',
                f'{obj.system.key}: {obj.system.name}' if obj.system else None,
            ),
            (
                'Подсистема',
                f'{obj.subsystem.key}: {obj.subsystem.name}'
                if obj.subsystem
                else None,
            ),
        ]

        enquiry_fields = [item for item in enquiry_fields if item[1]]

        context = {
            'enquiry_fields': enquiry_fields,
            'products': obj.initial_products,
            'replacements': 'Нет' if obj.no_replacement else 'Да',
            'links': [link.key for link in obj.links.all()],
        }

        body = loader.render_to_string('any_ticket.txt', context=context)

        return body.strip()


class TicketLocation(serializers.Serializer):

    queue = serializers.CharField(label=_('ENQUIRY::CREATE_TICKET_QUEUE'))
    type = serializers.CharField(label=_('ENQUIRY::CREATE_TICKET_TYPE'))


class TicketCreate(serializers.Serializer):
    check_for_nested_writes = False

    location = TicketLocation()

    summary = serializers.CharField(
        label=_('ENQUIRY::CREATE_TICKET_SUMMARY'), max_length=255
    )
    description = serializers.CharField(
        label=_('ENQUIRY::CREATE_TICKET_DESCRIPTION'),
        style={'x-wf': True},
        allow_blank=True,
    )
    attachments = AttachmentField(
        many=True,
        label=_('ENQUIRY::CREATE_TICKET_ATTACHMENTS'),
        allow_empty=True,
    )
