## Author Mufti Muntasir Ahmed 19-06-2021

from odoo import api, fields, tools, models, _
from odoo.exceptions import UserError, ValidationError
from datetime import timedelta


class StockPicking(models.Model):
    _inherit = 'stock.picking'

    picked = fields.Boolean('Picked')


class DeliveryPicking(models.Model):
    _name = 'delivery.picking'
    _description = 'Picking Information'
    _order = 'id desc'

    name = fields.Char('Picking Number')
    picker_name = fields.Char('Picker Name')
    remarks = fields.Text('Any Remarks')
    picking_datetime = fields.Datetime("Date",default=fields.Datetime.now)
    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')
    state = fields.Selection([
        ('pending', 'Pending'),
        ('confirm', 'Confirm'),
        ('cancel', 'Cancelled'),
        ], string='Status', readonly=True, copy=False, index=True, tracking=3, default='pending')

    @api.model
    def create(self, vals):
        res = super(DeliveryPicking, self).create(vals)
        pick_number = "PICK0" + str(res.id)
        res.name = pick_number

        ## Update the stock picking  Statet of Outgoing Challan Form

        stock_picking_ids= []
        for delivery_items  in res.delivery_picking_ids:
            stock_picking_ids.append(delivery_items.stock_picking_id.id)

        self._cr.execute("update stock_picking set picked='True' where id in %s", (tuple(stock_picking_ids),))



        ## Ends Here Challan Picking State
        return res


    def confirm_picking(self):
        for rec in self:
            if rec.state == 'pending':


                pack_vals = {
                    'name':'',
                    'packer_name':'',
                    'warehouse_id':rec.warehouse_id.id,
                    'packing_datetime':fields.datetime.now(),
                    'packing_line_ids':[],
                    'picking_id':self.id,
                    # 'delivery_picking_id':[]
                }
                packing_line_ids = []

                for del_items in rec.delivery_picking_ids:
                    packing_line_ids.append([0,False,{
                        'stock_picking_id':del_items.stock_picking_id.id,
                        'magento_order_no':'100012345',
                        'erp_no':del_items.stock_picking_id.origin
                    }])
                pack_vals['packing_line_ids']=packing_line_ids

                packing_ids = self.env['delivery.packing'].create(pack_vals)
                rec.write({'state': 'confirm'})

            elif rec.state == 'confirm':
                raise UserError(_("Already Confirmed"))

        return True



    def cancel_picking(self):
        for rec in self:
            if rec.state == 'pending':
                rec.write({'state': 'cancel'})
                stock_picking_ids = []
                for delivery_items in rec.delivery_picking_ids:
                    stock_picking_ids.append(delivery_items.stock_picking_id.id)

                self._cr.execute("update stock_picking set picked='False' where id in %s", (tuple(stock_picking_ids),))

            else:
                raise ValidationError(_('You can not cancel at this state'))
        return True




class ProductPickingLine(models.Model):
    _name = "product.picking.line"
    _description = "Picking Line Information"

    product_picking_id = fields.Many2one('delivery.picking', string='Product Picking Entry',index=True, required=True, readonly=True, auto_join=True, ondelete="cascade")
    product_id = fields.Many2one('product.product', string='Product Information')
    product_ean = fields.Char('Product EAN')
    total_ordered_qty = fields.Float('Total Challan QTY')
    total_handed_over_qty = fields.Float('Total Handed Over QTY')




class DeliveryPickingLine(models.Model):
    _name = "delivery.picking.line"
    _description = "Delivery Picking Line Information"

    delivery_picking_id = fields.Many2one('delivery.picking', string='Delivery Parent IDS Entry', index=True, required=True,
                                          readonly=True, auto_join=True, ondelete="cascade")
    stock_picking_id = fields.Many2one('stock.picking', string='Delivery Challan ID')
    magento_number = fields.Char('Order Number')
    erp_number = fields.Char('ERP No')






