from peewee import (
    AutoField,
    CharField,
    IntegerField,
    FloatField,
    BooleanField,
    DateTimeField,
    DateField,
    TextField,
)

from peewee import SQL, DoesNotExist
from ..base import BaseModel, MedianLibException
from ..constant import TypeServiListe, EtatListe
from ..database import TinyIntegerField
import datetime as dt

MODE_NOMINATIF = [
    'NOMINATIF',
    'EXOTIQUE',
]

FUSION_SORTIE_LOT = [
    'SORTIE DE LOTS',
]

FUSION_SORTIE_PERIME = [
    'SORTIE DE PERIMES',
]


class ListeErrorModel(BaseModel):

    pk = AutoField(
        column_name='x_pk', primary_key=True)
    liste = CharField(
        max_length=60, column_name='x_liste')
    mode = CharField(
        max_length=1, column_name='x_mode')
    message = TextField(
        column_name='x_message')

    class Meta:
        table_name = 'f_liste_error'
        indexes = (
            (('x_liste', 'x_mode'), True),
        )

    def save(self, force_insert=False, only=None):
        """Enforce control on each information passed"""
        # We retrieve the liste
        try:
            original_list = FListe.get(mode=self.mode, liste=self.liste)
            if original_list.with_note == 0:
                original_list.with_note = 1
                original_list.save()
        except DoesNotExist:
            raise MedianLibException("Original list not found ! error message not created")
        return super().save(force_insert, only)

    def delete_instance(self, recursive=False, delete_nullable=False):
        """When note is delete, we need to unlink note on list"""
        try:
            original_list = FListe.get(mode=self.mode, liste=self.liste)
            if original_list.with_note > 0:
                original_list.with_note = 0
                original_list.save()
        except DoesNotExist:
            raise MedianLibException("Original list not found ! error message not created")

        return super().delete_instance(recursive, delete_nullable)


class WorkItemModel(BaseModel):

    pk = AutoField(
        column_name='x_pk', primary_key=True)
    liste = CharField(
        column_name='x_liste', null=True, max_length=60, constraints=[SQL("DEFAULT ''")], default='')
    mode = CharField(
        column_name='x_mode', null=True, max_length=1, constraints=[SQL("DEFAULT ''")], default='')
    item = CharField(
        column_name='x_item', null=True, max_length=40, constraints=[SQL("DEFAULT ''")], default='')
    reference = CharField(
        column_name='x_ref', null=True, max_length=35, constraints=[SQL("DEFAULT ''")], default='')
    quantite_dem = FloatField(
        column_name='x_qte_dem', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.000)
    quantite_serv = FloatField(
        column_name='x_qte_serv', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.000)
    adresse = CharField(
        column_name='x_adr', null=True, max_length=19, constraints=[SQL("DEFAULT ''")], default='')
    adresse_from = CharField(
        column_name='x_adr_from', null=True, max_length=19, constraints=[SQL("DEFAULT ''")], default='')
    lot = CharField(
        column_name='x_lot', null=True, max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    admin = CharField(
        column_name='x_admin', null=True, max_length=10, constraints=[SQL("DEFAULT ''")], default='')
    date_peremption = DateTimeField(
        column_name='x_tperemp', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    id_fifo = IntegerField(
        column_name='x_id_fifo', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    ordre = CharField(
        column_name='x_ordre', null=True, max_length=10, constraints=[SQL("DEFAULT ''")], default='')
    item_work = IntegerField(
        column_name='x_item_w', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    date_quarantaine = DateTimeField(
        column_name='x_tquarant', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    info = CharField(
        column_name='x_info', null=True, max_length=80, constraints=[SQL("DEFAULT ''")], default='')
    service = CharField(
        column_name='x_dest', null=True, max_length=30, constraints=[SQL("DEFAULT ''")], default='')
    utilisateur = CharField(
        column_name='x_user', null=True, max_length=60, constraints=[SQL("DEFAULT ''")], default='')
    kit = CharField(
        column_name='x_kit', null=True, max_length=35, constraints=[SQL("DEFAULT ''")], default='')
    prix_unitaire = FloatField(
        column_name='x_prix_u', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.000)
    urgent = BooleanField(
        column_name='x_urgent', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    interface = CharField(
        column_name='x_interface', max_length=15, constraints=[SQL("DEFAULT ''")], default='')
    contenant = CharField(
        column_name='x_contenant', null=True, max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    num_ipp = CharField(
        column_name='x_num_ipp', max_length=35, constraints=[SQL("DEFAULT ''")], default='')
    num_sej = CharField(
        column_name='x_num_sej', max_length=35, constraints=[SQL("DEFAULT ''")], default='')
    adresse_tampon = CharField(
        column_name='x_adr_tampon', null=True, max_length=19, constraints=[SQL("DEFAULT ''")], default='')
    mode_mds = CharField(
        column_name='x_mode_mds', null=True, max_length=1, constraints=[SQL("DEFAULT ''")], default='')
    poste = CharField(
        column_name='x_poste', null=True, max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    user_alloc = CharField(
        column_name='x_user_alloc', max_length=60, constraints=[SQL("DEFAULT ''")], default='')
    date_alloc = DateTimeField(
        column_name='x_talloc', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    id_pilulier = CharField(
        column_name='x_id_pilulier', null=True, max_length=40, constraints=[SQL("DEFAULT ''")], default='')
    pos_pilulier = IntegerField(
        column_name='x_pos_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    tiroir = IntegerField(
        column_name='x_tiroir', constraints=[SQL("DEFAULT 0")], default=0)
    alveole = IntegerField(
        column_name='x_alveole', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    alveole_theo = IntegerField(
        column_name='x_alveole_theo', constraints=[SQL("DEFAULT 0")], default=0)
    no_pilulier = IntegerField(
        column_name='x_no_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    id_peigne = IntegerField(
        column_name='x_id_peigne', constraints=[SQL("DEFAULT 0")], default=0)
    pilulier_theo = IntegerField(
        column_name='x_pilulier_theo', constraints=[SQL("DEFAULT 0")], default=0)
    item_wms = IntegerField(
        column_name='x_item_wms', constraints=[SQL("DEFAULT 0")], default=0)
    ucd = CharField(
        column_name='x_ucd', max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    cip = CharField(
        column_name='x_cip', max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    zone_fin = CharField(
        column_name='x_zone_fin', max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    goulotte = IntegerField(
        column_name='x_goulotte', constraints=[SQL("DEFAULT 1")], default=1)
    fraction = IntegerField(
        column_name='x_fraction', constraints=[SQL("DEFAULT 100")], default=100)
    sous_secteur = CharField(
        column_name='xx_sous_secteur', max_length=100, constraints=[SQL("DEFAULT ''")], default='')
    pk_item = IntegerField(
        column_name='x_pk_item', null=True, default=None)
    id_plateau = IntegerField(
        column_name='x_id_plateau', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    pk_pilulier = IntegerField(
        column_name='x_pk_pilulier', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    code_bac = CharField(
        column_name='x_codebac', null=True, max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    capa = IntegerField(
        column_name="x_capa", null=True, constraints=[SQL("DEFAULT 0")], default=0)
    serial = CharField(
        column_name='x_serial', max_length=20, constraints=[SQL("DEFAULT ''")], default='')

    class Meta:
        table_name = 'f_item_w'
        indexes = (
            (('x_liste', 'x_mode'), False),
            (('x_liste', 'x_mode', 'x_item'), False),
            (('x_adr',), False),
            (('x_mode',), False),
            (('x_ucd',), False),
        )


class ListeItemModel(BaseModel):

    pk = AutoField(
        column_name='x_pk', primary_key=True)
    liste = CharField(
        column_name='x_liste', max_length=60,
        constraints=[SQL("DEFAULT ''")], default="")
    mode = CharField(
        column_name='x_mode', max_length=1,
        constraints=[SQL("DEFAULT ''")], default="")
    item = CharField(
        column_name='x_item', max_length=40,
        constraints=[SQL("DEFAULT ''")], default="")
    reference = CharField(
        column_name='x_ref', max_length=35,
        constraints=[SQL("DEFAULT ''")], default="")
    qte_dem = FloatField(
        column_name='x_qte_dem', constraints=[SQL("DEFAULT 0.000")], default=0.0)
    qte_serv = FloatField(
        column_name='x_qte_serv', constraints=[SQL("DEFAULT 0.000")], default=0.0)
    lot = CharField(
        column_name='x_lot', max_length=20,
        constraints=[SQL("DEFAULT ''")], default="")
    admin = CharField(
        column_name='x_admin', null=True, max_length=10, constraints=[SQL("DEFAULT ''")], default='')
    tperemp = DateTimeField(
        column_name='x_tperemp', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    is_kit = BooleanField(
        column_name='x_is_kit', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    deroule = BooleanField(
        column_name='x_deroule', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    kit = CharField(
        column_name='x_kit', null=True, max_length=35, constraints=[SQL("DEFAULT ''")], default='')
    adresse_pref = CharField(
        column_name='x_adr_pref', null=True, max_length=19, constraints=[SQL("DEFAULT ''")], default='')
    # go_libre = BooleanField(
    #     column_name='x_go_libre', null=True, constraints=[SQL("DEFAULT 0")])
    dest = CharField(
        column_name='x_dest', max_length=30,
        constraints=[SQL("DEFAULT ''")], default="")
    tquarant = DateTimeField(
        column_name='x_tquarant', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    user = CharField(
        column_name='x_user', null=True, max_length=60, constraints=[SQL("DEFAULT ''")], default='')
    format_p = CharField(
        column_name='x_format_p', null=True, max_length=10, constraints=[SQL("DEFAULT ''")], default='')
    nb_div = IntegerField(
        column_name='x_nb_div', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    etat = CharField(
        column_name='x_etat', max_length=1,
        constraints=[SQL("DEFAULT 'V'")], default="V")
    prix_unitaire = FloatField(
        column_name='x_prix_u', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.0)
    # ret_outi = BooleanField(
    #     column_name='x_ret_outi', null=True, constraints=[SQL("DEFAULT 0")])
    info = CharField(
        column_name='x_info', max_length=80,
        constraints=[SQL("DEFAULT ''")], default="")
    urgent = BooleanField(
        column_name='x_urgent', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    commande_hs = IntegerField(
        column_name='x_cde_hs', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    interface = CharField(
        column_name='x_interface', max_length=15, constraints=[SQL("DEFAULT ''")], default='')
    date_demande = CharField(
        column_name='x_date_dem', null=True, max_length=8, constraints=[SQL("DEFAULT ''")], default='')
    heure_demande = CharField(
        column_name='x_heure_dem', null=True, max_length=8, constraints=[SQL("DEFAULT ''")], default='')
    libelle_unite = CharField(
        column_name='x_lib_unite', null=True, max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    type_demande = CharField(
        column_name='x_typ_dem', null=True, max_length=2, constraints=[SQL("DEFAULT ''")], default='')
    magasin = CharField(
        column_name='x_num_mag', null=True, max_length=3, constraints=[SQL("DEFAULT ''")], default='')
    date_traitement = CharField(
        column_name='x_dt_trait', null=True, max_length=8, constraints=[SQL("DEFAULT ''")], default='')
    heure_traitement = CharField(
        column_name='x_h_trait', null=True, max_length=8, constraints=[SQL("DEFAULT ''")], default='')
    numero_demande = FloatField(
        column_name='x_num_dem', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    quantite_disp = FloatField(
        column_name='x_qte_disp', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.0)
    date_reception = DateField(
        column_name='x_d_recep', null=True, constraints=[SQL("DEFAULT '0000-00-00'")])
    four = CharField(
        column_name='x_four', null=True, constraints=[SQL("DEFAULT ''")])
    contenant = CharField(
        column_name='x_contenant', max_length=20, null=True,
        constraints=[SQL("DEFAULT ''")], default="")
    # magh2 = BooleanField(
    #     column_name='x_magh2', constraints=[SQL("DEFAULT 0")])
    num_ipp = CharField(
        column_name='x_num_ipp', max_length=35,
        constraints=[SQL("DEFAULT ''")], default="")
    num_sej = CharField(
        column_name='x_num_sej', max_length=35,
        constraints=[SQL("DEFAULT ''")], default="")
    # cause_non_delivrance = CharField(
    #     column_name='x_cause_non_delivrance', null=True, constraints=[SQL("DEFAULT ''")])
    adresse_tampon = CharField(
        column_name='x_adr_tampon', null=True, max_length=19, constraints=[SQL("DEFAULT ''")], default='')
    id_chargement = IntegerField(
        column_name='x_id_chargement', constraints=[SQL("DEFAULT 0")], default=0)
    id_chariot = IntegerField(
        column_name='x_id_chariot', constraints=[SQL("DEFAULT 0")], default=0)
    num_face = IntegerField(
        column_name='x_num_face', constraints=[SQL("DEFAULT 0")], default=0)
    dotation_item_add = BooleanField(
        column_name='x_dotitemadd', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    mode_mds = CharField(
        column_name='x_mode_mds', null=True, max_length=1, constraints=[SQL("DEFAULT ''")], default='')
    commentaire_web = CharField(
        column_name='x_commentaire_web', max_length=100, constraints=[SQL("DEFAULT ''")], default='')
    id_presc = IntegerField(
        column_name='x_id_presc', constraints=[SQL("DEFAULT 0")], default=0)
    liste_pat = CharField(
        column_name='x_liste_pat', max_length=60, constraints=[SQL("DEFAULT ''")])
    code_liv = CharField(
        column_name='x_code_liv', max_length=30, constraints=[SQL("DEFAULT ''")], default='')
    dtprise = DateTimeField(
        column_name='x_dtprise', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    moment = CharField(
        column_name='x_moment', max_length=35, constraints=[SQL("DEFAULT ''")], default="")
    commentaire = CharField(
        column_name='x_comment', max_length=80, constraints=[SQL("DEFAULT ''")], default='')
    id_pilulier = CharField(
        column_name='x_id_pilulier', max_length=40, constraints=[SQL("DEFAULT ''")], default="")
    pos_pilulier = IntegerField(
        column_name='x_pos_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    tiroir = IntegerField(
        column_name='x_tiroir', constraints=[SQL("DEFAULT 0")], default=0)
    alveole = IntegerField(
        column_name='x_alveole', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    alveole_theo = IntegerField(
        column_name='x_alveole_theo', constraints=[SQL("DEFAULT 0")], default=0)
    no_pilulier = IntegerField(
        column_name='x_no_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    id_peigne = IntegerField(
        column_name='x_id_peigne', constraints=[SQL("DEFAULT 0")], default=0)
    pilulier_theo = IntegerField(
        column_name='x_pilulier_theo', constraints=[SQL("DEFAULT 0")], default=0)
    item_wms = IntegerField(
        column_name='x_item_wms', constraints=[SQL("DEFAULT 0")], default=0)
    pk_item = IntegerField(
        column_name='x_pk_item', constraints=[SQL("DEFAULT 0")], default=0)
    heure = CharField(
        column_name='x_heure', max_length=4,
        constraints=[SQL("DEFAULT ''")], default="")
    readonly = BooleanField(
        column_name='x_readonly', constraints=[SQL("DEFAULT 0")], default=False)
    qte_prescrite = FloatField(
        column_name='x_qte_prescrite', constraints=[SQL("DEFAULT 0.000")], default=0)
    fraction = IntegerField(
        column_name='x_fraction', constraints=[SQL("DEFAULT 100")], default=100)
    type_servi = CharField(
        column_name='x_type_servi', max_length=10,
        constraints=[SQL("DEFAULT 'GLOBAL_BTE'")], default="GLOBAL_BTE")
    id_servi = IntegerField(
        column_name='x_id_servi', constraints=[SQL("DEFAULT 2")], default=2)
    sous_secteur = CharField(
        column_name='xx_sous_secteur', max_length=100,
        constraints=[SQL("DEFAULT ''")], default="")
    id_plateau = CharField(
        column_name='x_id_plateau', max_length=40,
        constraints=[SQL("DEFAULT ''")], default="")
    complement_envoye = BooleanField(
        column_name='x_complement_envoye',
        constraints=[SQL("DEFAULT 0")], default=0)
    liste_orig = CharField(
        column_name='x_liste_orig', max_length=60,
        constraints=[SQL("DEFAULT ''")], default="")
    posologie = TextField(
        column_name='x_posologie', constraints=[SQL("DEFAULT ''")], default="")
    ucd = CharField(
        column_name='x_id_ucd', max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    cip = CharField(
        column_name='x_cip', max_length=20, constraints=[SQL("DEFAULT ''")], default='')
    # Présent a Bordeaux mais ne semble pas utilisé
    # date_debut = DateTimeField(
    #     column_name='x_date_debut', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    # date_fin = DateTimeField(
    #     column_name='x_date_fin', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])

    class Meta:
        table_name = 'f_item'
        indexes = (
            (('x_liste', 'x_mode', 'x_item'), True),
            (('x_id_peigne',), False),
            (('x_id_pilulier',), False),
            (('x_id_plateau',), False),
            (('x_item',), False),
            (('x_item_wms',), False),
            (('x_liste',), False),
            (('x_mode',), False),
            (('x_pk_item',), False),
            (('x_ref',), False),
            (('xx_sous_secteur',), False),
        )

    def delete_instance(self, recursive=False, delete_nullable=False):
        """When we delete FItem, we must remove related FItemW elements"""
        f_workitems = WorkItemModel.select().where(
            WorkItemModel.liste == self.liste, WorkItemModel.mode == self.mode, WorkItemModel.item == self.item
        )
        for fi in f_workitems:
            fi.delete_instance()

        return super().delete_instance(recursive, delete_nullable)

    def reset_picking(self):
        # first, we delete all f_item_w
        f_workitems = WorkItemModel.select().where(
            WorkItemModel.liste == self.liste, WorkItemModel.mode == self.mode, WorkItemModel.item == self.item
        )
        for fi in f_workitems:
            fi.delete_instance()

        self.etat = "V"
        self.qte_serv = 0
        self.save()
        return True


class ListeValide(BaseModel):

    pk = AutoField(
        column_name='x_pk', primary_key=True)
    chrono = DateTimeField(
        column_name='x_chrono', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")],
        default=dt.datetime.now)
    liste = CharField(
        column_name='x_liste', max_length=60, constraints=[SQL("DEFAULT ''")], index=True)
    ddeb = DateTimeField(
        column_name='x_ddeb', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    service = CharField(
        column_name='x_dest', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    service_label = CharField(
        column_name='x_lib_dest', max_length=50, constraints=[SQL("DEFAULT ''")], default="")
    num_ipp = CharField(
        column_name='x_num_ipp', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    num_sej = CharField(
        column_name='x_num_sej', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    id_prescription = IntegerField(
        column_name='x_id_presc', constraints=[SQL("DEFAULT 0")], default=0)
    nom = CharField(
        column_name='x_nom', max_length=60, constraints=[SQL("DEFAULT ''")])
    nom_jf = CharField(
        column_name='x_nom_jf', max_length=35, constraints=[SQL("DEFAULT ''")])
    prenom = CharField(
        column_name='x_prenom', max_length=60, constraints=[SQL("DEFAULT ''")])
    date_naissance = DateTimeField(
        column_name='x_dtnaiss', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    type_servi = CharField(
        column_name='x_type_servi', max_length=10, constraints=[SQL("DEFAULT 'GLOBAL_BTE'")], default="GLOBAL_BTE")
    sous_secteur = CharField(
        column_name='xx_sous_secteur', max_length=100, constraints=[SQL("DEFAULT ''")], default="")
    id_chariot = IntegerField(
        column_name='x_id_chariot', constraints=[SQL("DEFAULT 0")])
    id_pilulier = CharField(
        column_name='x_id_pilulier', max_length=40, constraints=[SQL("DEFAULT ''")], default="", index=True)
    id_plateau = CharField(
        column_name='x_id_plateau', max_length=40, constraints=[SQL("DEFAULT ''")], default="")
    id_chargement = CharField(
        column_name='x_id_chargement', max_length=19, constraints=[SQL("DEFAULT ''")], default="")
    adr_pilulier = CharField(
        column_name='x_adr_pilulier', max_length=19, constraints=[SQL("DEFAULT ''")], default="")
    pos_pilulier = IntegerField(
        column_name='x_pos_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    pk_pilulier = CharField(
        column_name='x_pk_pilulier', max_length=40, constraints=[SQL("DEFAULT ''")], default="")
    imprimer = IntegerField(
        column_name='x_imprimer', constraints=[SQL("DEFAULT 0")], default=0)
    cr_imprimer = IntegerField(
        column_name='x_cr_imprimer', constraints=[SQL("DEFAULT 0")], default=0)
    mode_sache = IntegerField(
        column_name='x_mode_sache', constraints=[SQL("DEFAULT 0")], default=0)
    chambre = CharField(
        column_name='x_chambre', max_length=10, constraints=[SQL("DEFAULT ''")])
    lit = CharField(
        column_name='x_lit', max_length=10, constraints=[SQL("DEFAULT ''")])
    adr_carnet = IntegerField(
        column_name='x_adr_carnet', constraints=[SQL("DEFAULT 0")], default=0)

    class Meta:
        table_name = 'f_liste_valide'
        indexes = (
            (('x_liste',), False),
            (('x_id_pilulier',), False),
            (('x_id_plateau',), False),
            (('x_id_chargement',), False),
        )


class ItemValide(BaseModel):
    pk = AutoField(
        column_name='x_pk', primary_key=True)
    liste_pk = IntegerField(
        column_name='x_pk_liste', index=True)
    item = CharField(
        column_name='x_item', max_length=40, constraints=[SQL("DEFAULT ''")], index=True)
    reference = CharField(
        column_name='x_ref', max_length=35, constraints=[SQL("DEFAULT ''")], index=True)
    designation = CharField(
        column_name='x_desig', max_length=100, constraints=[SQL("DEFAULT ''")])
    quantite_dem = FloatField(
        column_name='x_qte_dem', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.000)
    quantite_serv = FloatField(
        column_name='x_qte_serv', null=True, constraints=[SQL("DEFAULT 0.000")], default=0.000)
    lot = CharField(
        column_name='x_lot', max_length=20, constraints=[SQL("DEFAULT ''")])
    tperemp = DateTimeField(
        column_name='x_tperemp', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    dtprise = DateTimeField(
        column_name='x_dtprise', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    moment = CharField(
        column_name='x_moment', max_length=35, constraints=[SQL("DEFAULT ''")], default="")
    id_pilulier = CharField(
        column_name='x_id_pilulier', max_length=40, constraints=[SQL("DEFAULT ''")], default="", index=True)
    pos_pilulier = IntegerField(
        column_name='x_pos_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    tiroir = IntegerField(
        column_name='x_tiroir', constraints=[SQL("DEFAULT 0")], default=0)
    alveole = IntegerField(
        column_name='x_alveole', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    alveole_theo = IntegerField(
        column_name='x_alveole_theo', constraints=[SQL("DEFAULT 0")], default=0)
    no_pilulier = IntegerField(
        column_name='x_no_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    id_plateau = CharField(
        column_name='x_id_plateau', max_length=40,
        constraints=[SQL("DEFAULT ''")], default="", index=True)
    pilulier_theo = IntegerField(
        column_name='x_pilulier_theo', constraints=[SQL("DEFAULT 0")], default=0)
    readonly = BooleanField(
        column_name='x_readonly', constraints=[SQL("DEFAULT 0")], default=False)
    pk_item = IntegerField(
        column_name='x_pk_item', constraints=[SQL("DEFAULT 0")], default=0, index=True)
    item_wms = IntegerField(
        column_name='x_item_wms', constraints=[SQL("DEFAULT 0")], default=0, index=True)
    heure = CharField(
        column_name='x_heure', max_length=4,
        constraints=[SQL("DEFAULT ''")], default="")
    qte_prescrite = FloatField(
        column_name='x_qte_prescrite', constraints=[SQL("DEFAULT 0.000")], default=0)
    fraction = IntegerField(
        column_name='x_fraction', constraints=[SQL("DEFAULT 100")], default=100)
    type_servi = CharField(
        column_name='x_type_servi', max_length=10,
        constraints=[SQL("DEFAULT 'GLOBAL_BTE'")], default="GLOBAL_BTE")
    sous_secteur = CharField(
        column_name='xx_sous_secteur', max_length=100,
        constraints=[SQL("DEFAULT ''")], default="", index=True)
    doublon = IntegerField(
        column_name='x_doublon', constraints=[SQL("DEFAULT 0")], default=0,)
    nom = CharField(
        column_name='x_nom', max_length=60, constraints=[SQL("DEFAULT ''")])
    nom_jf = CharField(
        column_name='x_nom_jf', max_length=35, constraints=[SQL("DEFAULT ''")])
    prenom = CharField(
        column_name='x_prenom', max_length=60, constraints=[SQL("DEFAULT ''")])
    date_naissance = DateTimeField(
        column_name='x_dtnaiss', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    sexe = CharField(
        column_name='x_sexe', max_length=1, constraints=[SQL("DEFAULT ''")])
    chambre = CharField(
        column_name='x_chambre', max_length=10, constraints=[SQL("DEFAULT ''")])
    lit = CharField(
        column_name='x_lit', max_length=10, constraints=[SQL("DEFAULT ''")])
    id_presc = IntegerField(
        column_name='x_id_presc', constraints=[SQL("DEFAULT 0")], default=0)
    num_ipp = CharField(
        column_name='x_num_ipp', max_length=35,
        constraints=[SQL("DEFAULT ''")], default="")
    sejour = CharField(
        column_name='x_sejour', max_length=35, constraints=[SQL("DEFAULT ''")])
    pk_doublon = IntegerField(
        column_name='x_pk_doublon', constraints=[SQL("DEFAULT 0")], default=0,)
    serial_doublon = CharField(
        column_name='x_serial_doublon', max_length=20, constraints=[SQL("DEFAULT ''")])
    info = CharField(
        column_name='x_info', max_length=80,
        constraints=[SQL("DEFAULT ''")], default="")

    class Meta:
        table_name = 'f_item_valide'
        indexes = (
            (('x_item',), False),
            (('x_ref',), False),
            (('x_pk_liste',), False),
            (('x_pk_item',), False),
            (('x_id_pilulier',), False),
            (('x_id_plateau',), False),
            (('x_item_wms',), False),
            (('xx_sous_secteur',), False),
        )


class ListeModel(BaseModel):

    pk = AutoField(
        column_name='x_pk', primary_key=True)
    liste = CharField(
        column_name='x_liste', max_length=60, constraints=[SQL("DEFAULT ''")])
    date_creation = DateTimeField(
        column_name='x_tcreat', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")],
        default=dt.datetime.now)
    etat = CharField(
        column_name='x_etat', max_length=1, constraints=[SQL("DEFAULT ''")], default="")
    mode = CharField(
        column_name='x_mode',  max_length=1, constraints=[SQL("DEFAULT ''")], default="")
    fusion = CharField(
        column_name='x_fusion', max_length=60, constraints=[SQL("DEFAULT ''")], default="")
    nb_item = IntegerField(
        column_name='x_nb_item', constraints=[SQL("DEFAULT 0")], default=0)
    service = CharField(
        column_name='x_dest', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    date_modification = DateTimeField(
        column_name='x_tmodif', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")],
        default=dt.datetime.now)
    sequence = CharField(
        column_name='x_sequence', max_length=25, null=True, constraints=[SQL("DEFAULT ''")], default="")
    interface = CharField(
        column_name='x_interface', max_length=15, constraints=[SQL("DEFAULT ''")], default="")
    num_ipp = CharField(
        column_name='x_num_ipp', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    num_sej = CharField(
        column_name='x_num_sej', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    zone_deb = CharField(
        column_name='x_zone_deb', max_length=20, constraints=[SQL("DEFAULT ''")], default="")
    zone_fin = CharField(
        column_name='x_zone_fin', max_length=20, constraints=[SQL("DEFAULT ''")], default="")
    dot = CharField(
        column_name='x_dot', null=True, max_length=35, constraints=[SQL("DEFAULT ''")], default="")
    date_reception = DateTimeField(
        column_name='x_date_rece', null=True, constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    impression_transfert = BooleanField(
        column_name='x_imp_transfert', null=True, constraints=[SQL("DEFAULT 0")], default=0)
    type_liste_web = IntegerField(
        column_name='x_type_liste_web', constraints=[SQL("DEFAULT 0")], default=0)
    username = CharField(
        column_name='x_createur', max_length=20, constraints=[SQL("DEFAULT ''")])
    ddeb = DateTimeField(
        column_name='x_ddeb', constraints=[SQL("DEFAULT '0000-00-00 00:00:00'")])
    moment = CharField(
        column_name='x_moment', null=True, max_length=35, constraints=[SQL("DEFAULT ''")], default='')
    ipp = CharField(
        column_name='x_ipp', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    id_prescription = IntegerField(
        column_name='x_id_presc', constraints=[SQL("DEFAULT 0")], default=0)
    liste_pat = CharField(
        column_name='x_liste_pat', max_length=60, constraints=[SQL("DEFAULT ''")], default="")
    code_livraison = CharField(
        column_name='x_code_liv', max_length=30, constraints=[SQL("DEFAULT ''")], default="")
    type_servi = CharField(
        column_name='x_type_servi', max_length=10, constraints=[SQL("DEFAULT 'GLOBAL_BTE'")], default="GLOBAL_BTE")
    id_servi = IntegerField(
        column_name='x_id_servi', constraints=[SQL("DEFAULT 2")], default=2)
    robot = CharField(
        column_name='x_robot', max_length=20, constraints=[SQL("DEFAULT ''")], default="")
    sous_secteur = CharField(
        column_name='xx_sous_secteur', max_length=100, constraints=[SQL("DEFAULT ''")], default="")
    selectionne = IntegerField(
        column_name='x_selectionne', constraints=[SQL("DEFAULT 0")], default=0)
    origine_sel = CharField(
        column_name='x_origine_sel', max_length=20, constraints=[SQL("DEFAULT ''")], default="")
    valide_sel = BooleanField(
        column_name='x_valide_sel', constraints=[SQL("DEFAULT 0")], default=False)
    id_pilulier = CharField(
        column_name='x_id_pilulier', max_length=40, constraints=[SQL("DEFAULT ''")], default="")
    id_plateau = CharField(
        column_name='x_id_plateau', max_length=40, constraints=[SQL("DEFAULT ''")], default="")
    no_pilulier = IntegerField(
        column_name='x_no_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    id_peigne = IntegerField(
        column_name='x_id_peigne', constraints=[SQL("DEFAULT 0")], default=0)
    tiroir = IntegerField(
        column_name='x_tiroir', constraints=[SQL("DEFAULT 0")], default=0)
    pos_pilulier = IntegerField(
        column_name='x_pos_pilulier', constraints=[SQL("DEFAULT 0")], default=0)
    id_chargement = CharField(
        column_name='x_id_chargement', max_length=19, constraints=[SQL("DEFAULT ''")], default="")
    id_chariot = IntegerField(
        column_name='x_id_chariot', constraints=[SQL("DEFAULT 0")])
    adr_pilulier = CharField(
        column_name='x_adr_pilulier', max_length=19, constraints=[SQL("DEFAULT ''")], default="")
    pk_pilulier = CharField(
        column_name='x_pk_pilulier', max_length=40, constraints=[SQL("DEFAULT ''")], default="")
    num_face = IntegerField(
        column_name='x_num_face', constraints=[SQL("DEFAULT 0")], default=0)
    liste_origine = CharField(
        column_name='x_liste_orig', null=True, max_length=60,
        constraints=[SQL("DEFAULT ''")], default=""
    )
    adr_carnet = IntegerField(
        column_name='x_adr_carnet', constraints=[SQL("DEFAULT 0")], default=0)
    with_note = TinyIntegerField(
        column_name='x_with_note', constraints=[SQL("DEFAULT 0")], default=0)

    class Meta:
        table_name = 'f_liste'
        indexes = (
            (('x_liste', 'x_mode'), True),
            (('x_id_plateau',), False),
            (('x_liste',), False),
            (('x_mode',), False),
            (('xx_sous_secteur',), False),
        )

    def save(self, force_insert=False, only=None):
        """Enforce control on each information passed"""
        if self.mode == 'S' and self.type_servi in MODE_NOMINATIF:
            self.ipp = self.num_ipp
            if self.id_prescription is None:
                raise ValueError('No prescription found')
            if self.num_ipp is None:
                raise ValueError('No IPP found')
        elif self.mode == 'S' and self.fusion in FUSION_SORTIE_LOT:
            if self.type_servi is None:
                raise ValueError('No Type Servi found')
            if self.etat is None:
                self.etat = 'V'
        elif self.mode == 'S' and self.fusion in FUSION_SORTIE_PERIME:
            if self.type_servi is None:
                raise ValueError('No Type Servi found')
            if self.etat is None or self.etat == '':
                self.etat = 'V'
        if not self.num_ipp and self.mode == 'S':
            raise ValueError('Num IPP is missing')
        if not self.num_sej and self.mode == 'S':
            raise ValueError('Num Sejour is missing')
        if not self.etat:
            self.etat = EtatListe.Vierge.value
        if self.type_servi == TypeServiListe.RiedlBoite.value and not self.zone_deb:
            self.zone_deb = "RIEDL"
        return super().save(force_insert, only)

    def delete_instance(self, recursive=False, delete_nullable=False):
        """When we delete FListe, we must remove related FItem"""
        fi_list = FItem.select().where(FItem.liste == self.liste, FItem.mode == self.mode)
        for fi in fi_list:
            fi.delete_instance()

        # Delete also liste error if exists
        err_list = FListeError.select().where(FListeError.liste == self.liste, FListeError.mode == self.mode)
        for er in err_list:
            er.delete_instance()

        return super().delete_instance(recursive, delete_nullable)

    def reset_picking(self):
        if self.mode == "E":
            raise ValueError('We cannot process on entry list')

        fi_list = FItem.select().where(FItem.liste == self.liste, FItem.mode == self.mode)
        for fi in fi_list:
            fi.reset_picking()

        self.etat = "V"
        self.selectionne = 0
        self.id_chargement = ""
        self.id_plateau = ""
        self.origine_sel = ""
        self.valide_sel = False
        self.adr_pilulier = ""
        self.save()
        return True


# Backward compatibility
Dispensation = ListeModel  # noqa
DispensationItem = ListeItemModel  # noqa
DispensationError = ListeErrorModel  # noqa
# TODO: Delete below when version 2 is release
FItem = ListeItemModel  # noqa
FListe = ListeModel  # noqa
FListeError = ListeErrorModel  # noqa
