# Author Mufti Muntasir Ahmed 21-06-2021
from datetime import date

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 Name',required=False)
    picker_name = fields.Char('Picker Name',required=False)
    remarks = fields.Text('Any Remarks')
    picking_datetime = fields.Datetime("Date",default=fields.Datetime.now)
    warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse',required=True)
    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):
        self.ensure_one()
        picking_obj = self.pool.get('delivery.picking')
        res_ids = self._context.get('active_ids')
        picking_data = {
            'picker_name': self.name,
            'remarks': self.remarks,
            'picking_datetime': fields.datetime.now(),
            'warehouse_id': self.warehouse_id.id,
            'state': 'pending',
            'picking_line_ids': [],
            'delivery_picking_ids': [],
        }




        delivery_lines = self.env['stock.picking'].search([('id' ,'in',res_ids),])
        delivery_picking_lin_ids = []
        picking_line_ids =[]

        product_id_exists = []
        product_lines_dict = {}
        for item in delivery_lines:
            delivery_picking_lin_ids.append([0,'',{
                'stock_picking_id':item.id,
                'magento_number':'1000000006577',
                'erp_number':item.origin,
            }])

            for p_item in item.move_line_ids_without_package:
                if p_item.product_id.id not in product_id_exists:
                    product_id_exists.append(p_item.product_id.id)
                    product_lines_dict[p_item.product_id.id]=p_item.product_uom_qty
                elif p_item.product_id.id in product_id_exists:
                    product_lines_dict[p_item.product_id.id] += p_item.product_uom_qty




        for k,v in product_lines_dict.items():

            picking_line_ids.append([0,'',
                                     {
                                         'product_id':k,
                                         'total_ordered_qty':v,
                                      }]
                                    )

        picking_data['picking_line_ids']=picking_line_ids
        picking_data['delivery_picking_ids']=delivery_picking_lin_ids
        product_a = self.env['delivery.picking'].create(picking_data)


        return True

        # if context is None:
        #     context = {}
        # get_data = self.read(cr, uid, ids)[0]
        # data = {}
        # picking_line = []
        # today_date = fields.Date.today()
        #
        # data['description'] = get_data.get('description')
        #
        # 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




