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

class SOS_CCRF(models.Model):
    _name = 'sos_ccrf'
    _description = 'Customer Complaint Registration Form'
    _rec_name = 'ccrf_no'

    ccrf_no = fields.Char(string="CCRF No", readonly= True, required= True, default=lambda self: self._generate_id())
    complaint_received_on = fields.Date(string="Complaint Received On")
    complaint_received_mode = fields.Selection([ ('email', 'Email'),('telephone', 'Telephone'),('oral', 'Oral')], default='email' , string="Complaint Received Mode")
    customer_name = fields.Many2one('sos_inventory_customers', string="Customer Name")
    customer_address = fields.Text(string="Address")
    customer_phone_number = fields.Char(string="Contact No")
    customer_email = fields.Char(string="Email Id")
    fg_name = fields.Selection(
            [
              ('BHMS 1.2V', 'BHMS 1.2V'), 
                ('BHMS 2V', 'BHMS 2V'), 
                ('BHMS 12V', 'BHMS 12V'),  
                ('BHMS 48V', 'BHMS 48V'),
                ('BMS-HV', 'BMS-HV'),
                ('BMS-LV 100A', 'BMS-LV 100A'), 
                ('BMS-LV 40A', 'BMS-LV 40A'), 
                ('SBMS 55A', 'SBMS 55A'),              
                ('MC 250W', 'MC 250W'),                                
                ('HeartTarang', 'HeartTarang')                  
            ],
            string="Product Type"
        )
    sub_fg_name = fields.Many2one('sos_fg', string="Product Name")
    batch_no = fields.Char(string="Batch No")
    complaint_details = fields.Text(string="Nature Of Complaint")
    incident_place = fields.Char(string="Place of Incident")
    incident_date = fields.Date(string="Date of Incident")

    invoice_no = fields.Char(string="Invoice No")
    quantity_dispatched = fields.Integer(string="Quantity Dispatched")
    batch_release_date = fields.Date(string="Invoice Date")
    brcoa_no = fields.Char(string="BRCOA No")
    brcoa_date = fields.Date(string="BRCOA Date")
    other_complaints = fields.Text(string="Details of any other Complaints received from this Production run")
    data_collected_by  = fields.Many2one('res.users', string='Data Collected By')
    data_collected_image = fields.Image(related="data_collected_by.signature_image",string='Data Collected Sign',readonly=True)
    data_collected_on = fields.Datetime(string="Data Collected On")
    interin_containment_actions = fields.Html(string="Interim Containment Action")
    device_failed_to_meet_specification = fields.Selection([ ('yes', 'YES'),('no', 'No')], default='no' , string="Device Failed To Meet Specification")
    labelling_error = fields.Selection([ ('yes', 'YES'),('no', 'No')], default='no' , string="Labelling Error")
    ifu = fields.Selection([ ('yes', 'YES'),('no', 'No')], default='no' , string="Error in Instruction For Use(IFU)")
    packaging_details = fields.Selection([ ('yes', 'YES'),('no', 'No')], default='no' , string="Packaging Error")
    processing = fields.Selection([ ('yes', 'YES'),('no', 'No')], default='no' , string="Processing")
    raw_materials = fields.Selection([ ('yes', 'YES'),('no', 'No')], default='no' , string="Raw Materials / Components")
    investigation_carriedout_by  = fields.Many2one('res.users', string='Investigation Carried Out By')
    investigation_carriedout_image = fields.Image(related="investigation_carriedout_by.signature_image",string='Investigation Carried Out Sign',readonly=True)
    investigation_carriedout_on = fields.Datetime(string="Investigation Carried Out On")
    root_cause = fields.Html(string="Root Cause",
    default="<p>Why #1</p><p>Why #2</p><p>Why #3</p>")
    rootcause_carriedout_by  = fields.Many2one('res.users', string='Root Cause Carried Out By')
    rootcause_carriedout_image = fields.Image(related="rootcause_carriedout_by.signature_image",string='Root Cause Carried Out Sign',readonly=True)
    rootcause_carriedout_on = fields.Datetime(string="Root Cause Carried Out On")
    corrective_action = fields.Html(string="Corrective Action")
    preventive_action = fields.Html(string="Preventive Action")
    capa_status = fields.Selection([ ('open', 'OPEN'),('close', 'Close')], default='open' , string="Status")
    status_reviewed_by  = fields.Many2one('res.users', string='Status Reviewed By')
    status_reviewed_image = fields.Image(related="status_reviewed_by.signature_image",string='Status Reviewed Out Sign',readonly=True)
    status_reviewed_on = fields.Datetime(string="Status Reviewed On")
    response_sent_date = fields.Date(string="Response Sent to Customer On")
    customer_feedback_on_response = fields.Text(string="Customer Feedback")
    qa_comments=fields.Text(string="QA Comments")
    qa_by = fields.Many2one('res.users',string='QC In-Charge',readonly=True)
    qa_sign = fields.Image(related="qa_by.signature_image",string='QC In-Charge',readonly=True)
    qa_closed_on = fields.Datetime(string="Approved On")
    rootcause_verifiedout_by  = fields.Many2one('res.users', string='Root Cause Verified By')
    rootcause_verifiedout_image = fields.Image(related="rootcause_verifiedout_by.signature_image",string='Root Cause Verified By Sign',readonly=True)
    rootcause_verifiedout_on = fields.Datetime(string="Root Cause Verified On")
    helper_field = fields.Many2many('sos_fg', string="Helper Field")
    @api.onchange('fg_name')
    def _onchange_fg_name(self):
        if self.fg_name:
            if " " in self.fg_name:
                second_half = self.fg_name.split(" ")[1]
            else:
                second_half = self.fg_name
            self.helper_field = self.env['sos_fg'].search([('sub_type', '=', second_half)])

    def action_report_ccrf_btn(self):
        try:
            action = self.env.ref("sos_inventory.action_report_ccrf").report_action(self)
            return action
        except ValueError as e:
            print(f"Failed to find report action: {e}")
           
            

    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_ccrf','CCRF', 'ccrf_no')
    
    def action_data_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'data_collected_by',
        'data_collected_on'
        )
    def action_rootcause_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'rootcause_carriedout_by',
        'rootcause_carriedout_on'
        )
    def action_investigation_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'investigation_carriedout_by',
        'investigation_carriedout_on'
        )
    def action_capa_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'status_reviewed_by',
        'status_reviewed_on'
        )
    def action_qa_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'qa_by',
        'qa_closed_on'
        )
    def action_rootcause_verify_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'rootcause_verifiedout_by',
        'rootcause_verifiedout_on'
        )
    