# Author Mufti Muntasir Ahmed 21-06-2021


from odoo import api, fields, tools, models, _
from odoo import api, models


class MakePickingFromDelivery(models.TransientModel):
    _name = "delivery.picking.wizard"
    _description = "Delivery Picking Wizard"

    name = fields.Char('Picking Number')
    picker_name = fields.Char('Picker Name')
    remarks = fields.Text('Any Remarks')
    picking_datetime = fields.Datetime("Date")
    warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse')
    picking_line_ids = fields.One2many('product.picking.line', 'product_picking_id', string='Picking lines')
    delivery_picking_ids = fields.One2many('delivery.picking.line', 'delivery_picking_id',
                                           string='Delivery Picking lines')

    def make_picking(self, cr, uid, ids, context=None):
        picking_obj = self.pool.get('picking.list')
        import pdb
        pdb.set_trace()

        get_activite_ids = self._context['active_ids']


        if context is None:
            context = {}



        picking_dict = {
            'name':'Mufti',
            'picker_name':'Mufti Picker',
            'remarks':'Mufti Picker cool',
            'picking_datetime':fields.datetime.now(),
            'warehouse_id': 1,
        }


        get_data = self.read(cr, uid, ids)[0]
        data = {}
        picking_line = []
        today_date = fields.Date.today()

        data['description'] = get_data.get('description')
        self.env['stock.move'].create({})

        for items in context.get('active_ids'):
            picking_line.append([0, False,
                                 {'stock_id': items, 'receive_date': today_date.strftime('%Y-%m-%d'), 'details': False,
                                  'state': 'pending', 'return_date': False}])

        data['picking_line'] = picking_line

        save_the_data = picking_obj.create(cr, uid, data, context=context)

        # create picking_products and picking_products_line
        # save_the_data is the id of the picking_list created

        pl_obj = picking_obj.browse(cr, uid, [save_the_data], context=context)

        pp_data = {
            'picking': pl_obj.id,
            'state': 'pending',
        }

        pp_line_list = list()

        """
        product_dict = {"01234": 10}
        """
        product_dict = dict()
        for pick_line in pl_obj.picking_line:

            # 'stock_id': fields.many2one('stock.picking', string='Stock Picking')
            # if the product_dict does not contains product then add with 0 quantity
            for product in pick_line.stock_id.move_lines:
                product_id = product.product_id.id

                if product_dict.has_key(str(product_id)):
                    product_dict[str(product_id)] = float(product.product_qty) + product_dict[str(product_id)]
                else:
                    product_dict[str(product_id)] = float(product.product_qty)

        # create picking_product_line
        product_obj = self.pool.get('product.product')
        for key, value in product_dict.iteritems():
            if value != 0.00:
                prod = product_obj.browse(cr, uid, [int(key)], context=context)
                pp_line_list.append([0, False,
                                     {
                                         'picking_id': save_the_data,
                                         'product_id': int(key),
                                         'product': str(prod.product_name),
                                         'product_ean': str(prod.ean13),
                                         'total_challan_qty': value,
                                         'picking_qty': value,
                                         'state': 'pending',
                                     }])

            pp_data['pick_prod_line'] = pp_line_list
            if pp_line_list:
                pick_pro_env = self.pool.get('picking.products')
                saved_pick_pro_id = pick_pro_env.create(cr, uid, pp_data, context=context)
        return True
