# -*- coding: utf-8 -*-
##############################################################################
#
#    datenpol gmbh
#    Copyright (C) 2013-TODAY datenpol gmbh ()
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see .
#
##############################################################################
from odoo import api, fields, models
from odoo.addons import decimal_precision as dp
from odoo.tools import float_round
class AcccountInvoice(models.Model):
    _inherit = 'account.invoice'
    @api.model
    def invoice_line_move_line_get(self):
        res = []
        for line in self.invoice_line_ids:
            if line.quantity == 0:
                continue
            tax_ids = []
            for tax in line.invoice_line_tax_ids:
                tax_ids.append((4, tax.id, None))
                for child in tax.children_tax_ids:
                    if child.type_tax_use != 'none':
                        tax_ids.append((4, child.id, None))
            analytic_tag_ids = [(4, analytic_tag.id, None) for analytic_tag in line.analytic_tag_ids]
            move_line_dict = {
                'invl_id': line.id,
                'type': 'src',
                'name': line.name.split('\n')[0][:64],
                'price_unit': line.price_reduce,
                'quantity': line.quantity,
                'price': line.price_subtotal,
                'account_id': line.account_id.id,
                'product_id': line.product_id.id,
                'uom_id': line.uom_id.id,
                'account_analytic_id': line.account_analytic_id.id,
                'tax_ids': tax_ids,
                'invoice_id': self.id,
                'analytic_tag_ids': analytic_tag_ids
            }
            if line['account_analytic_id']:
                move_line_dict['analytic_line_ids'] = [(0, 0, line._get_analytic_line())]
            res.append(move_line_dict)
        return res
    @api.multi
    def get_taxes_values(self):
        tax_grouped = {}
        for line in self.invoice_line_ids:
            taxes = \
                line.invoice_line_tax_ids.compute_all(line.price_reduce, self.currency_id, line.quantity,
                                                      line.product_id,
                                                      self.partner_id)['taxes']
            for tax in taxes:
                val = self._prepare_tax_line_vals(line, tax)
                key = self.env['account.tax'].browse(tax['id']).get_grouping_key(val)
                if key not in tax_grouped:
                    tax_grouped[key] = val
                else:
                    tax_grouped[key]['amount'] += val['amount']
                    tax_grouped[key]['base'] += val['base']
        return tax_grouped
class AccountInvoiceLine(models.Model):
    _inherit = 'account.invoice.line'
    price_reduce = fields.Float(string='REP', digits=dp.get_precision('Product Price'), default=0.0,
                                compute='_compute_price_reduce', required=True, store=True,
                                help='Rabattierter Einzelpreis, inkludiert bereits den Rabatt und ist auf 2 Stellen '
                                     'kaufmännisch gerundet.')
    hide_discount = fields.Boolean(string='RV', help='Rabatt verbergen')
    @api.multi
    @api.depends('price_unit', 'discount')
    def _compute_price_reduce(self):
        for line in self:
            line.price_reduce = float_round(line.price_unit * (1.0 - line.discount / 100.0),
                                            precision_digits=self.env['decimal.precision'].precision_get(
                                                'Product Price'))
    @api.multi
    @api.depends('price_unit', 'discount', 'invoice_line_tax_ids', 'quantity',
                 'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id', 'invoice_id.company_id',
                 'invoice_id.date_invoice')
    def _compute_price(self):
        for line in self:
            currency = line.invoice_id and line.invoice_id.currency_id or None
            taxes = False
            if line.invoice_line_tax_ids:
                taxes = line.invoice_line_tax_ids.compute_all(line.price_reduce, currency, line.quantity,
                                                              product=line.product_id,
                                                              partner=line.invoice_id.partner_id)
            line.price_subtotal = price_subtotal_signed = taxes[
                'total_excluded'] if taxes else line.quantity * line.price_reduce
            line.price_total = taxes['total_included'] if taxes else line.price_subtotal
            if line.invoice_id.currency_id and line.invoice_id.currency_id != line.invoice_id.company_id.currency_id:
                price_subtotal_signed = line.invoice_id.currency_id.with_context(
                    date=line.invoice_id.date_invoice).compute(price_subtotal_signed,
                                                               line.invoice_id.company_id.currency_id)
            sign = line.invoice_id.type in ['in_refund', 'out_refund'] and -1 or 1
            line.price_subtotal_signed = price_subtotal_signed * sign