# -*- coding: utf-8 -*-

from odoo import fields, models, api
import base64
from werkzeug.urls import url_encode

import datetime
from odoo.exceptions import UserError
from datetime import datetime, date, timedelta


class Partner(models.Model):
    _inherit = 'res.partner'

    @api.model
    def _default_company_id(self):
        if self._context.get('default_project_id'):
            return self.env['project.project'].browse(self._context['default_project_id']).company_id
        return self.env.company

    def _default_effectif(self):
        if self.effectif_dads:
            self.effectif = self.effectif_dads

        return self.effectif

    @api.model
    def year_selection(self):
        year = 2000  # replace 2000 with your a start year
        year_list = []
        while year != 2030:  # replace 2030 with your end year
            year_list.append((str(year), str(year)))
            year += 1
        return year_list

    @api.model
    def mois_selection(self):
        mois = 1  # replace 2000 with your a start year
        mois_list = []
        while mois != 10:  # replace 2030 with your end year
            mois_list.append(('0' + str(mois), '0' + str(mois)))
            mois += 1
        mois_list.append((str(10), str(10)))
        mois_list.append((str(11), str(11)))
        mois_list.append((str(12), str(12)))
        return mois_list
    date_renouvel = fields.Date('date de renouvelement')

    appel_cot_year = fields.Selection(year_selection, string="Année",
                                      default='2020')  # as a default value it would be 2019
    appel_cot_mois = fields.Selection(mois_selection, string="Mois",
                                      default='01')  # as a default value it would be 2019

    def _appel_autorise_default(self):

        self.appel_autorise = True

        return True

    contact_m2m_ids = fields.Many2many( "res.partner","rel_table","direct_rel_id","back_rel_id",string="Contacts")
    other_company = fields.Many2many(  "res.partner",  "rel_table","back_rel_id", "direct_rel_id",string="Sociétés " )
    #
    # other_company = fields.Many2many('res.partner','id',string='Societé')
    # other_company_ids =fields.Many2many('res.partner','other_company',string='Contacts')


    # function = fields.Many2one('function.occuped', 'Job Position')
    function2 = fields.Many2one('function.occuped', 'Poste occupé')
    college_lycee = fields.Boolean(string='college_lycee', invisible=True, default=False)
    commission = fields.Boolean(string='commission', invisible=True, default=False)
    dirigeant = fields.Boolean(string='dirigeant', invisible=True, default=False)
    protocolaires = fields.Boolean(string='protocolaires', invisible=True, default=False)
    rh_comptable = fields.Boolean(string='rh_comptable', invisible=True, default=False)
    adherent = fields.Boolean(string='Adhérent ', default=False)
    email_existe = fields.Boolean(string='existe ', compute='_compute_email_existe', store=True)
    mail_notif = fields.Boolean(string='mail notif ', default=False)

    # partie groupe
    public = fields.Boolean(string='Public')
    prive = fields.Boolean(string='Privé')

    commission_paritaire_salaires = fields.Boolean(string='Commission Paritaire salaires / Jury CQPM')
    cprefp = fields.Boolean(string='CPREFP')

    bureau_uimm79 = fields.Boolean(string='Bureau UIMM 79', default=False)
    club_RH = fields.Boolean(string='Club RH', default=False)

    mde = fields.Boolean(string='MDE / Missions Locales', default=False)

    # partie groupe

    # res_createur_id  =  fields.Many2one('product.template', string='Créateur')
    member_categ_id = fields.Many2one('member.categ', string='Type de membres')
    siret = fields.Char(string='N° SIRET')
    code_naf = fields.Char(string='Code NAF')
    fax = fields.Char(string='Fax')
    activite = fields.Char(string='Activité')

    rubrique_anuaire = fields.Many2one('secteur.activite', string='Secteur d’activité')

    appel_autorise = fields.Boolean(string='Appel autorisé', default=_appel_autorise_default)

    ligne_tel_direct = fields.Char('Ligne téléphonique directe')

    appartenance_indiq = fields.Char("Si appartenance à un groupe, merci d'indiquer son nom")
    section_syndicale = fields.Many2many('section.syndicale', string='Section(s) syndicale(s)')
    cse = fields.Boolean('CSE')
    chiffre_affaires = fields.Char("Chiffre d'affaires H.T")

    # appel cotisation fields
    raison_social = fields.Char(string='Raison sociale')
    addresse_appel_cotisation = fields.Char(string='Adresse')

    effectif_dads = fields.Integer(string='Effectif DSN')
    effectif = fields.Integer(string='Effectif', default=_default_effectif)

    total_brut_dads = fields.Float(string='Total salaires bruts declares DSN année')

    nombre_salaries = fields.Float(string='Nombre de salarié jeune industrie')

    montant_total_cotisation = fields.Float(string='Montant Total de la cotistation', readonly=True)
    sous_total_cotisation = fields.Float(string='Montant Total de la cotistation sans jeune industrie', readonly=True)

    c1_tranche = fields.Float(string='Premiére tranche', readonly=True)
    c2_tranche = fields.Float(string='Deuxieme tranche', readonly=True)
    c3_tranche = fields.Float(string='Troisième tranche', readonly=True)

    cotisation_his_ids = fields.One2many('cotisation.product.historique', 'partner_id', string='Historique cotisation',
                                         readonly=True)

    territoire_id = fields.Many2one('territoire', string='Territoire')
    group_id = fields.Many2many('res.partner.group', string='Groupes')

    fr = fields.Char(string='France')
    exporter = fields.Char(string='Exporter')

    company_id = fields.Many2one('res.company', string='Company', required=True, default=_default_company_id)

    # company_type = fields.Selection(string='Company Type',
    #                                 selection=[('person', 'Individual'), ('company', 'Company')],
    #                                 compute='_compute_company_type', inverse='_write_company_type', default='company')

    _defaults = {
        'appel_autorise': _appel_autorise_default,
    }


    @api.model_create_multi
    def create(self, vals_list):
        res= super(Partner, self).create(vals_list)

        if res :
            if res.mail_notif :
                template = self.env.ref('gestion_adherents.email_template_adherent_creation')
                all_user = res.env['res.users'].search([])
                partner_ids=[]
                for user in all_user:
                    if user.has_group('base.group_user'):
                        partner_ids.append(user.partner_id.id)
                if  partner_ids:
                    template.send_mail(res.id, force_send=True,email_values={'recipient_ids': partner_ids})
        return res

    def _compute_email_existe(self):
        for record in self:
            rec_ids = self.search([('email', '=', record.email)], order='id desc')
            record.email_existe = True
            if len(rec_ids) > 1:
                rec_ids[0].email_existe = True
                for rec in rec_ids:
                    if rec.id != rec_ids[0].id:
                        rec.email_existe = False

    @api.onchange('name')
    def raison_social_default(self):
        if self.company_type == "company" and self.name:
            self.raison_social = self.name

    @api.onchange('group_id')
    def onchange_group_id(self):
        self.college_lycee = False
        self.commission = False
        self.dirigeant = False
        self.protocolaires = False
        self.rh_comptable = False

        for group in self.group_id:
            if group.type_group == 'college_lycee':
                self.college_lycee = True
            if group.type_group == 'commission':
                self.commission = True
            if group.type_group == 'dirigeant':
                self.dirigeant = True
            if group.type_group == 'protocolaires':
                self.protocolaires = True
            if group.type_group == ('rh_comptable'):
                self.rh_comptable = True

    @api.onchange('effectif_dads')
    def onchange_effectif_dads(self):
        if self.effectif_dads:
            self.effectif = self.effectif_dads

    @api.onchange('effectif')
    def onchange_effectif(self):
        if self.effectif:
            self.effectif_dads = self.effectif

    # Générer Adhésion

    # calcule le montant total de cotisation
    def calcule_montant_tot_cotisation(self):
        if self.member_categ_id.name == 'MEMBRE' or not self.member_categ_id.name:
            c0 = 0
            c2 = 0
            c3 = 0
            c1 = 0

            if self.total_brut_dads:
                # montant total inf a 3 m£
                if self.total_brut_dads <= 3000000:
                    if self.total_brut_dads <= 250000:
                        c0 = 450
                    else:
                        c0 = (self.total_brut_dads / 1000) * (1.8)
                # montant total sup a 3 m£
                if self.total_brut_dads > 3000000:

                    c1 = (3000000 / 1000) * 1.8
                    rest_a_paye = (self.total_brut_dads - 3000000)

                    if self.total_brut_dads > 9000000:
                        c2 = (6000000 / 1000) * 1.35
                        c3 = ((self.total_brut_dads - 9000000) / 1000) * 1.01
                    else:
                        c2 = (rest_a_paye / 1000) * 1.35
            self.c1_tranche = c1
            self.c2_tranche = c2
            self.c3_tranche = c3
            ji = self.nombre_salaries
            self.montant_total_cotisation = ji + c0 + c1 + c2 + c3
            self.sous_total_cotisation = c0 + c1 + c2 + c3
        if self.member_categ_id.name == 'GROUPE':

            c0 = 0
            c2 = 0
            c3 = 0
            c1 = 0

            if self.total_brut_dads:
                # montant total inf a 3 m£
                if self.total_brut_dads <= 3000000:
                    if self.total_brut_dads <= 250000:
                        c0 = 450

                    else:
                        c0 = (self.total_brut_dads / 1000) * (1.8)

                # montant total sup a 3 m£

                if self.total_brut_dads > 3000000:

                    c1 = (3000000 / 1000) * 1.8

                    rest_a_paye = (self.total_brut_dads - 3000000)

                    if rest_a_paye > 9000000:
                        c2 = (6000000 / 1000) * 1.35

                        rest_a_paye = (rest_a_paye - 6000000)
                        c3 = (rest_a_paye / 1000) * 1.01


                    else:
                        c2 = (rest_a_paye / 1000) * 1.35

            self.c1_tranche = c1
            self.c2_tranche = c2
            self.c3_tranche = c3

            ji = self.nombre_salaries

            self.montant_total_cotisation = ji + c0 + c1 + c2 + c3
            self.sous_total_cotisation = c0 + c1 + c2 + c3

        if self.member_categ_id.name == 'GIFAS':
            c0 = 0

            if self.total_brut_dads:
                # montant total inf a 3 m£

                if self.total_brut_dads <= 250000:
                    c0 = 450

                else:
                    c0 = (self.total_brut_dads / 1000) * (0.41)

            ji = self.nombre_salaries

            self.montant_total_cotisation = ji + c0
            self.sous_total_cotisation = c0
            self.c1_tranche = 0
            self.c2_tranche = 0
            self.c3_tranche = 0

        if self.member_categ_id.name == 'NON METAUX':
            c0 = 0

            if self.total_brut_dads:
                # montant total inf a 3 m£

                if self.total_brut_dads <= 250000:
                    c0 = 450

                else:
                    c0 = (self.total_brut_dads / 1000) * (0.41)

            ji = self.nombre_salaries

            self.montant_total_cotisation = ji + c0
            self.sous_total_cotisation = c0
            self.c1_tranche = 0
            self.c2_tranche = 0
            self.c3_tranche = 0

        return self.montant_total_cotisation

    def _get_share_url(self, redirect=False, signup_partner=False, pid=None):
        """
        Build the url of the record  that will be sent by mail and adds additional parameters such as
        access_token to bypass the recipient's rights,
        signup_partner to allows the user to create easily an account,
        hash token to allow the user to be authenticated in the chatter of the record portal view, if applicable
        :param redirect : Send the redirect url instead of the direct portal share url
        :param signup_partner: allows the user to create an account with pre-filled fields.
        :param pid: = partner_id - when given, a hash is generated to allow the user to be authenticated
            in the portal chatter, if any in the target page,
            if the user is redirected to the portal instead of the backend.
        :return: the url of the record with access parameters, if any.
        """
        self.ensure_one()
        params = {
            'model': self._name,
            'res_id': self.id,
        }
        if hasattr(self, 'access_token'):
            params['access_token'] = self._portal_ensure_token()
        if pid:
            params['pid'] = pid
            params['hash'] = self._sign_token(pid)
        if signup_partner and hasattr(self, 'partner_id') and self.partner_id:
            params.update(self.partner_id.signup_get_auth_param()[self.partner_id.id])

        return '%s?%s' % ('/mail/view' if redirect else self.access_url, url_encode(params))

    def action_qmail_send(self):

        self.ensure_one()
        lang = self.env.context.get('lang')
        template_id = self.env.ref('mail.email_template_partner').id

        report = self.env.ref('gestion_adherents.action_report_adherents').render_qweb_pdf(self.ids[0])
        filename = 'Fiche adherents' + '.pdf'
        attachment = self.env['ir.attachment'].create({
            'name': filename,
            'type': 'binary',
            'datas': base64.b64encode(report[0]),
            # 'datas_fname': filename,
            'store_fname': filename,
            'res_model': 'res.partner',
            'res_id': self.ids[0],
            'mimetype': 'application/x-pdf'
        })
        cotisations_report = self.env.ref('gestion_adherents.action_cotisations_report').render_qweb_pdf(self.ids[0])
        filename_cotisations = 'Bordereaux_de_cotisations' + '.pdf'
        attachment_cotisations = self.env['ir.attachment'].create({
            'name': filename_cotisations,
            'type': 'binary',
            'datas': base64.b64encode(cotisations_report[0]),
            # 'datas_fname': filename_cotisations,
            'store_fname': filename_cotisations,
            'res_model': 'res.partner',
            'res_id': self.ids[0],
            'mimetype': 'application/x-pdf'
        })
        ctx = {
            'default_model': 'res.partner',
            'active_model': 'res.partner',
            'active_id': self.ids[0],
            'default_res_id': self.ids[0],
            'default_composition_mode': 'comment',
            'mark_so_as_sent': True,
            'default_use_template': bool(template_id),
            'default_template_id': template_id,
            'custom_layout': "mail.mail_notification_paynow",
            'proforma': self.env.context.get('proforma', False),
            'force_email': True,
            'default_attachment_ids': [(6, 0, [attachment.id, attachment_cotisations.id])],
        }
        return {
            'type': 'ir.actions.act_window',
            'name': 'Envoyer courriel',
            'view_mode': 'form',
            'res_model': 'mail.compose.message',
            'views': [(False, 'form')],
            'view_id': False,
            'target': 'new',
            'context': ctx,
        }

    def generer_adhesion(self):

        if self.montant_total_cotisation:
            year = datetime.today().year
            name = "Adhésion "+" "+(self.appel_cot_year)+" "+"pour"+" "+ self.name
            list_price = self.montant_total_cotisation
            default_code = "adh" + self.appel_cot_year

            membership_date_from = datetime.today()

            membership_date_to = membership_date_from + timedelta(days=365)

            all_product = self.env['product.template'].search(
                [('for_year', '=', self.appel_cot_year), ('res_createur_ids', '=', int(self.id))])

            if not all_product:

                product = self.env['product.template'].create({
                    'name': name,
                    'list_price': list_price,
                    'membership': 't',
                    'default_code': default_code,
                    'type': 'service',
                    'for_year': self.appel_cot_year,
                    'membership_date_from': membership_date_from,
                    'membership_date_to': membership_date_to,
                    'res_createur_ids': self.id,

                })
                self.date_renouvel = datetime(year, 12, 10)



            else:
                raise UserError(("Il existe un appel de cotisation dans cette année"))



        else:
            raise UserError(("Vérifier votre information(Montant Total de la cotistation)"))


    def _cron_renouvele_coti(self,date):
        date_now = datetime.today()

        product_object = self.env['res.partner']
        product_object.search([('date_renouvel', '=', date_now)])
        if product_object:
            print('renouve existe')

        else :
            print('renouve n existe pas ')

    def vers_adherent(self):
        self.all_members=True
        self.adherent=True
