# -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.exceptions import ValidationError, Warning
from datetime import datetime

# mapping invoice type to journal type
TYPE2JOURNAL = {
    'out_invoice': 'sale',
    'in_invoice': 'purchase',
    'out_refund': 'sale_refund',
    'in_refund': 'purchase_refund',
}

class account_interest_line(models.Model):
    _name = "account.interest.line"
    # _inherit = "account.interest.line"

    origin = fields.Char(string='Source Document', help="Reference of the document that produced this invoice.")
    invoice_id = fields.Many2one('account.invoice', string='Invoice Reference', ondelete='cascade', index=True, required=True)
    invoice_line_id = fields.Many2one('account.invoice.line', string='Invoice line Reference', ondelete='cascade', index=True, required=True)
    date  = fields.Date()
    name_product = fields.Text(string='Description', required=True)
    price_subtotal = fields.Float(string='Amount')
    quantity = fields.Float(string='Quantity')
    state = fields.Boolean()
    partner_id = fields.Many2one('res.partner', string='Partner')
    interes_invoice = fields.Many2one('account.invoice', string='Invoice Reference', ondelete='cascade', index=True, required=True)
    move_line_id = fields.Many2one('account.move.line', string='Seguimiento de Pago ', ondelete='cascade', index=True, required=True)

    @api.model
    def _default_journal(self):
        inv_type = self._context.get('type', 'out_invoice')
        inv_types = inv_type if isinstance(inv_type, list) else [inv_type]
        company_id = self._context.get('company_id', self.env.user.company_id.id)
        domain = [
            ('type', 'in', filter(None, map(TYPE2JOURNAL.get, inv_types))),
            ('company_id', '=', company_id),
        ]
        return self.env['account.journal'].search(domain, limit=1)

    journal_id = fields.Many2one('account.journal', string='Journal',
        required=True, readonly=True, states={'draft': [('readonly', False)]},
        default=_default_journal,
        domain="[('type', 'in', {'out_invoice': ['sale'], 'out_refund': ['sale_refund'], 'in_refund': ['purchase_refund'], 'in_invoice': ['purchase']}.get(type, [])), ('company_id', '=', company_id)]")

class invoice_interes(models.Model):
    _inherit = "account.invoice"

    interes_ids = fields.One2many('account.interest.line', inverse_name="invoice_id", string="id Interes")

    @api.onchange('interes_ids')
    def onchange_update(self):
        for interest in self.interes_ids:
            if interest.state == False:
                interest_datos = self.env['account.interest.line'].search([('id','in', interest.ids)])
                print(interest_datos.price_subtotal)
                interest_datos.write({'state' : False})

    def actualizarInteres(self, cr , uid, dato, context=None):
        # print("*****Eliminado linea de Interes***********************************")
        estado=None
        # Obtener los datos de Interest Line (Linea de interes)
        interes_model = self.pool.get('account.interest.line').search(cr, uid,[('interes_invoice', 'in', dato),
                                                                               ('state', '=', False)],context=context)
        interes_datos = self.pool.get('account.interest.line').browse(cr, uid, interes_model, context=context)
        for interes in interes_datos:
            # print(interes.name_product)
            # Obtener los datos de invoice line (Iten de facturacion)
            line_model = self.pool.get('account.invoice.line').search(cr, uid, [('id', '=', interes.invoice_line_id.ids)], context=context)
            line_datos = self.pool.get('account.invoice.line').browse(cr, uid, line_model, context=context)
            for line in line_datos:
                # Obtener los datos de invoice para su actualizacion
                invoice_model = self.pool.get('account.invoice').search(cr, uid, [('id', 'in', dato)],context=context)
                invoice_dato  = self.pool.get('account.invoice').browse(cr, uid, invoice_model, context=context)
                # Actualizar Invoice(facturacion)
                invoice_dato.write({'residual' : (invoice_dato.residual - line.price_subtotal),
                                    'amount_total' : (invoice_dato.amount_total - line.price_subtotal),
                                    'amount_untaxed' : (invoice_dato.amount_untaxed - line.price_subtotal)})
                # Actualar cuanta a pagr del cliente
                # partner_model = self.pool.get('res.partner').search(cr, uid,[('id', '=', invoice_dato.partner_id.ids)], context=context)
                # parthner_datos = self.pool.get('res.partner').browse(cr, uid, partner_model,context=context)
                # parthner_datos.write({'payment_amount_due' :invoice_dato.residual})
                # Otnere los linea de condicion de pago
                payment_line_model = self.pool.get('account.payment.term.line').search(cr, uid, [('payment_id', 'in', invoice_dato.payment_term.ids)
                                                                                                ], order='id', context=context)
                payment_line_dato = self.pool.get('account.payment.term.line').browse(cr, uid, payment_line_model, context=context)
                # print(payment_line_dato)
                # Obtener Datos de Move Line
                move_line_model = self.pool.get('account.move.line').search(cr, uid, [('reconcile_ref', '=', None), ('ref', '=', invoice_dato.reference),
                                                                                      ('credit', '=', 0)], order='id', context=context)
                # Obtener los registrode la lineas
                move_line_modelp = self.pool.get('account.move.line').search(cr, uid, [('ref', '=', invoice_dato.reference), ('credit', '=', 0)], order='id', context=context)
                # Retorna la cantidad de Registro de la Consulta
                move_count = self.pool.get('account.move.line').search_count(cr, uid, [('reconcile_ref', '=', None), ('ref', '=', invoice_dato.reference),
                                                                                        ('credit', '=', 0)], context=context)
                # Selecionar todos los dactos de Move Line para su activacion
                model_move_line1 = self.pool.get('account.move.line').search(cr, uid,[('ref', '=', invoice_dato.reference)], context=context)
                datos_move_line2 = self.pool.get('account.move.line').browse(cr, uid, model_move_line1, context=context)
                move_line_dato = self.pool.get('account.move.line').browse(cr, uid, move_line_model, context=context)
                move_line_datosp = self.pool.get('account.move.line').browse(cr, uid, move_line_modelp, context=context)
                # print(move_line_dato)
                monto_cuota = invoice_dato.residual
                # Obterner el registro de diario de ventas
                model_journal = self.pool.get('account.journal').search(cr, uid,[('type', '=', 'sale')], context=context)
                datos_journal = self.pool.get('account.journal').browse(cr, uid, model_journal, context=context)
                #Activar Modificacion
                datos_journal.write({'entry_posted' : True})
                # datos_move_line2.write({'debit' :  (moveline2.debit + ammount_interes)})
                for move_line in move_line_datosp:
                    # obterner move
                    move_model = self.pool.get('account.move').search(cr, uid, [('id', 'in', move_line.move_id.ids)],context=context)
                    move_dato = self.pool.get('account.move').browse(cr, uid, move_model, context=context)
                    for move in move_dato:
                        estado = move.state
                        # Obtener pagos
                        # print('voucher')
                        # voucher_model = self.pool.get('account.voucher').search(cr, uid, [('move_id', 'in', move.id)],context=context)
                        # voucher_dato = self.pool.get('account.voucher').browse(cr, uid, voucher_model,context=context)
                        # for voucher in voucher_dato:
                        # obtener ls linea de pagos
                        line_voucher_model = self.pool.get('account.voucher.line').search(cr, uid, [('move_line_id', 'in', move_line.ids),
                                                                                                    ('amount', '>', 0), ('reconcile', '=', False)],context=context)
                        line_voucher_dato = self.pool.get('account.voucher.line').browse(cr, uid, line_voucher_model,context=context)
                        for voucher_line in line_voucher_dato:
                            monto_cuota =(monto_cuota - (voucher_line.amount_original - voucher_line.amount))
                move_dato.write({'state' : 'draft'})
                c=0
                montototal=0
                for line_move in move_line_dato:
                    c +=1
                    if c <= (move_count-1):
                        move_line = self.pool.get('account.move.line').search(cr, uid, [('id', '=', line_move.ids)], context=context)
                        move_line_browse = self.pool.get('account.move.line').browse(cr, uid, move_line, context=context)
                        monto_cuota1= (monto_cuota*0.33)
                        montototal +=monto_cuota1
                        move_line_browse.write({'debit' : monto_cuota1})
                    else:
                        if c == move_count:
                            move_line = self.pool.get('account.move.line').search(cr, uid, [('id', '=', line_move.ids)], context=context)
                            move_line_browse = self.pool.get('account.move.line').browse(cr, uid, move_line, context=context)
                            monto_cuota1= (monto_cuota - montototal)
                            move_line_browse.write({'debit' : monto_cuota1})
                if  estado == None:
                    estado='draft'
                move_dato.write({'state' : estado})
                #Desativar Modificacion
                datos_journal.write({'entry_posted' : False})
                # Activar Move line
                datos_move_line2.write({'state' : 'valid'})
                # Eliminar Invoice Line ------------------------------------------------------
                self.pool.get('account.invoice.line').unlink(cr, uid,line.ids,context=context)
            # Eliminar linea de account.interest.line  cuando su estado esta en fase ----------
            self.pool.get('account.interest.line').unlink(cr, uid, interes.ids, context=context)
        print("*****************************************************************")