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

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


class BaseConsent(models.Model):
    _name = 'base.consent'
    _inherit = ['mail.thread', 'utm.mixin']
    _description = 'Consent'
    _order = 'date_from desc'

    name = fields.Char(string=_('Номер'))
    date_from = fields.Date(string=_('Дата выдачи'), default=lambda self: fields.Datetime.now())
    date_to = fields.Date(string=_('Действительна по'), default=lambda self: datetime.today() + timedelta(days=180))
    partner_id = fields.Many2one('res.partner', string=_('Контрагент'), required=1)
    employee_id = fields.Many2one('hr.employee', string=_('Сотрудник'), required=1)
    purchaseorder_id = fields.Many2one('purchase.order', _('Заказ на закупку'), domain="[('partner_id','=',partner_id)]",
                                       required=1)
    company_id = fields.Many2one('res.company', string=_('Компания'),
                                 default=lambda self: self.env.company,
                                 required=1)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if not vals.get("name"):
                vals["name"] = self.env["ir.sequence"].next_by_code("base.consent")

        records = super().create(vals_list)
        for record in records:
            if record.purchaseorder_id:
                record.purchaseorder_id.sudo().write({
                    "consent_id": record.id
                })

        return records

    @api.onchange('purchaseorder_id')
    def set_partner(self):
        if self.purchaseorder_id:
            self.partner_id = self.purchaseorder_id.partner_id

    @api.constrains('purchaseorder_id')
    def fill_order(self):
        p_orders = self.env['purchase.order'].sudo().browse(self.purchaseorder_id.id)
        for order in p_orders:
            order.consent_id = self.id
