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

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

class sos_return_iqi(models.Model):
    _name = 'sos_return_iqi'
    _description = 'Retrun - Incoming Quality Inspection'
    _rec_name = 'iqi_no'
    _order = 'iqi_no desc'

    iqi_no = fields.Char(string="IQI No", readonly= True, required= True, default=lambda self: self._generate_id())
    iqi_date = fields.Datetime(string="IQI Date",  default=fields.Datetime.now)
    mrn_id=fields.Many2one('sos_mrn', string='Return Ref No')
    batch_no = fields.Char(string="Batch No")
    fg_name = fields.Many2one('sos_fg', string='FG Name')
    material_name = fields.Many2one('sos_material', string="Material Name")
    material_code = fields.Char(string="Material Code")
    material_category = fields.Many2one('sos_material_configuration',string="Material Category")
    rca_required = fields.Selection([('yes', 'Yes'),('no', 'No')], string="RCA Required")
    sfg_name = fields.Many2one('sos_sfg', string="SFG Name")
    sfg_code = fields.Char(string="SFG Code",related="sfg_name.sfg_code")
    sfg_category = fields.Many2one('sos_sfg_configuration',string="SFG Category")
    rca_notes_text=fields.Text(string="Notes",default="The requirement for a Root Cause Analysis (RCA) is determined by defect severity, recurrence, or a defect rate below 10,000 parts per million (PPM).")
    ncmr_ref = fields.Many2one('sos_ncmr',string="NCMR Reference (If any Rejected)")
    dc_no = fields.Char(string="DC No")
    dc_date = fields.Datetime(string="DC date")
    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')
    testing_line_ids = fields.One2many('sos_return_testing_parameters_line', 'ref_id', ondelete='cascade')
    calibration_line_ids = fields.One2many('sos_return_iqi_calibration_line','calibration_id', ondelete='cascade')
    material_option = fields.Boolean('Materials', default=True)
    sfg_option = fields.Boolean('Semi-Finished Goods')
    prepared_by_name = fields.Many2one('res.users', string='Prepared by')
    prepared_by_image = fields.Image(related="prepared_by_name.signature_image",string='Prepared by Sign',readonly=True)
    prepared_on = fields.Datetime(string="Approved On")
    iqi_type = fields.Selection([('sfg','SFG'),('material','Material')],string='IQI Type',compute='_compute_iqi_type',store=True)
    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')
    qc_tested_on = fields.Datetime(string="Approved On")

    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")

    qa_by_name = fields.Many2one('res.users', string='QA 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")
    qa_comments = fields.Text(string="QA Comments")
    ppm = fields.Integer(string="PPM",compute="_compute_ppm")
    status = fields.Selection([ ('open', 'Open'),('closed', 'Closed')], default='open' , string="Status")

    @api.depends('material_option', 'sfg_option')
    def _compute_iqi_type(self):
        for record in self:
            if record.sfg_option:
                record.iqi_type = 'sfg'
            elif record.material_option:
                record.iqi_type = 'material'
            else:
                record.iqi_type = False

    @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.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.onchange('material_category')
    def _onchange_material_category(self):
        if self.material_category:
            self._load_testing_parameters('material')
    @api.onchange('sfg_category')
    def _onchange_sfg_category(self):
        if self.sfg_category:
            self._load_testing_parameters('sfg')
    def _load_testing_parameters(self,types):
        if types == 'material':
            if self.material_category:
                testing_parameters = self.env['sos_material_configuration'].search([('id', '=', self.material_category.id)])
                if not testing_parameters:
                    raise UserError('No testing parameters found for this Item.')
                lines = [(5, 0, 0)]
                sorted_parameters = testing_parameters.parameter_ids.sorted(key=lambda param: param.sequence)

                for param in sorted_parameters:
                    lines.append((0, 0, {
                        'testing_parameter': param.name,
                        'req_readings':param.observation,
                        'obtained_readings':param.obtained_observation
                        
                    }))
                self.testing_line_ids = lines
        else:
            if self.sfg_category:
                testing_parameters = self.env['sos_sfg_configuration'].search([('id', '=', self.sfg_category.id)])
                if not testing_parameters:
                    raise UserError('No testing parameters found for this Item.')
                lines = [(5, 0, 0)]
                sorted_parameters = testing_parameters.parameter_ids.sorted(key=lambda param: param.sequence)
                for param in sorted_parameters:
                    lines.append((0, 0, {
                        'testing_parameter': param.name,
                        'req_readings':param.observation,
                        'obtained_readings':param.obtained_observation
                    }))
                self.testing_line_ids = lines
    @api.onchange('material_option')
    def _onchange_material_option(self):
        if self.material_option:
            self.sfg_option = False

    @api.onchange('sfg_option')
    def _onchange_sfg_option(self):
        if self.sfg_option:
            self.material_option = False
    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_return_iqi','Return-IQI', 'iqi_no')

    def action_report_esign_btn(self):
        # Email part
        body_html = f"""
        <p>Below <b>IQI</b> is waiting for your Approval</p>
        """
        send_email = self.env['sos_common_scripts']
        send_email.send_group_email(self.env,'sos_iqi',self.id,"deenalaura.m@sosaley.in","IQI Approval Request",body_html,'sos_inventory.sos_qc_user')
        # Email part ends
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.action_assign_signature(
        self, 
        'prepared_by_name',
        'prepared_on'
    )
    def action_qc_esign_btn(self):
        #If rejected ncmr creation
        sequence_util = self.env['sos_common_scripts']
        ncmr_id = sequence_util.generate_sequence('sos_ncmr', 'NCMR', 'ncmr_no')
        if self.rejected_qty > 0:
            if self.material_option:
                
                ncmr_record = self.env['sos_ncmr'].create({
                            'ncmr_no': ncmr_id,
                            'material_option':True,
                            'fg_option':False,
                            'sfg_option':False,
                            'batch_no':self.batch_no,
                            'rejected_qty':self.rejected_qty,
                            'material_name': self.material_name.id,
                            'material_code': self.material_name.material_code,
                            'ncmr_type':'return',
                            'return_incoming_doc_ref':self.id,
                            'department':'Quality Control',
                            'rca_required':self.rca_required
                        })
            else:
                ncmr_record = self.env['sos_ncmr'].create({
                            'ncmr_no': ncmr_id,
                            'material_option':False,
                            'sfg_option':True,
                            'fg_option':False,
                            'batch_no':self.batch_no,
                            'rejected_qty':self.rejected_qty,
                            'sfg_name': self.sfg_name.id,
                            'sfg_code': self.sfg_name.sfg_code,
                            'ncmr_type':'return',
                            'return_incoming_doc_ref':self.id,
                            'department':'Quality Control',
                            'rca_required':self.rca_required
                        })
            self.ncmr_ref = ncmr_record.id
            ncmr_body_html = f"""
        <p>Below <b>NCMR</b> is waiting for your Inspection</p>
        """
            sequence_util.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>IQI</b> is waiting for your Approval</p>
        """
        
        sequence_util.send_group_email(self.env,'sos_iqi',self.id,"deenalaura.m@sosaley.in","IQI Approval Request",body_html,'sos_inventory.sos_scg_group_user')
        # Email part ends
        return sequence_util.action_assign_signature(
        self, 
        'qc_by_name',
        'qc_tested_on'
    )
    def action_qa_esign_btn(self):
        self.status = "closed"
        if self.ncmr_ref:
            self.ncmr_ref.rca_required = self.rca_required
            self.ncmr_ref.rca_notes_text = self.rca_notes_text
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.action_assign_signature(
        self, 
        'qa_by_name',
        'qa_tested_on'
    )
    def update_stocks(self):
        if self.material_option == True:
            approved_qty = self.approved_qty
            current_qty = self.material_name.inhand_stock_qty
            current_value = self.material_name.unit_price
            new_qty = current_qty + approved_qty
            if new_qty > 0:  
                new_unit_price = ((current_qty * current_value) + (approved_qty * self.material_name.unit_price)) / new_qty
            else:
                new_unit_price = self.material_name.unit_price
            self.material_name.inhand_stock_qty = new_qty
            self.material_name.unit_price =  new_unit_price
            if approved_qty > 0:
                self.env['sos_material_transaction_history'].create({
                    'ref_id': self.material_name.id,
                    'mrn_no': self.mrn_id.id,
                    'component_id': self.material_name.id,
                    'quantity': approved_qty,
                    'unit_price': self.material_name.unit_price,
                    'action': 'in',
                })
        elif self.sfg_option == True:
            approved_qty = self.approved_qty
            current_qty = self.sfg_name.inhand_stock_qty
            current_value = self.sfg_name.unit_price
            new_qty = current_qty + approved_qty
            if new_qty > 0:  
                new_unit_price = ((current_qty * current_value) + (approved_qty * self.sfg_name.unit_price)) / new_qty
            else:
                new_unit_price = self.sfg_name.unit_price
            self.sfg_name.inhand_stock_qty = new_qty
            self.sfg_name.unit_price =  new_unit_price
            if approved_qty > 0:
                self.env['sos_sfg_transaction_history'].create({
                    'ref_id': self.sfg_name.id,
                    'mrn_no': self.mrn_id.id,
                    'component_id': self.sfg_name.id,
                    'quantity': approved_qty,
                    'unit_price': self.sfg_name.unit_price,
                    'action': 'in',
                })
        
    def action_stores_received_esign_btn(self):
        self.update_stocks()
        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'
        )
        # Email part
        body_html = f"""
        <p>Below <b>IQI</b> is waiting for your Approval</p>
        """
        send_email = self.env['sos_common_scripts']
        send_email.send_group_email(self.env,'sos_return_iqi',self.id,"deenalaura.m@sosaley.in","Return - IQI Approval Request",body_html,'sos_inventory.sos_qa_user')
        # Email part ends
        
class sos_return_testing_lines(models.Model):
    _name = 'sos_return_testing_parameters_line'
    _description = 'Return IQI Testing Parameters Lines'

    ref_id = fields.Many2one('sos_return_iqi', string="Materials", ondelete="cascade")
    qp_no = fields.Char(string="QP No")
    testing_parameter = fields.Char(string="Testing Parameter")
    req_readings = fields.Char(string="Required Readings / Observation")
    obtained_readings = fields.Char(string="Obtained Readings / Observation")
    inspection_remark = fields.Selection([('PASS','PASS'),('FAIL','FAIL')],string="Inspection Remarks")
    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")
    aodr_qty = fields.Integer(string="Accepted on Deviation  (or) Reworked Qty (If any)")
    aodr_no = fields.Many2one('sos_aodr',string="AODR NO")


class SOS_iqi_calibration_line(models.Model):
    _name = 'sos_return_iqi_calibration_line'
    _description = 'Calibration Devices of Return - IQI'

    calibration_id = fields.Many2one('sos_return_iqi', string="Materials", ondelete="cascade")
    name = fields.Many2one('sos_calibration_devices',string="Equipment Name", required=True)
    s_no = fields.Char(string="Equipment Serial No",related="name.s_no")
    identification_no= fields.Char(string="Identification No",related="name.identification_no")
    certification_no= fields.Char(string="Certification No",related="name.certification_no")
    calibrated_on = fields.Date(string="Calibrated On",related="name.calibrated_on")
    calibrated_due = fields.Date(string="Calibration Due",related="name.calibrated_due")