from odoo import models,fields,_


class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'
    benefit_family_id = fields.Many2one(comodel_name='grant.benefit', string='Benefit Family')
    family_confirm_id = fields.Many2one(comodel_name='confirm.benefit.expense', string='Benefit Family')
    family_code = fields.Char(string='Family Code', related='benefit_family_id.code',readonly=True)

class AccountMove(models.Model):
    _inherit = 'account.move'
    family_confirm_id = fields.Many2one(comodel_name='confirm.benefit.expense', string='Benefit Family')
    benefit_family_ids = fields.Many2many(comodel_name='grant.benefit',relation='account_move_grant_family_rel',
    column1='move_id',column2='family_id', string='Benefit Family')
    required_attachment_line_count = fields.Integer(string="Required Attachments",compute='_compute_required_attachment_line_count',store=False,)

    def _compute_required_attachment_line_count(self):
        for move in self:
            payment_order = self.env['payment.orders'].search([
                ('move_id', '=', move.id),
                ('type', '=', 'services')
            ], limit=1)

            if not payment_order or not payment_order.service_requests_ids:
                move.required_attachment_line_count = 0
                continue
            all_lines = payment_order.service_requests_ids.mapped('attachment_lines')
            move.required_attachment_line_count = len(all_lines)

    def action_view_service_attachments(self):

        payment_order = self.env['payment.orders'].search([
            ('move_id', '=', self.id),
            ('type', '=', 'services')
        ], limit=1)

        attachment_ids = payment_order.service_requests_ids.mapped('attachment_lines').ids

        ctx = self.env.context.copy()
        ctx.update({
            'create': False, 'edit': False, 'delete': False,
        })

        return {
            'name': _('Service Required Attachments'),
            'type': 'ir.actions.act_window',
            'res_model': 'service.attachments.settings',
            'view_mode': 'tree,form',
            'domain': [('id', 'in', attachment_ids)],
            'context': ctx,
            'target': 'current',
        }