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

class SaleOrder(models.Model):
    _inherit = 'sale.order'
    
    mt_contract_id = fields.Many2one('partner.contract.customer', string=_('Номер договора'))
    sec_partner_id = fields.Many2one('res.partner', string=_('Контрагент'), store=True, compute='_compute_get_pid')
    stamp = fields.Boolean(string=_('Печать и подпись'), related='mt_contract_id.stamp')

    @api.depends('partner_id')
    def _compute_get_pid(self):
        for s in self:
            s.sec_partner_id = s.partner_id.parent_id if s.partner_id.parent_id else s.partner_id

    @api.onchange('mt_contract_id')
    def set_ons(self):
        for s in self:
            if s.mt_contract_id:
                s.payment_term_id = s.mt_contract_id.payment_term_id

    @api.constrains('state')
    def late_payment_check(self):
        for s in self:
            if s.mt_contract_id:
                if s.state == 'sale':
                    late_invoices_count = 0
                    max_receivable = s.mt_contract_id.profile_id.max_receivable_id

                    invoices_obj = self.env['account.move'].search([('partner_id', '=', s.partner_id.id),
                                                                    ('state', '=', 'posted'),
                                                                    ('payment_state', 'not in', ['paid', 'reversed']),
                                                                    ('move_type', 'in', ['out_invoice']),
                                                                    ('invoice_date_due', '<', datetime.now().date())])

                    for invoice in invoices_obj:
                        late_invoices_count += invoice.amount_residual

                    if late_invoices_count > max_receivable:
                        raise exceptions.ValidationError(
                            f'Нельзя подтвердить заказ, так как у контрагента {s.sec_partner_id.name} нарушено '
                            f'условие по дебиторской задолженности.\n\n'
                            f'Контрагент {s.sec_partner_id.name} должен {late_invoices_count}руб.\n'
                            f'Максимальная дебиторская задолженность указанная в '
                            f'договоре №{s.mt_contract_id.name} - {max_receivable}руб.\n\n'
                            f'Проверьте следующие неоплаченные счета контрагента:\n'
                            f'{", ".join([invoice.name for invoice in invoices_obj])}')


    def _prepare_invoice(self):
        invoice_vals = super(SaleOrder, self)._prepare_invoice()
        for s in self:
            if s.mt_contract_id:
                invoice_vals['mt_contract_id'] = s.mt_contract_id.id
                invoice_vals['osnovanie'] = 'Договор № ' + s.mt_contract_id.name + ' от ' + fields.Datetime.from_string(
                    s.mt_contract_id.date_start).strftime("%d.%m.%Y")
        return invoice_vals