from odoo import api, exceptions, fields, models, _
import datetime


# class RelationPutLineToAQCLine(models.Model):
#     _name = 'relation.put.line.to.aqc.line'
#
#     _columns = {
#         'product_id': fields.integer('Product ID'),
#         'put_line_id': fields.integer('Put Line ID'),
#         'aqc_line_id': fields.integer('AQC Line ID'),
#         'assigned_qty': fields.float('Assigned Quantity'),
#         'location': fields.char('Location'),
#         'grn_id': fields.integer('GRN ID'),
#
#     }

class PutawayProcess(models.Model):
    _name = 'putaway.process'
    _description = "Putaway Process For Inbound"
    _order = 'id desc'

    scan = fields.Char('Scan')
    qc_number = fields.Char('QC Number')
    location_scan = fields.Char('Product Location Scan')
    location = fields.Char('Your Current Location')
    product_scan = fields.Char('Product Scan')
    product_location = fields.Char('Product Location')
    remark = fields.Char('Remarks')
    name = fields.Char('Name')
    name = fields.Char('Name')
    pqc_number = fields.Char('PQC Number')
    warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse ID')
    aqc_id = fields.Many2one('accepted.quality.control', string='AQC ID')
    irn_id = fields.Many2one('irn.control', string='IRN ID')
    pqc_id = fields.Many2one('pending.quality.control', string='PQC ID')
    received_by = fields.Many2one('res.users', string='Receiver (PQC) ID')
    irn_number = fields.Char('IRN Number')
    po_id = fields.Many2one('purchase.order', string='PO ID')
    po_number = fields.Char('PO Number')
    qc_id = fields.Many2one('quality.control', string='QC ID')
    assign_id = fields.Char('Assignee')
    description = fields.Char('Description')
    confirmation_date = fields.Datetime('Confirmation Date')
    state = fields.Selection([
        ('confirmed', 'Confirmed'),
        ('pending', 'Pending'),
        ('cancel', 'Cancelled'),
    ], 'Status', help="Gives the status of the Put Away control", select=True)

    putaway_line_view = fields.One2many('putaway.process.details.view', 'putaway_line_ids', 'Putaway Line',
                                             required=True)

    def put_cancel(self):
        
        put_data = self

        if put_data.state == 'confirmed':
            raise exceptions.ValidationError(_('Confirmed.\nThis Put Away already confirmed. You can not cancel it'))

        if put_data.state == 'cancel':
            raise exceptions.ValidationError(_('Cancelled.\nThis Put Away already Cancelled'))

        # put_line_id = [item.id for item in put_data.putaway_line_view]
        # put_line_ids = self.pool.get('relation.put.line.to.aqc.line').search(
        #                                                                      [('put_line_id', 'in', put_line_id)])
        # assigned_put = self.pool.get('relation.put.line.to.aqc.line').browse(put_line_ids)
        #
        # for rel_item in assigned_put:
        #
        #     self._cr.execute(

        #         "select accepted_quality_control.id,accepted_quality_control_line.remaining_quantity "
        #         "from  accepted_quality_control,accepted_quality_control_line where accepted_quality_control.id "
        #         "= accepted_quality_control_line.aqc_id and accepted_quality_control_line.id=%s",
        #         ([rel_item.aqc_line_id]))
        #     qc_ids = self._cr.fetchall()
        #     if len(qc_ids)>0:
        #         remaining_qty = qc_ids[0][1]+rel_item.assigned_qty
        #         self._cr.execute("update accepted_quality_control set assigned=FALSE where id=%s", ([qc_ids[0][0]]))
        #         self._cr.commit()
        #         self._cr.execute("update accepted_quality_control_line set remaining_quantity=%s where id=%s",
        #                          ([remaining_qty,rel_item.aqc_line_id]))
        #         self._cr.commit()
        #

        for element in self:
            ids = [element.id]

            if ids is not None:
                self._cr.execute("update putaway_process set state='cancel' where id=%s", (ids))
                self._cr.commit()

        return True

    def put_confirm(self):
        product_dict = {}
        put_product_list = []

        for items in self.putaway_line_view:
            product_dict[items.product_id]=[items.quantity,items.location]
            put_product_list.append(items.product_id)




        if self.state == 'confirmed':
            raise exceptions.ValidationError(_('Confirmed.\nThis Put Away already confirmed'))
        if self.state == 'cancel':
            raise exceptions.ValidationError(_('Cancelled.\nThis Put Away already Cancelled. '
                                               'You can not confirm it. Please create new one.'))
        created_id = None

        ### Here i have to add transfer Code



        picking_ids = []
        waiting_picking = False

        for picking in self.po_id.picking_ids:
            if picking.state in ['assigned']:
                picking_ids.append(picking)
            if picking.state in ['confirmed']:
                waiting_picking=True




        if waiting_picking == True:
            pass

        ### Stock Transfer Code

        for pick_item in picking_ids:
            vals = {

            }

            sto_id = pick_item.location_dest_id.id
            for mv_itm in pick_item.move_lines:
                mv_lines = []
                if mv_itm.product_id.id in put_product_list:
                    mv_lines.append([0,'',{
                        'product_id':mv_itm.product_id.id,
                        'product_uom_id':1,
                        'qty_done':product_dict[mv_itm.product_id.id][0],
                        'location_id':4,
                        'location_dest_id':sto_id,
                    }])
                vals['move_line_nosuggest_ids']=mv_lines
                mv_itm.write(vals)

            wiz = self.env['stock.backorder.confirmation'].create({'pick_ids': [(4, p.id) for p in pick_item]})
            wiz._process()

        ####  Ends Here Stock Transfer


        ### Start Invoice Creation from here

        bill = self.env['account.move'].browse()

        bill = bill.new({
            'date': fields.date.today(),
            'partner_id': self.po_id.partner_id.id,
            'ref': self.po_id.partner_ref,
            'company_id': self.po_id.env.company.id,
            'invoice_payment_term_id': self.po_id.payment_term_id.id,
            'currency_id': self.po_id.currency_id.id,
            'fiscal_position_id': self.po_id.fiscal_position_id,
            'type': 'in_invoice',
            'purchase_id': self.po_id.id,
            'journal_id': 2, ## IT is a journal ID of Purchase Journal
        })

        bill._onchange_purchase_auto_complete()
        self.po_id.invoice_ids += bill


        #### Ends here Invoice Creationt


        ### ENds Here

        ### Now confirm the putaway

        for single_id in self:
            putaway_update_query = "UPDATE putaway_process SET state='confirmed', confirmation_date='{0}' " \
                                     "WHERE id={1}".format(str(fields.datetime.now()), single_id.id)
            self._cr.execute(putaway_update_query)
            self._cr.commit()

        #### Ends Here Putaway confirmation

        return True

    @api.onchange('location_scan')
    def put_away_location_onchange(self):
        location = str(self.location_scan)
        self.location=location
        self.location_scan=""

    # def check_total_qty_put_line(self,get_all_pending_aqc_list=[],submitted_put_line_value=[]):
    #
    #     product_list = [items[2].get('product_id') for items in submitted_put_line_value]
    #
    #     product_list = list(set(product_list))
    #
    #     submitted_dict = {}
    #
    #     for p_id in product_list:
    #         qty = 0
    #         for items in submitted_put_line_value:
    #             if items[2].get('product_id') == p_id:
    #                 qty += items[2].get('quantity')
    #     submitted_dict[p_id] = qty
    #
    #     query_product_list = [items[2] for items in get_all_pending_aqc_list]
    #     query_product_list = list(set(query_product_list))
    #
    #     query_dict = {}
    #
    #     for qp_id in query_product_list:
    #         qty = 0
    #         for item in get_all_pending_aqc_list:
    #             if qp_id == item[2]:
    #                 qty += item[4]
    #         query_dict[qp_id] = qty
    #
    #     message = 0
    #
    #     for key, item in submitted_dict.iteritems():
    #
    #         if query_dict.get(key) is not None:
    #             if item > query_dict.get(key):
    #                 message = 1
    #                 break
    #         else:
    #             message = 2
    #             break
    #     return message

    @api.onchange('product_scan')
    def put_away_product_onchange(self):
        ean_number = str(self.product_scan)
        location = str(self.location)
        self.product_scan = ""
        if location == 'False':
            raise exceptions.ValidationError(_('At first scan the location then product'))

        if self.putaway_line_view:
            new_line=[]
            for items in self.putaway_line_view:
                new_line.append({
                    'qc_id':items['qc_id'],
                    'product_id':items['product_id'],
                    'product':items['product'],
                    'location':items['location'],
                    'quantity':items['quantity'],
                    'remarks':items['remarks'],
                    'po_number':items['po_number'],
                })

        if ean_number != 'False':
            if 'Prod' not in ean_number:
                
                product_env = self.env['product.product']
                product_obj = product_env.search(['|','|','|','|',('ean13', '=', str(ean_number)),('gift_ean', '=', str(ean_number)),('box_ean', '=', str(ean_number)),('case_ean', '=', str(ean_number)),('pallet_ean', '=', str(ean_number))])
                if not product_obj.id:
                    raise exceptions.ValidationError(_('Product Not found.Please add EAN number in Product '
                                                       'Configuration. Or contact with Your department head'))

            else:
                get_list = ean_number.split('Prod')
                product_id = int(get_list[1])

                product_env = self.env['product.product']
                product_obj = product_env.search([('id', '=', product_id)])

                if product_obj.id:
                    qty=1
                else:
                    raise exceptions.ValidationError(_('Product Not found.Please scan properly with proper product'))

            for items in self.putaway_line_view:
                if items['product_id'] == product_obj.id:
                    items['location'] = location

        self.product_scan = ""

    @api.onchange('scan')
    def put_away_barcode_onchange(self):

        qc_number = str(self.scan)
        qc_ids=[]

        if self.putaway_line_view:
            new_putaway_line=[]
            for items in self.putaway_line_view:
                qc_ids.append(items['qc_id'])
                new_putaway_line.append({

                    'qc_id':items['qc_id'],
                    'product_id':items['product_id'],
                    'product':items['product'],
                    'location':items['location'],
                    'quantity':items['quantity'],
                    'remarks':items['remarks'],
                    'po_number':items['po_number'],
                })
        else:
            new_putaway_line = []

        if qc_number != 'False':
            qc_number = str(qc_number.upper())
            mod_obj = self.env['accepted.quality.control']
            model_data_ids = mod_obj.search([('aqc_number', '=', str(qc_number))])

            for items in model_data_ids:
                if not items.assigned:
                    for qc_items in items.aqc_line:

                        # Assign Product Location By Default

                        p_loc =''
                        if qc_items.product_id.x_products_location:
                            p_loc=qc_items.product_id.x_products_location

                        if qc_items.aqc_id not in qc_ids:

                            new_putaway_line.append({
                                'qc_id': qc_items.aqc_id,
                                'product_id': qc_items.product_id,
                                'product': qc_items.product,
                                'po_number': items.po_number,
                                'location': p_loc,
                                'remarks': '',
                                'quantity': qc_items.accepted_quantity,
                            })
                    self.putaway_line_view = new_putaway_line
            self.scan = ""

    @api.model
    def create(self, vals):
        record = super(PutawayProcess, self).create(vals)
        put_number = "PUT0" + str(record.id)
        record.name = put_number
        record.state = 'pending'
        putaway_obj = record
        # self.pool.get('inb.end.to.end').putaway_data_create(str(putaway_obj.aqc_id.po_number),
        #                                                      putaway_obj.aqc_id.po_id, record,
        #                                                     put_number, putaway_obj.create_date)
        return record


class PutawayProcessDetails(models.Model):
    _name = 'putaway.process.details'

    putaway_line_ids = fields.Many2one('putaway.process', 'Put Away Process ID', required=True,
                                                ondelete='cascade', select=True, readonly=True)
    qc_id = fields.Many2one('accepted.quality.control', string='AQC ID')
    product_id = fields.Integer('Product')
    location = fields.Char('Location')
    product = fields.Char('Product')
    remarks = fields.Char('Remarks')
    po_number = fields.Char('PO Number')
    quantity = fields.Float('Quantity')


class PutawayProcessDetailsView(models.Model):
    _name = 'putaway.process.details.view'

    putaway_line_ids = fields.Many2one('putaway.process', 'Put Away Process ID', required=True,
                                                ondelete='cascade', select=True, readonly=True)
    product_id = fields.Integer('Product')
    qc_id = fields.Integer('Aputaway_line_viewQC ID')
    location = fields.Char('Location')
    product = fields.Char('Product')
    remarks = fields.Char('Remarks')
    po_number = fields.Char('PO Number')
    quantity = fields.Float('Quantity')


