from odoo import models, fields, api
from odoo.exceptions import UserError

class Return_FIR_BRR(models.Model):
    _name = 'sos_return_fir'
    _description = 'Return - Batch Release Report'
    _rec_name='fir_no'
    _order = 'id desc' 
    fir_no = fields.Char(string="BRR No",default=lambda self: self._generate_id(),readonly= True, required= True)
    fir_date = fields.Date(string="BRR Date")
    fg_name = fields.Many2one('sos_fg', string='FG Name')
    plan_ref_no = fields.Char(
        readonly=True,string='Indent No'
    )
    customer_name = fields.Many2one('sos_inventory_customers', string="Customer Name")

    batch_size = fields.Integer(string="Batch Size / Received Quantity")
    serial_no = fields.Char(string="Serial No")
    batch_No = fields.Char(string="Batch No")
    mfg_date = fields.Date(string="Manufacturing Date")
    sampling_size = fields.Char(string="Sampling Size")
    calibration_line_ids = fields.One2many('sos_return_calibration_devices_fir', 'ref_id',copy=True)
    testing_parameter_line_ids = fields.One2many('sos_return_fir_line', 'ref_line_id',copy=True)
    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')
    qc_by_name = fields.Many2one('res.users', string='QC Tested&Provided by Sign')
    qc_by_image = fields.Image(related="qc_by_name.signature_image",string='Prepared by Sign',readonly=True)
    qc_tested_on = fields.Datetime(string="Approved On")
    reworked_count = fields.Integer(string="Reworked Count",default=0)
    qa_by_name = fields.Many2one('res.users', string='QA by Sign')
    qa_by_image = fields.Image(related="qa_by_name.signature_image",string='Prepared by Sign',readonly=True)
    qa_tested_on = fields.Datetime(string="Approved On")
    ppm = fields.Integer(string="PPM",compute="_compute_ppm")
    stores_received_by = fields.Many2one('res.users', string='Store Received by Sign')
    stores_received_image = fields.Image(related="stores_received_by.signature_image",string='Stores Received by Sign',readonly=True)
    stores_received_on = fields.Datetime(string="Stores Received On")
    stores_provided_by = fields.Many2one('res.users', string='Store Provided by Sign')
    stores_provided_image = fields.Image(related="stores_provided_by.signature_image",string='Stores Provided by Sign',readonly=True)
    stores_provided_on = fields.Datetime(string="Stores Provided On")
    ncmr_ref = fields.Many2one('sos_ncmr',string="NCMR Reference (If any Rejected)")
    qa_comments = fields.Text(string="QA Comments")
    @api.depends('batch_size', 'rejected_qty')
    def _compute_ppm(self):
        for record in self:
            if record.rejected_qty != 0:
                record.ppm = (record.rejected_qty / record.batch_size) * 10**6
            else:
                record.ppm = 0 
    @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('batch_size', 'rejected_qty')
    def _compute_rejected_percentage(self):
        for record in self:
            if record.batch_size > 0:
                record.rejection_percentage = (record.rejected_qty / record.batch_size) * 100
            else:
                record.rejection_percentage = 0
    def action_qc_esign_btn(self):
        send_email = self.env['sos_common_scripts']
        if self.rejected_qty > 0:
            ncmr_id = send_email.generate_sequence('sos_ncmr', 'NCMR', 'ncmr_no')
            ncmr_record = self.env['sos_ncmr'].create({
                            'ncmr_no': ncmr_id,
                            'material_option':False,
                            'fg_option':True,
                            'sfg_option':False,
                            'batch_no':self.batch_No,
                            'rejected_qty':self.rejected_qty,
                            'fg_name': self.fg_name.id,
                            'ncmr_type':'return',
                            'return_fg_incoming_doc_ref':self.id,
                            'department':'Quality Control'
                        })
            if ncmr_record:
                self.ncmr_ref = ncmr_record.id
            ncmr_body_html = f"""
        <p>Below <b>NCMR</b> is waiting for your Inspection</p>
        """
            send_email.send_group_email(self.env,'sos_ncmr',ncmr_id,"deenalaura.m@sosaley.in","NCMR Inspection Pending",ncmr_body_html,'sos_inventory.sos_qc_user')

        # Email part
        body_html = f"""
        <p>Below <b>BRR</b> is waiting for your Approval</p>
        """
        
        
        send_email.send_group_email(self.env,"sos_fir_brr",self.id,"deenalaura.m@sosaley.in","BRR Approval Request",body_html,'sos_inventory.sos_qa_user')
        # Email part ends
        return send_email.action_assign_signature(
        self, 
        'qc_by_name',
        'qc_tested_on'
    )
    def action_qa_esign_btn(self):
        # Email part
        body_html = f"""
        <p>Below <b>BRR</b> is waiting for your Approval</p>
        """
        
        send_email = self.env['sos_common_scripts']
        send_email.send_group_email(self.env,"sos_fir_brr",self.id,"deenalaura.m@sosaley.in","BRR Approval Request",body_html,'sos_inventory.sos_scg_group_user')
        # Email part ends
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.action_assign_signature(
        self, 
        'qa_by_name',
        'qa_tested_on'
    )
    def action_stores_provide_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'stores_provided_by',
        'stores_provided_on',
        'sos_inventory.sos_scg_group_user'
        )
    def action_stores_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'stores_received_by',
        'stores_received_on',
        'sos_inventory.sos_scg_group_user'
        )
        approved_qty = self.approved_qty
        if approved_qty > 0:  
            current_qty = self.fg_name.inhand_stock_qty
            current_value = self.fg_name.unit_price
            new_qty = current_qty + approved_qty
            self.fg_name.inhand_stock_qty = new_qty
            self.env['sos_fg_transaction_history'].create({
                'ref_id': self.fg_name.id,
                'return_fir_no': self.id,
                'component_id': self.fg_name.id,
                'quantity': approved_qty,
                'action': 'in',
            })
        
    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_return_fir','Return-BRR', 'fir_no')
    
    @api.onchange('fg_name')
    def _onchange_fg_name(self):
        if self.fg_name:
            self._load_testing_parameters()

    @api.model
    def create(self, vals):
        record = super(Return_FIR_BRR, self).create(vals)
        if record.fg_name:
            record._load_testing_parameters()
        return record

    def write(self, vals):
        result = super(Return_FIR_BRR, self).write(vals)
        if 'fg_name' in vals:
            self._load_testing_parameters()
        return result

    def _load_testing_parameters(self):
        if self.fg_name:
            testing_parameters = self.env['sos_testing_parameters'].search([('fg_name', '=', self.fg_name.id)])
            if not testing_parameters:
                print('No testing parameters found for this FG.')

            # Clear any existing lines
            lines = [(5, 0, 0)]

            sorted_parameters = testing_parameters.parameter_ids.sorted(key=lambda param: param.sequence)
            # Append the sorted parameters
            for param in sorted_parameters:
                lines.append((0, 0, {
                    'testing_parameter': param.id,
                    'sequence': param.sequence,
                    'specification': param.specification,
                    'results': param.results,
                    'inspection_decision':param.inspection_decision
                }))

            # Set the sorted lines to testing_parameter_line_ids
            self.testing_parameter_line_ids = lines


class Return_FIR_BRR_Line(models.Model):
    _name = 'sos_return_fir_line'
    _description = 'Return - Batch Release Report Line Items'

    ref_line_id = fields.Many2one('sos_return_fir',  ondelete="cascade")
    sequence = fields.Integer(string="sequence")
    testing_parameter = fields.Many2one('sos_parameter', string='Testing Parameter')
    sampled_qty = fields.Integer(string="Sampled Quantity")
    accepted_qty = fields.Integer(string="Accepted Quantity")
    rejected_qty = fields.Integer(string="Rejected Quantity")
    remarks = fields.Text(string="Remarks")
    inspection_decision = fields.Selection([('PASS','PASS'),('FAIL','FAIL')],string="Inspection Decision")
    specification = fields.Char(string="Specification")
    results = fields.Text(string="Results")

class Return_Calibration_devices(models.Model):
    _name = 'sos_return_calibration_devices_fir'
    _description = 'Calibartion Devices List'
    
    ref_id = fields.Many2one('sos_return_fir',  ondelete="cascade")
    calibration_device = fields.Many2one('sos_calibration_devices',string="Equipment Name", required=True)
    identification_No = fields.Char(string="Identification No",related="calibration_device.identification_no")
    certification_No = fields.Char(string="Certification No",related="calibration_device.certification_no")
    calibrated_date = fields.Date(string="Calibrated Date",related="calibration_device.calibrated_on")
    due_date = fields.Date(string="Due Date",related="calibration_device.calibrated_due")

