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

from odoo import models, fields, api


class SOS_SFG(models.Model):
    _name = 'sos_sfg'
    _description = 'Semi-Finished Goods Master'

    sfg_code = fields.Char(string="Part No", required= True)
    code_no = fields.Char(string="Code")
    name = fields.Char(string="Display Name", required= True)
    sfg_type = fields.Selection([ ('In-House', 'In-House'),('Outsourcing', 'Outsourcing')], default='Outsourcing' , string="Type", required= True)
    category = fields.Selection([ ('pcba', 'PCB Board'),('cables', 'Cables & Connectors'),('others', 'Others')], default='pcba' , string="Category", required= True)
    qp_no = fields.Char(string="QP No")
    hsn_code = fields.Char(string="HSN Code")
    sac_code = fields.Char(string="SAC Code")
    opening_bal_qty = fields.Float(string="Opening Balance Qty")
    uom = fields.Selection([ ("Nos", "Nos"), ('Packs', 'Packs'),('set', 'set')], default="Nos" , string="UOM")
    currency_id = fields.Many2one('res.currency', string='Currency')
    minimum_stock_qty = fields.Integer(string="Minimum Stock Qty")
    minimum_order_qty = fields.Integer(string="Minimum Order Qty")
    inhand_stock_qty = fields.Integer(string="In-Hand Stock Qty")
    inhand_stock_val = fields.Monetary(string="In-Hand Stock Value", currency_field='currency_id',compute='_compute_stock_val', store=True)
    in_transit_stock_qty = fields.Integer(string="In-Transit Qty") 
    in_transit_stock_val = fields.Monetary(string="In-Transit Stock Value", currency_field='currency_id')
    received_qty = fields.Integer(string="Last Received Qty")
    received_stock_val = fields.Monetary(string="Last Received Stock Value", currency_field='currency_id')
    cancelled_qty = fields.Integer(string="Canceled Qty")
    blocked_qty = fields.Integer(string="Blocked Qty")
    issued_qty = fields.Integer(string="Issue to Dispatch Qty")
    issued_val = fields.Monetary(string="Issue to Dispatch Value", currency_field='currency_id')
    defect_qty = fields.Integer(string="Defect Qty")
    defect_val = fields.Monetary(string="Defect Value", currency_field='currency_id')
    order_qty = fields.Integer(string="Required/Order Qty")
    unit_price = fields.Monetary(string="Unit Price", currency_field='currency_id')
    msp = fields.Monetary(string="Max Selling Price", currency_field='currency_id')
    location = fields.Char(string="Location in Stores")
    image = fields.Image(string="Upload Image",max_height=100,max_width=100)
    service_providers=fields.Many2many("sos_service_providers",string="Service providers")
    description = fields.Text(string="Remarks")
    assembling_charges = fields.Monetary(string="Assembling cost per unit")
    line_ids_in = fields.One2many(
        'sos_sfg_transaction_history', 'ref_id',
        string="SFG History - In",
        domain=[('action', '=', 'in')]
    )

    line_ids_out = fields.One2many(
        'sos_sfg_transaction_history', 'ref_id',
        string="SFG History - Out",
        domain=[('action', '=', 'out')]
    )
    last_batch_no = fields.Char(string="Batch No")
    last_serial_no = fields.Integer(string="Last Serial No")
    def write(self, vals):
        assembling_changed = 'assembling_charges' in vals
        res = super().write(vals)

        if assembling_changed:
            for sfg in self:
                bom_records = self.env['sos_sfg_bom'].search([('name', '=', sfg.id)])
                for bom in bom_records:
                    bom._compute_overall_total()  # If you want to force recompute manually
                    bom._sync_unit_price_with_sfg()
        return res
    @api.onchange('category')
    def onchange_category(self):
        if self.category:
            prefix_map = {
                "pcba": "SP",
                "cables": "SC"
            }
            prefix = prefix_map.get(self.category, "SO")

            matching_records = self.env['sos_sfg'].search([
                ('code_no', 'like', prefix + '%')
            ])

            max_number = 0
            for rec in matching_records:
                code = rec.code_no
                if code.startswith(prefix):
                    suffix = code[len(prefix):]
                    if suffix.isdigit():
                        num = int(suffix)
                        if num > max_number:
                            max_number = num

            next_number = max_number + 1
            self.code_no = f"{prefix}{next_number}"



    @api.depends('unit_price','inhand_stock_qty')
    def _compute_stock_val(self):
        for val in self:
            val.inhand_stock_val = val.unit_price * val.inhand_stock_qty
class SOS_SFG_Line(models.Model):
    _name = 'sos_sfg_transaction_history'
    _description = 'SFG Lines'
    _order = 'date desc'

    ref_id = fields.Many2one('sos_sfg', string="SFG", ondelete="cascade")
    component_id = fields.Many2one('sos_sfg', string="Part No")
    action = fields.Selection([('in', 'IN'),('out', 'OUT')], string="Action", default='in')
    quantity = fields.Integer(string="Quantity")
    currency_id = fields.Many2one('res.currency', string='Currency')
    unit_price = fields.Monetary(string="Unit Price", currency_field='currency_id')
    date = fields.Datetime(string="Date", default=fields.Datetime.now)
    ir_no = fields.Many2one('sos_ir', string="Material Inward Ref No")
    min_no = fields.Many2one('sos_min', string="Material Issue Ref No")
    mrn_no = fields.Many2one('sos_mrn', string="Material Return Ref No")
    iqi_no = fields.Many2one('sos_iqi', string="In-house Inspection Ref No")


