# Copyright 2020 Le Filament (<http://www.le-filament.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from datetime import datetime, timedelta
from odoo import models, fields, api


class Project(models.Model):
    _inherit = "project.project"

    privacy_visibility = fields.Selection([
            ('followers', 'On invitation only'),
            ('employees', 'Visible by all employees'),
            ('portal', 'Visible by following customers'),
        ],
        string='Confidentialité', required=True,
        default='employees')
    # Champs étape "Demande" => Vue générale
    name_subtitle = fields.Char("Sous-titre")
    first_contact_id = fields.Many2one(
        'res.partner',
        string='1er contact',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False)],
        on_delete='restrict')
    type_contact = fields.Selection([
        ('pdp', 'Porteur de projet'),
        ('adherent', 'Adhérent'),
        ('no_adherent', 'Non adhérent')],
        string="Type contact")
    date_first_contact = fields.Date(
        "Date de 1er contact",
        default=fields.Date.today)
    prescripteur_id = fields.Many2one(
        'res.partner',
        string='Prescripteur',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False)],
        on_delete='restrict')
    prescripteur_company_id = fields.Many2one(
        'res.partner',
        string='Structure prescripteur',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', True)],
        on_delete='restrict')
    porteurs_projets_ids = fields.Many2many(
        comodel_name='res.partner.porteur.project',
        relation='res_partner_porteur_project_rel',
        column1='porteur_id',
        column2='project_id', 
        string="Porteurs de projet")
    description = fields.Text("Description")
    territoire_id = fields.Many2one(
        'res.partner',
        string='Territoire',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', True),
            ('type_structure_id', '!=', False)],
        on_delete='restrict')
    user_id = fields.Many2one(
        'res.users', 
        string='CFD', 
        default=lambda self: self.env.user, 
        track_visibility="onchange")

    # Champs étape "Instruction" => Vue générale
    od_id = fields.Many2one(
        'res.partner',
        string='OD',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', True)],
        on_delete='restrict')
    animateur_id = fields.Many2one(
        'res.partner',
        string='Animateur',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False)],
        on_delete='restrict')
    type_convention_id = fields.Many2one(
        'adefpat.type.convention', 
        domain=[
            '|', ('date_end_validity', '>=', fields.Date.today()),
            ('date_end_validity', '=', False)],
        string="Type de convention de financement")
    date_ca = fields.Date("Date de CA pressenti")
    date_start = fields.Date("Date de démarrage prévisionnel")
    # list_photos_ids = fields.One2many('images')
    # documents_ids = fields.One2many('ir.attachment', "Documents")

    # Champs étape "Instruction" => Onglet Dossier
    contexte = fields.Text("Contexte projet")
    caract_beneficiaire = fields.Text("Caractéristiques du bénéficiaire")
    historique = fields.Text("Historique & Aujourd’hui")
    besoins_beneficiaires = fields.Text("Besoins des bénéficiaires")
    objectifs_accompagnement = fields.Text("Objectifs d’accompagnement / compétences à acquérir (pour le bénéficiaire)")
    competences_requises = fields.Text("Compétences requises pour le consultant formateur")
    secteurs_requis = fields.Text("Secteurs d’activités dont la connaissance est requise pour le consultant formateur")
    modalites_intervention = fields.Text("Modalités d'intervention")
    modalites_facturation = fields.Text("Modalités de facturation")
    modalites_reponse = fields.Text("Modalités de réponse")

    # Infos dossier CA
    type_beneficiaire = fields.Selection(
        [
            ('demandeur', "Demandeur d'emploi"),
            ('dirigeant', "Dirigeant"),
            ('salaries', "Salariés"),
            ('agriculteur', 'Agriculteur'),
            ('elu', 'Élu'),
            ('inactif', 'Inactif'),
            ('administrateur', 'Administrateur'),
            ('charge_dev', "Chargé de développement")
        ],
        string="Type de bénéficiaires")
    objectif_projet = fields.Selection(
        [
            ('creation', "Création d'entreprise"),
            ('post_creation', 'Post-création'),
            ('reprise', 'Reprise'),
            ('operation', "Opération territoriale pour les entreprises"),
            ('emergence', 'Émergence'),
            ('consolidation', 'Consolidation'),
            ('creation_activite', 'Création nouvelle activité'),
            ('transmission', 'Transmission'),
            ('post_reprise', 'Post-reprise'),
            ('projet_inter', 'Projet inter-entreprise'),
            ('projet_structurant', 'Projet structurant territoire'),
        ],
        string="Objectif projet")
    secteur_crit = fields.Selection(
        [
            ('agro_alimentaire', 'Agro-alimentaire'),
            ('service', 'Service'),
            ('tourisme', 'Tourisme - Hôtellerie - Restauration'),
            ('artisanat', 'Artisanat - Commerce - Industrie'),
            ('intersectoriel', 'Intersectoriel'),
            ('environnement', 'Environnement'),
            ('culture', 'Culture'),
            ('agriculture', 'Agriculture'),
            ('service', 'Services à la population'),
        ],
        string="Secteur d'activité")
    taille = fields.Selection(
        [
            ('inf_10', "De 10 à 250"),
            ('sup_10', "< 10 salariés")
        ],
        string="Taille entreprise")
    objectif_formation = fields.Selection(
        [
            ('def_projet', "Définition de projet"),
            ('def_modele_eco', "Définition d'un modèle économique"),
            ('def_strat_com', "Définition d'une stratégie de développement"),
            ('diagnostic', 'Diagnostic stratégique'),
            ('marketing', "Marketing  - Commercialisation - Promotion - Communication"),
            ('orga_collective', 'Organisation collective'),
            ('gestion_prod', 'Gestion de production'),
            ('gestion_financ', 'Gestion financière'),
            ('management', 'Management - Organisation - RH'),
        ],
        string="Objectif formation")
    type_formation = fields.Selection(
        [
            ('individuelle', 'Générale individuelle'),
            ('collective', 'Générale collective'),
            ('indiv_collect', 'Générale collective individualisée'),
        ],
        string="Type formation")
    encadrement = fields.Selection(
        [
            ('minimis', 'De minimis'),
            ('neant', 'Neant'),
            ('encadrement', 'Encadrement des aides à la formation')
        ],
        string="Encadrement Aides")
    lieu = fields.Text("Lieu")
    periode_realisation = fields.Text("Période de réalisation")
    # duree_totale
    # info_budget

    # Champs étape "Instruction" => Onglet Consultation
    consulant_ids = fields.Many2many(
        comodel_name='res.partner.consultants.project',
        relation='res_partner_consultants_project_rel',
        column1='consultant_id',
        column2='project_id', 
        string="Consultants")

    # Champs étape "Instruction" => Onglet GAP
    elu_referent_id = fields.Many2one(
        'res.partner',
        string='Élu référent',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False)],
        on_delete='restrict')
    membre_ids = fields.Many2many(
        comodel_name='res.partner.membres.project',
        relation='res_partner_membres_project_rel',
        column1='membre_id',
        column2='project_id', 
        string="Membres")
    # documents_gap_ids = fields.One2many('ir.attachment', string="Documents GAP")
    modalite_gap = fields.Text("Modalités GAP")
    reunion_ids = fields.One2many(
        'adefpat.reunion.gap', 
        'project_id', 
        string="Réunions")

    # Champs étape "Prêt pour CA" => Onglet Général
    num_dossier = fields.Char("Numéro de dossier")

    @api.multi
    def validate_ca(self):
        for project in self:
            project.num_dossier = datetime.strftime(datetime.today(), '%y') + self.env['ir.sequence'].next_by_code(
                'increment_num_dossier')

    @api.onchange('prescripteur_id')
    def onchange_prescripteur_id(self):
        if self.prescripteur_id:
            self.prescripteur_company_id = False
            relation_model = self.env['res.partner.relation.all']
            relation_ids = relation_model.search([('this_partner_id', '=', self.prescripteur_id.id)])
            partner_list = relation_ids.mapped('other_partner_id.id')
            b = {'domain': {'prescripteur_company_id': [('id', 'in', partner_list)]}}
        else:
            b = {'domain': {'prescripteur_company_id': []}}
        return b


class AdefpatTypeConvention(models.Model):
    _name = 'adefpat.type.convention'
    _description = 'Liste type de convetion'

    name = fields.Char("Convention")
    date_end_validity = fields.Date("Date de fin de validité")


class AdefpatReunionGAP(models.Model):
    _name = 'adefpat.reunion.gap'
    _description = 'Réunions GAP'

    # document_ids = fields.One2many('ir.attachment', string="Documents")
    date = fields.Date("Date du GAP")
    project_id = fields.Many2one(
        'project.project',
        string='Projet',
        default=lambda self: self.env.context.get('default_project_id'))


class AdefpatMembresProjets(models.Model):
    _name = 'res.partner.membres.project'
    _description = 'Membres'

    partner_id = fields.Many2one(
        'res.partner',
        string='Membre',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False)],
        on_delete='restrict')
    structure_liee_id = fields.Many2one(
        'res.partner',
        string='Structure liée',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', True)],
        on_delete='restrict')
    lastname = fields.Char(
        related='partner_id.lastname', 
        string="Nom",
        store=False)
    firstname = fields.Char(
        related='partner_id.firstname', 
        string="Prénom",
        store=False)
    commune = fields.Char(
        related='partner_id.city', 
        string="Commune",
        store=False)
    mobile = fields.Char(
        related='partner_id.mobile', 
        string="Mobile",
        store=False)
    fixe = fields.Char(
        related='partner_id.phone', 
        string="Fixe",
        store=False)
    email = fields.Char(
        related='partner_id.email', 
        string="Email",
        store=False)

    @api.onchange('partner_id')
    def onchange_prescripteur_id(self):
        if self.partner_id:
            self.structure_liee_id = False
            relation_model = self.env['res.partner.relation.all']
            relation_ids = relation_model.search([('this_partner_id', '=', self.partner_id.id)])
            partner_list = relation_ids.mapped('other_partner_id.id')
            b = {'domain': {'structure_liee_id': [('id', 'in', partner_list)]}}
        else:
            b = {'domain': {'structure_liee_id': []}}
        return b


class AdefpatConsultantsProjets(models.Model):
    _name = 'res.partner.consultants.project'
    _description = 'Consultants'

    partner_id = fields.Many2one(
        'res.partner',
        string='Consultant',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False),
            ('is_consultant_form', '=', True),
            '|', ('reference', '=', 'reference'),
            ('reference', '=', 'prereference')],
        on_delete='restrict')
    lastname = fields.Char(
        related='partner_id.lastname', 
        string="Nom",
        store=False)
    firstname = fields.Char(
        related='partner_id.firstname', 
        string="Prénom",
        store=False)
    mobile = fields.Char(
        related='partner_id.mobile', 
        string="Mobile",
        store=False)
    email = fields.Char(
        related='partner_id.email', 
        string="Email",
        store=False)
    reference = fields.Selection([
        ('reference', 'Référencé'),
        ('prereference', 'Pré-Référencé'),
        ('dereference', 'Dé-Référencé')],
        related='partner_id.reference',
        string="Référencement",
        store=False)
    date_cdc = fields.Date("Date d'envoi du CDC")
    cout_journée = fields.Float("Coût journée")
    # document_ids = fields.One2many('ir.attachment', string="Documents Consultants")
    date_selection = fields.Date("Date de sélection")
    date_notification = fields.Date("Date de notification")


class AdefpatPorteursProjets(models.Model):
    _name = 'res.partner.porteur.project'
    _description = 'Porteurs de projets'

    partner_id = fields.Many2one(
        'res.partner',
        string='Porteur de projet',
        domain=[
            ('active', '=', True), 
            ('is_company', '=', False)],
        on_delete='restrict')
    lastname = fields.Char(
        related='partner_id.lastname', 
        string="Nom",
        store=False)
    firstname = fields.Char(
        related='partner_id.firstname', 
        string="Prénom",
        store=False)
    commune = fields.Char(
        related='partner_id.city', 
        string="Commune",
        store=False)
    mobile = fields.Char(
        related='partner_id.mobile', 
        string="Mobile",
        store=False)
    fixe = fields.Char(
        related='partner_id.phone', 
        string="Fixe",
        store=False)
    email = fields.Char(
        related='partner_id.email', 
        string="Email",
        store=False)
    statut = fields.Selection(
        [
            ('demandeur', "Demandeur d'emploi"),
            ('dirigeant', "Dirigeant"),
            ('salaries', "Salariés"),
            ('agriculteur', 'Agriculteur'),
            ('elu', 'Élu'),
            ('inactif', 'Inactif'),
            ('administrateur', 'Administrateur'),
            ('charge_dev', "Chargé de développement")
        ],
        string="Statut")
    eligible = fields.Boolean(
        string="Eligible")