# Copyright (C) 2021: Criptomart (<https://criptomart.net/>)
# @author: Criptomart (<tech@criptomart.net>)
# 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 en 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="Ubicación usada 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="Ubicación usada para gestionar el material que éste proveedor nos deja en depósito."
     )
     deposit_buy_last_liquidation_date = fields.Datetime(
         string='Fecha última liquidación compras',
         help="Cuándo se realizó la última liquidación de compras con éste proveedor."
     )
     deposit_sale_last_liquidation_date = fields.Datetime(
         string='Fecha última liquidación ventas',
         help="Cuándo se realizó la última liquidación de ventas con éste proveedor."
     )

     @api.model
     def create(self, vals):
         if vals.get('deposit_sale_accept', False) == True:
             vals['deposit_sale_location_id'] = self.env['stock.location'].create({
                 'usage': 'internal',
                 'name': vals.get('name'),
                 'location_id': self.env.ref('stock_picking_deposito.stock_location_deposits_stock').id
                 }).id
         if vals.get('deposit_buy_accept', False) == True:
             vals['deposit_buy_location_id'] = self.env['stock.location'].create({
                 'usage': 'internal',
                 'name': vals.get('name'),
                 'location_id': self.env.ref('stock_picking_deposito.location_deposit_buy').id
                 }).id
         return super().create(vals)

     @api.multi
     def write(self, vals):
         if ( vals.get('deposit_sale_accept', False) == True ) and not self.deposit_sale_location_id:
             vals['deposit_sale_location_id'] = self.env['stock.location'].create({
                 'usage': 'internal',
                 'name': self.name,
                 'location_id': self.env.ref('stock_picking_deposito.stock_location_deposits_stock').id
                 }).id
         if ( vals.get('deposit_buy_accept', False) == True ) and not self.deposit_buy_location_id:
             vals['deposit_buy_location_id'] = self.env['stock.location'].create({
                 'usage': 'internal',
                 'name': self.name,
                 'location_id': self.env.ref('stock_picking_deposito.location_deposit_buy').id
                 }).id
         return super().write(vals)

     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 Compras " + 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,
                'partner_id': self.id,
                'invoice_line_ids': product_list,
                'company_id': self.company_id.id,
            })
            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 de compras : %s" %self.deposit_buy_last_liquidation_date.strftime("%d-%m-%Y, %H:%M:%S")
            else:
                msg += "Todavía no se ha realizado ninguna liquidación de compras a éste proveedor."
            raise ValidationError(msg)

     def make_liquidation_sale(self, context = None):
        self.deposit_sale_location_id
        sale_order_obj = self.env['sale.order']
        search_vals = [('location_id', '=', self.deposit_sale_location_id.id)]
        stock_lines = self.env['stock.quant'].search(search_vals)
        product_list = []
        for mv in stock_lines:
              product_list.append([0, False, {
                  'product_id': mv.product_id.id,
                  'product_uom_qty': mv.quantity,
                  'name': mv.product_id.name,
                  'price_unit': mv.product_id.lst_price,
                  'product_uom': mv.product_id.uom_id.id,
                }
              ])
        if len(product_list):
            self.deposit_sale_last_liquidation_date = fields.datetime.now()
            so_vals = sale_order_obj.default_get(sale_order_obj._fields.keys())
            so_vals.update({
                'partner_id': self.id,
                'origin': "Liquidación Ventas " + self.deposit_sale_last_liquidation_date.strftime("%d-%m-%Y"),
                'date_order': self.deposit_sale_last_liquidation_date.strftime("%Y-%m-%d %H:%M:%S"),
                #'journal_id': self.env.user.company_id.deposit_journal_id.id,
                'order_line': product_list,
                'warehouse_id': self.env.ref('stock_picking_deposito.wh_deposits').id
            })
            sale_order = self.env['sale.order'].sudo().create(so_vals)
            views = [(self.env.ref('sale.view_order_form').id, 'form')]
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'sale.order',
                'res_id': sale_order.id,
                'target': 'current',
                'views': views,
            }
        else:
            msg= "No hay ningún producto enviado en depósito a éste cliente desde la última liquidación de ventas.\n\n"
            if self.deposit_sale_last_liquidation_date:
                msg += "Fecha última liquidación de ventas: %s" %self.deposit_buy_last_liquidation_date.strftime("%d-%m-%Y, %H:%M:%S")
            else:
                msg += "Todavía no se ha realizado ninguna liquidación de ventas a éste proveedor."
            raise ValidationError(msg)

