from django.conf import settings

from staff.gap.controllers.utils import get_chief
from staff.gap.workflows.base_workflow import BaseWorkflow
from staff.gap.workflows.decorators import allowed_states
from staff.gap.workflows.choices import GAP_STATES as GS
from staff.person.models import Staff


class IllnessWorkflow(BaseWorkflow):

    editable_fields = [
        'has_sicklist',
        'is_covid',
    ] + BaseWorkflow.editable_fields

    workflow = 'illness'
    ui_key = 'gap.workflow.illness'
    gap_type = 'illness'
    verbose_name = 'Болезнь'
    verbose_name_en = 'Illness'
    color = '#f67360'

    template_context = {
        'new_gap_head_ru': 'Болезнь создана',
        'new_gap_head_en': 'Illness was created',
        'edit_gap_head_ru': 'Болезнь изменена',
        'edit_gap_head_en': 'Illness was edited',
        'cancel_gap_head_ru': 'Болезнь отменена',
        'cancel_gap_head_en': 'Illness was canceled',
    }

    def new_gap(self, data):
        self._create_self_gap(data)
        self._new_gap_email(approver=get_chief(self.gap['person_login']))

        self.new_issue('new_illness')

        if self.gap['is_covid']:
            self.new_issue(
                'new_illness_covid',
                master_issue_field='covid_issue',
                issue_unique_prefix='staff_gap_covid_',
            )

        return self.gap

    def prepare_issue_params(self, *args, **kwargs):
        result = super().prepare_issue_params(*args, **kwargs)

        if result is None:
            return None

        if self._has_sickleave():
            result['typeOfDocument'] = 'Есть больничный лист'

        if self._is_outstaff():
            result['tags'] = ['КПБ']

        return result

    def _is_outstaff(self):
        department = Staff.objects.get(login=self.gap['person_login']).department
        return department.get_ancestors().filter(id=settings.OUTSTAFF_DEPARTMENT_ID).exists()

    def _has_sickleave(self):
        return bool(self.gap['has_sicklist'])

    def _append_gap(self, data):
        return {
            'has_sicklist': data.get('has_sicklist', False),
            'is_covid': data.get('is_covid', False),
            'master_issue': data.get('master_issue'),
            'covid_issue': data.get('covid_issue'),
        }

    def _append_base_default(self):
        return {
            'has_sicklist': False,
            'is_covid': False,
            'master_issue': None,
            'covid_issue': None,
        }

    @allowed_states([GS.NEW])
    def sign_gap(self):
        self._set_state(GS.SIGNED)

        self._update()

    @allowed_states([GS.NEW, GS.SIGNED])
    def edit_gap(self, data):
        updated = self._update_editable(data, self.editable_fields)
        if not updated:
            return
        self._update()

        self._new_to_notify(updated)

        master_issue_created = False
        if 'has_sicklist' in updated:
            if updated['has_sicklist']['new']:
                self.gap = self.new_issue('new_illness')
                master_issue_created = True
            del updated['has_sicklist']

        covid_issue_created = False
        if 'is_covid' in updated:
            if updated['is_covid']['new']:
                self.new_issue(
                    'new_illness_covid',
                    master_issue_field='covid_issue',
                    issue_unique_prefix='staff_gap_covid_',
                )
                covid_issue_created = True
            elif updated['is_covid']['old']:
                self.issue_comment('cancel_illness_covid', master_issue_field='covid_issue')

            del updated['is_covid']

        if not updated:
            return

        if not master_issue_created:
            self.issue_comment(
                'edit_gap',
                gap_diff=updated,
                reset_dates=True,
            )

        if not covid_issue_created:
            self.issue_comment(
                'edit_gap_covid',
                gap_diff=updated,
                reset_dates=True,
                master_issue_field='covid_issue',
            )

        self._edit_gap_email(updated, approver=get_chief(self.gap['person_login']))

    @allowed_states([GS.NEW, GS.SIGNED])
    def cancel_gap(self):
        self._set_state(GS.CANCELED)

        self._update()
        self._cancel_gap_email(approver=get_chief(self.gap['person_login']))

        self.issue_comment('cancel_illness')
        self.issue_comment('cancel_illness_covid', master_issue_field='covid_issue')
