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

from odoo import models, fields, api


class SOS_Oursourcing_Monitor(models.Model):
    _name = 'sos_outsourcing_vendor_monitoring_register'
    _description = 'Outsourcing Vendor Monitoring Register'
    _rec_name = 'service_provider_name'
    
    
    service_provider_name = fields.Many2one('sos_service_providers', string="Service Provider Name", required=True)
    qp_no= fields.Char(string="QP No",related="service_provider_name.qp_no")
    line_ids  = fields.One2many('sos_outsourcing_vendor_monitoring_register_lines','ref_id',copy=True)
    _sql_constraints = [
        ('service_provider_name_unique', 'UNIQUE(service_provider_name)', 'This Service Provider was already present')
    ]
class SOS_Oursourcing_Monitor_Lines(models.Model):
    _name = 'sos_outsourcing_vendor_monitoring_register_lines'
    _description = 'Outsourcing Vendor Montinoring Register Lines'
    
    ref_id = fields.Many2one('sos_outsourcing_vendor_monitoring_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")
    sfg_names = fields.Many2many('sos_sfg', string="SFG Name")
    
    wo_no = fields.Many2one(
        'sos_wo', 
        string="Work Order Reference No", 
        domain="[('supplier_name', '=', parent.service_provider_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('wo_no')
    def _onchange_wo_no(self):
        """Updates the IQI references based on the selected Work Order (wo_no)."""
        if self.wo_no:
            #print(f"Inside action: {self.wo_no.id}")
            ir_records  = self.env['sos_ir'].search([('wo_no', '=', self.wo_no.id)])
            iqi_records = self.env['sos_iqi'].search([('ir_id_unique_id', 'in', ir_records.ids)])
            #print(f"Inside action: {ir_records.ids}")
            dc_records  = self.env['sos_dc'].search([('wo_no', '=', self.wo_no.id)])
            #print(f"Inside if dc_records:{dc_records} ")
            #grn_records = self.env['sos_grn'].search([('iqi_no', 'in', iqi_records.ids)])
            grn_records = self.env['sos_grn'].search([('wo_no', '=', self.wo_no.id)])
            #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(iqi_records.mapped('received_qty'))
            self.approved_qty   = sum(iqi_records.mapped('approved_qty'))
            self.rejected_qty   = sum(iqi_records.mapped('rejected_qty'))

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

            sfg_record = []
            for record in iqi_records:
                if record.sfg_name.name:
                    sfg_record.append(record.sfg_name.id)
                
            self.sfg_names = [(6, 0, sfg_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.sfg_names      = [(5, 0, 0)]
            self.iqi_references = [(5, 0, 0)]
            self.received_qty   = 0
            self.approved_qty   = 0
            self.rejected_qty   = 0
