# Copyright (C) 2021: Criptomart ()
# @author: Criptomart ()
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
#import logging
from odoo import models, fields, api
from odoo.exceptions import ValidationError, Warning
#_logger = logging.getLogger(__name__)
class ResPartner(models.Model):
     _inherit = 'res.partner'
     deposit_sale_accept = fields.Boolean(
        string='Acepta depósitos de venta',
        help='Éste cliente acepta nuestro material a depósito',
     )
     deposit_buy_accept = fields.Boolean(
        string='Acepta depósitos de compra',
        help='Éste proveedor nos deja material a depósito',
     )
     deposit_sale_location_id = fields.Many2one(
         comodel_name='stock.location', 
         string='Ubicación de depósito de ventas',
         help="La ubicación que se usará para gestionar el depósito que dejamos a éste proveedor"
     )
     deposit_buy_location_id = fields.Many2one(
         comodel_name='stock.location', 
         string='Ubicación de depósito de compras',
         help="La ubicación que se usará para gestionar el material que éste proveedor nos deja en depósito."
     )
     deposit_buy_last_liquidation_date = fields.Datetime(
         string='Fecha de la última liquidación de compras',
         help="Cuándo se realizó la última liquidación de compras con éste proveedor."
     )    
     deposit_sale_last_liquidation_date = fields.Datetime(
         string='Fecha de la última liquidación de ventas',
         help="Cuándo se realizó la última liquidación de ventas con éste proveedor."
     )    
     @api.onchange('deposit_sale_accept')
     def _onchange_deposit_sale_accept(self):
        if self.deposit_sale_accept and not self.deposit_sale_location_id:
            new_loc = self.env['stock.location'].create({
                'usage': 'internal',
                'name': self.name,
                'location_id': self.env.ref('stock_picking_deposito.location_deposit_sale').id
            })
            self.update({
                'deposit_sale_location_id': new_loc
            })
     @api.onchange('deposit_buy_accept')
     def _onchange_deposit_buy_accept(self):
        if self.deposit_buy_accept and not self.deposit_buy_location_id:
            new_loc = self.env['stock.location'].create({
                'usage': 'internal',
                'name': self.name,
                'location_id': self.env.ref('stock_picking_deposito.location_deposit_buy').id
            })
            self.update({
                'deposit_buy_location_id': new_loc
            })
     def make_liquidation_buy(self, context = None):
        invoice_obj = self.env['account.invoice']            
        search_vals = [
            ('location_id', '=', self.deposit_buy_location_id.id),'|',
            ('location_dest_id', '=', self.env.ref('stock.stock_location_customers').id),
            ('location_dest_id', '=', self.env.ref('stock.stock_location_stock').id),
        ]            
        if self.deposit_buy_last_liquidation_date:
            search_vals.append(('date', '>', self.deposit_buy_last_liquidation_date.strftime("%Y-%m-%d %H:%M:%S")))
        move_lines = self.env['stock.move.line'].search(search_vals)
        product_list = []
        for mv in move_lines:
          new_prod = True
          for p in product_list:
              if p[2]['product_id'] == mv.product_id.id:
                  p[2]['quantity'] += mv.qty_done
                  new_prod = False
                  break
          if new_prod:
              product_list.append([0, False, {
                  'product_id': mv.product_id.id, 
                  'quantity': mv.qty_done,
                  'name': mv.product_id.name,
                  'price_unit': mv.product_id.lst_price,
                  'uom_id': mv.product_id.uom_id.id,
                  'account_id': self.env['account.account'].search([('user_type_id', '=', self.env.ref('account.data_account_type_expenses').id)], limit=1).id 
                }
              ])
        if len(product_list): 
            self.deposit_buy_last_liquidation_date = fields.datetime.now()
            invoice_vals = invoice_obj.default_get(invoice_obj._fields.keys())
            invoice_vals.update({
                'origin': "Liquidación " + self.deposit_buy_last_liquidation_date.strftime("%d-%m-%Y"),
                'type': 'in_invoice',
                'date_invoice': self.deposit_buy_last_liquidation_date.strftime("%Y-%m-%d %H:%M:%S"),
                'journal_id': self.env.user.company_id.deposit_journal_id.id,
                'account_id': self.env['account.account'].search([('user_type_id', '=', self.env.ref('account.data_account_type_receivable').id)], limit=1).id,
                'partner_id': self.id,
                'invoice_line_ids': product_list,
            })
            invoice = self.env['account.invoice'].create(invoice_vals)
            views = [(self.env.ref('account.invoice_form').id, 'form')]
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'account.invoice',
                'res_id': invoice.id,
                'target': 'current',
                'views': views,
            }
        else:
            msg= "No se ha vendido ningún producto en depósito de éste provedor desde la última liquidación.\n\n"
            if self.deposit_buy_last_liquidation_date:  
                msg += "Fecha última liquidación : %s" %self.deposit_buy_last_liquidation_date.strftime("%d-%m-%Y, %H:%M:%S")
            else:
                msg += "No se ha realizado ninguna liquidación a éste proveedor." 
            raise ValidationError(msg)
     def make_liquidation_sale(self, context = None):
        invoice_obj = self.env['account.invoice']            
        search_vals = [
            ('location_id', '=', self.deposit_buy_location_id.id),'|',
            ('location_dest_id', '=', self.env.ref('stock.stock_location_customers').id),
            ('location_dest_id', '=', self.env.ref('stock.stock_location_stock').id),
        ]            
        if self.deposit_buy_last_liquidation_date:
            search_vals.append(('date', '>', self.deposit_buy_last_liquidation_date.strftime("%Y-%m-%d %H:%M:%S")))
        move_lines = self.env['stock.move.line'].search(search_vals)
        product_list = []
        for mv in move_lines:
          new_prod = True
          for p in product_list:
              if p[2]['product_id'] == mv.product_id.id:
                  p[2]['quantity'] += mv.qty_done
                  new_prod = False
                  break
          if new_prod:
              product_list.append([0, False, {
                  'product_id': mv.product_id.id, 
                  'quantity': mv.qty_done,
                  'name': mv.product_id.name,
                  'price_unit': mv.product_id.lst_price,
                  'uom_id': mv.product_id.uom_id.id,
                  'account_id': self.env['account.account'].search([('user_type_id', '=', self.env.ref('account.data_account_type_expenses').id)], limit=1).id 
                }
              ])
        if len(product_list): 
            self.deposit_buy_last_liquidation_date = fields.datetime.now()
            invoice_vals = invoice_obj.default_get(invoice_obj._fields.keys())
            invoice_vals.update({
                'origin': "Liquidación " + self.deposit_buy_last_liquidation_date.strftime("%d-%m-%Y"),
                'type': 'in_invoice',
                'date_invoice': self.deposit_buy_last_liquidation_date.strftime("%Y-%m-%d %H:%M:%S"),
                'journal_id': self.env.user.company_id.deposit_journal_id.id,
                'account_id': self.env['account.account'].search([('user_type_id', '=', self.env.ref('account.data_account_type_receivable').id)], limit=1).id,
                'partner_id': self.id,
                'invoice_line_ids': product_list,
            })
            invoice = self.env['account.invoice'].create(invoice_vals)
            views = [(self.env.ref('account.invoice_form').id, 'form')]
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'account.invoice',
                'res_id': invoice.id,
                'target': 'current',
                'views': views,
            }
        else:
            msg= "No se ha vendido ningún producto en depósito de éste provedor desde la última liquidación.\n\n"
            if self.deposit_buy_last_liquidation_date:  
                msg += "Fecha última liquidación : %s" %self.deposit_buy_last_liquidation_date.strftime("%d-%m-%Y, %H:%M:%S")
            else:
                msg += "No se ha realizado ninguna liquidación a éste proveedor." 
            raise ValidationError(msg)