# -*- coding: utf-8 -*-

from odoo import models, fields, api


class SOS_Mat_Oursourcing_Monitor(models.Model):
    _name = 'sos_mat_outsourcing_vendor_register'
    _description = 'Outsourcing Vendor Monitoring Register'
    _rec_name = 'supplier_name'
    
    supplier_name = fields.Many2one('sos_suppliers', string="Supplier Name", required=True)
    qp_no= fields.Char(string="QP No",related="supplier_name.qp_no")
    line_ids  = fields.One2many('sos_mat_outsourcing_vendor_register_lines','ref_id',copy=True)
    _sql_constraints = [
        ('supplier_name_unique', 'UNIQUE(supplier_name)', 'This Supplier Name was already present')
    ]
class SOS_Mat_Oursourcing_Monitor_Lines(models.Model):
    _name = 'sos_mat_outsourcing_vendor_register_lines'
    _description = 'Outsourcing Vendor Montinoring Register Lines'
    
    ref_id = fields.Many2one('sos_mat_outsourcing_vendor_register',ondelete="cascade") 
    iqi_references = fields.Many2many('sos_iqi', string="IQI References")
    dc_references = fields.Many2many('sos_dc', string="DC References")
    grn_references = fields.Many2many('sos_grn', string="GRN References")
    material_names = fields.Many2many('sos_material', string="Material Name")
    
    po_no = fields.Many2one(
        'sos_po', 
        string="Purchase Order Reference No", 
        domain="[('supplier_name', '=', parent.supplier_name)]"
    )
    received_qty = fields.Integer(string="Received Quantity")
    approved_qty = fields.Integer(string="Approved Quantity")
    rejected_qty = fields.Integer(string="Rejected Quantity")
    rejection_percentage = fields.Float(string="Rejected Percentage", compute="_compute_rejected_percentage", store=True)
    rejection_percentage_display = fields.Char('Rejection Percentage', compute='_compute_rejected_percentage_display')
    ppm = fields.Integer(string="PPM",compute="_compute_ppm")

    quality_marks = fields.Float(string="Quality Marks") 
    delivery_marks = fields.Float(string="Delivery Marks")
    responsiveness_marks = fields.Float(string="Responsiveness Marks")
    report_marks = fields.Float(string="Report Marks")

    @api.depends('rejection_percentage')
    def _compute_rejected_percentage_display(self):
        for record in self:
            record.rejection_percentage_display = "{:.2f}%".format(record.rejection_percentage)
    @api.depends('received_qty', 'rejected_qty')
    def _compute_rejected_percentage(self):
        for record in self:
            if record.received_qty > 0:
                record.rejection_percentage = (record.rejected_qty / record.received_qty) * 100
            else:
                record.rejection_percentage = 0
    @api.depends('received_qty', 'rejected_qty')
    def _compute_ppm(self):
        for record in self:
            if record.rejected_qty != 0:
                record.ppm = (record.rejected_qty / record.received_qty) * 10**6
            else:
                record.ppm = 0 
    @api.onchange('po_no')
    def _onchange_po_no(self):
        """Updates the IQI references based on the selected Work Order (po_no)."""
        if self.po_no:
            #print(f"Inside grn_records:{self.po_no.id} ")
            ir_records  = self.env['sos_ir'].search([('po_no', '=', self.po_no.id)])
            iqi_records = self.env['sos_iqi'].search([('ir_id_unique_id', 'in', ir_records.ids)])
            #dc_records  = self.env['sos_dc'].search([('po_no', '=', self.po_no.id)])
            grn_records = self.env['sos_grn'].search([('po_no', '=', self.po_no.id)])
            grn_line_records = self.env['sos_grn_line'].search([('grn_id', 'in', grn_records.ids)])
            #print(f"Inside grn_records:{grn_records} ")

            #self.dc_references  = [(6, 0, dc_records.ids)]
            self.grn_references = [(6, 0, grn_records.ids)]
            self.iqi_references = [(6, 0, iqi_records.ids)]
            self.received_qty   = sum(grn_records.line_ids.mapped('received_qty'))
            self.approved_qty   = sum(grn_records.line_ids.mapped('approved_qty'))
            self.rejected_qty   = sum(grn_records.line_ids.mapped('rejected_qty'))

            if grn_records.delivery:
                self.quality_marks        = round(sum(float(line.quality_marks) for line in grn_records.line_ids) / len(grn_records.line_ids), 2)
                self.delivery_marks       = grn_records.delivery
                self.responsiveness_marks = grn_records.responsiveness
                self.report_marks         = grn_records.reports
            else:
                self.quality_marks = 0
                self.delivery_marks = 0
                self.responsiveness_marks = 0
                self.report_marks = 0

            mat_record = []
            for record in grn_line_records:
                if record.component_id.part_no:  
                    mat_record.append(record.component_id.id)
                
            self.material_names = [(6, 0, mat_record)]

        else:
            # Clear the IQI references and quantities if no Work Order is selected
            self.dc_references  = [(5, 0, 0)]
            self.grn_references = [(5, 0, 0)]
            self.material_names = [(5, 0, 0)]
            self.iqi_references = [(5, 0, 0)]
            self.received_qty   = 0
            self.approved_qty   = 0
            self.rejected_qty   = 0
