from odoo import api, fields, models


class AccountMoveTemplateMixin(models.AbstractModel):
    _name = 'account.move.template.mixin'
    _description = 'Миксин для создания проводок через шаблоны'

    move_ids = fields.Many2many(
        comodel_name='account.move',
        string='Проводки',
    )
    move_count = fields.Integer(
        compute='_compute_move_count',
        string='Количество проводок',
    )

    @api.depends('move_ids')
    def _compute_move_count(self):
        for record in self:
            record.move_count = len(record.move_ids)

    def action_open_journal_wizard(self):
        """If move_ids is empty, open wizard. Otherwise delegate to action_view_moves."""
        self.ensure_one()
        if self.move_ids:
            return self.action_view_moves()
        amounts = self.get_move_line_amounts()
        default_amount = amounts[0]['amount'] if amounts else 0.0
        return {
            'type': 'ir.actions.act_window',
            'name': 'Создать проводку',
            'res_model': 'account.move.template.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_res_model': self._name,
                'default_res_id': self.id,
                'default_amount': default_amount,
            },
        }

    def action_view_moves(self):
        """Return action to view related account.move records."""
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': 'Проводки',
            'res_model': 'account.move',
            'view_mode': 'list,form',
            'domain': [('id', 'in', self.move_ids.ids)],
        }

    def get_move_line_amounts(self):
        """Override in inheriting models to provide line amounts.
        Returns list of dicts: [{'name': str, 'amount': float}, ...]
        """
        return []
