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

class SOS_Batch_Allotment(models.Model):
    _name = 'sos_batch_allotment_register'
    _description = 'Batch Allotment Register'
    _rec_name = 'batch_no'

    alloted_date = fields.Datetime(string="Alloted Date")
    sfg_name = fields.Many2one('sos_sfg',string="SFG Name")
    fg_ref_no  = 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="FG Ref"
        )
    batch_no = fields.Char(string="Batch No")
    mfg_date = fields.Date(string="Manufacturing Date")
    batch_size = fields.Integer(string="Batch Size")
    qa_incharge = fields.Many2one('res.users', string='QA Incharge')
    last_serial_no = fields.Integer(string="Last Serial No")
    iqi_ref_no = fields.Many2one('sos_iqi',string="IQI Reference")


    @api.model
    def create(self, vals):
        sfg_record = self.env['sos_sfg'].browse(vals.get('sfg_name'))
        last_batch_no = sfg_record.last_batch_no 
        last_serial_no = sfg_record.last_serial_no  
        if last_batch_no is not None and last_serial_no is not None:
            current_year = datetime.now().strftime('%y')  
            current_month = datetime.now().strftime('%m') 
            
            prefix = last_batch_no[:-7] 
            last_suffix = last_batch_no[-3:] 

            last_batch_year = last_batch_no[6:8] 
            
            if last_batch_year == current_year:
                suffix_num = int(last_suffix[1:]) + 1 
                new_suffix = f"B{suffix_num:02d}"
            else:
                new_suffix = "B01"

            new_batch_no = f"{prefix}{current_year}{current_month}{new_suffix}"
            starting_serial_no = last_serial_no + 1
            batch_size = vals.get('batch_size', 10)  
            ending_serial_no = starting_serial_no + batch_size - 1

            formatted_start_serial = f"{starting_serial_no:03d}"
            formatted_end_serial = f"{ending_serial_no:03d}"
            vals.update({
                'batch_no': f"{new_batch_no}-{formatted_start_serial} to {new_batch_no}-{formatted_end_serial}",
                'last_serial_no': ending_serial_no
            })

      

            record = super(SOS_Batch_Allotment, self).create(vals)

            sfg_record.write({
                'last_batch_no': new_batch_no,
                'last_serial_no': ending_serial_no
            })

            return record
        else:
            raise UserError("Batch allotment format is missing (or) Incorrect for this SFG.")







