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

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

class SOS_Order_Delivery_Plan(models.Model):
    _name = 'sos_order_delivery_plan'
    _description = 'Order Delivery Plan'
    _rec_name = 'sales_id'
    _order = 'sales_id asc'
    
    sales_id = fields.Many2one('sos_sales_order',string="Sales Order 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 Name",required=True)
    quantity = fields.Integer(string="Quantity")
    customer_name = fields.Char(string="Customer Name")
    lead_time = fields.Datetime(string="Lead Time")
    customer_po_no = fields.Char(string="PO No")
    customer_po_date = fields.Datetime(string="PO Date")
    deliverables_boq_id = fields.Many2one('sos_deliverables_boq', string="Deliverables BOQ")
    line_ids_miscellaneous = fields.One2many(related='deliverables_boq_id.line_ids_miscellaneous', string="Miscellaneous", readonly=False)
    line_ids_installation_kit = fields.One2many(related='deliverables_boq_id.line_ids_installation_kit', string="Installation Kit", readonly=False)
    accounts_reviewed_by = fields.Many2one('res.users', string='Prepared by')
    accounts_reviewed_by_image = fields.Image(related="accounts_reviewed_by.signature_image",string='Reviewed by Sign',readonly=True)
    accounts_reviewed_on = fields.Datetime(string="Approved On")
    accounts_comments = fields.Text(string="Comments")
    top_management_comments = fields.Text(string="Comments")
    top_management_reviewed_by = fields.Many2one('res.users', string='Prepared by')
    top_management_reviewed_by_image = fields.Image(related="top_management_reviewed_by.signature_image",string='Reviewed by Sign',readonly=True)
    top_management_reviewed_on = fields.Datetime(string="Approved On")
    company_id = fields.Many2one('res.company', store=True, copy=False,
                                string="Company",
                                default=lambda self: self.env.user.company_id.id)
    currency_id = fields.Many2one('res.currency', string="Currency",
                                 related='company_id.currency_id',
                                 default=lambda
                                 self: self.env.user.company_id.currency_id.id)
    total_cost = fields.Monetary(compute='_compute_total_value',string="Total", currency_field='currency_id')
    total_cost_spare = fields.Monetary(compute='_compute_total_value_spare',string="Total", currency_field='currency_id')
    sfg_total_cost = fields.Monetary(compute='_compute_sfg_total_value',string="Total", currency_field='currency_id')
    sfg_total_cost_spare = fields.Monetary(compute='_compute_sfg_total_value_spare',string="Total", currency_field='currency_id')
    material_total_cost = fields.Monetary(compute='_compute_material_total_value',string="Total", currency_field='currency_id')
    material_total_cost_spare = fields.Monetary(compute='_compute_material_total_value_spare',string="Total", currency_field='currency_id')
    miscellaneous_total_cost = fields.Monetary(compute='_compute_miscellaneous_total_value',string="Total", currency_field='currency_id')
    installation_kit_total_cost = fields.Monetary(compute='_compute_installation_kit_total_value',string="Total", currency_field='currency_id')
    overall_cost =  fields.Monetary(compute='_compute_overall_value',string="Overall Cost", currency_field='currency_id')
    overall_cost_spare =  fields.Monetary(compute='_compute_overall_value_spare',string="Overall Spare Cost", currency_field='currency_id')
    final_cost =  fields.Monetary(compute='_compute_final_value',string="Estimated Cost", currency_field='currency_id')

    line_ids_fg = fields.One2many(
        comodel_name='sos_deliverables_line_fg',
        string="Finished Goods",
        compute='_compute_filtered_lines',
        readonly=False
    )
    line_ids_sfg = fields.One2many(
        comodel_name='sos_deliverables_line_sfg',
        string="Semi-Finished Goods",
        compute='_compute_filtered_lines',
        readonly=False
    )
    line_ids_material = fields.One2many(
        comodel_name='sos_deliverables_line_material',
        string="Materials",
        compute='_compute_filtered_lines',
        readonly=False
    )
    line_ids_fg_spare = fields.One2many(
        comodel_name='sos_deliverables_line_fg',
        string="Finished Goods",
        compute='_compute_filtered_lines_spare',
        readonly=False
    )
    line_ids_sfg_spare = fields.One2many(
        comodel_name='sos_deliverables_line_sfg',
        string="Semi-Finished Goods",
        compute='_compute_filtered_lines_spare',
        readonly=False
    )
    line_ids_material_spare = fields.One2many(
        comodel_name='sos_deliverables_line_material',
        string="Materials",
        compute='_compute_filtered_lines_spare',
        readonly=False
    )
    @api.depends(
        'deliverables_boq_id.line_ids_fg',
        'deliverables_boq_id.line_ids_sfg',
        'deliverables_boq_id.line_ids_material'
    )
    def _compute_filtered_lines(self):
        for record in self:
            if record.deliverables_boq_id:
                record.line_ids_fg = record._get_filtered_lines(record.deliverables_boq_id.line_ids_fg, False)
                record.line_ids_sfg = record._get_filtered_lines(record.deliverables_boq_id.line_ids_sfg, False)
                record.line_ids_material = record._get_filtered_lines(record.deliverables_boq_id.line_ids_material, False)
            else:
                record.line_ids_fg = False
                record.line_ids_sfg = False
                record.line_ids_material = False
    @api.depends(
        'deliverables_boq_id.line_ids_fg',
        'deliverables_boq_id.line_ids_sfg',
        'deliverables_boq_id.line_ids_material'
    )
    def _compute_filtered_lines_spare(self):
        for record in self:
            if record.deliverables_boq_id:
                record.line_ids_fg_spare = record._get_filtered_lines(record.deliverables_boq_id.line_ids_fg, True)
                record.line_ids_sfg_spare = record._get_filtered_lines(record.deliverables_boq_id.line_ids_sfg, True)
                record.line_ids_material_spare = record._get_filtered_lines(record.deliverables_boq_id.line_ids_material, True)
            else:
                record.line_ids_fg_spare = False
                record.line_ids_sfg_spare = False
                record.line_ids_material_spare = False
    def _get_filtered_lines(self, lines, is_spare_value):
        """Helper method to filter lines by is_spare."""
        return lines.filtered(lambda line: line.is_spare == is_spare_value and line.add_production_cost)

    @api.depends('overall_cost','overall_cost_spare','installation_kit_total_cost','miscellaneous_total_cost')
    def _compute_final_value(self):
        for record in self:
            record.final_cost = record.overall_cost + record.overall_cost_spare + record.installation_kit_total_cost  + record.miscellaneous_total_cost 
    @api.depends('total_cost','sfg_total_cost','material_total_cost')
    def _compute_overall_value(self):
        for record in self:
            record.overall_cost = record.total_cost + record.sfg_total_cost + record.material_total_cost 
    @api.depends('total_cost_spare','sfg_total_cost_spare','material_total_cost_spare')
    def _compute_overall_value_spare(self):
        for record in self:
            record.overall_cost_spare = record.total_cost_spare + record.sfg_total_cost_spare + record.material_total_cost_spare 
    @api.depends('line_ids_fg.total_price')
    def _compute_total_value(self):
        for record in self:
            record.total_cost = round(sum(line.total_price for line in record.line_ids_fg), 2)
    @api.depends('line_ids_fg_spare.total_price')
    def _compute_total_value_spare(self):
        for record in self:
            record.total_cost_spare = round(sum(line.total_price for line in record.line_ids_fg_spare), 2)
    @api.depends('line_ids_sfg.total_price')
    def _compute_sfg_total_value(self):
        for record in self:
            record.sfg_total_cost = round(sum(line.total_price for line in record.line_ids_sfg), 2)
    @api.depends('line_ids_sfg_spare.total_price')
    def _compute_sfg_total_value_spare(self):
        for record in self:
            record.sfg_total_cost_spare = round(sum(line.total_price for line in record.line_ids_sfg_spare), 2)
    @api.depends('line_ids_material.total_price')
    def _compute_material_total_value(self):
        for record in self:
            record.material_total_cost = round(sum(line.total_price for line in record.line_ids_material), 2)
    @api.depends('line_ids_material_spare.total_price')
    def _compute_material_total_value_spare(self):
        for record in self:
            record.material_total_cost_spare = round(sum(line.total_price for line in record.line_ids_material_spare), 2)
    
    @api.depends('line_ids_miscellaneous.total_price')
    def _compute_miscellaneous_total_value(self):
        for record in self:
            record.miscellaneous_total_cost = round(sum(line.total_price for line in record.line_ids_miscellaneous), 2)
    @api.depends('line_ids_installation_kit.total_price')
    def _compute_installation_kit_total_value(self):
        for record in self:
            record.installation_kit_total_cost = round(sum(line.total_price for line in record.line_ids_installation_kit), 2)
    
    def action_accounts_esign_btn(self):
        # Email part
        body_html = f"""
            <p>Below <b>Order Delivery Plan</b> is waiting for your Approval</p>
        """
        send_email = self.env['sos_common_scripts']
        send_email.send_direct_email(self.env,"sos_order_delivery_plan",self.id,"ramachandran.r@sosaley.in","Order Delivery Plan",body_html)
        # Email part ends
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.action_assign_signature(
        self, 
        'accounts_reviewed_by',
        'accounts_reviewed_on'
    )
    def update_order_qty(self, line_items, model_name):
        for item in line_items:
            sos_record = self.env[model_name].search([
                ('id', '=', item.component_id.id)
            ], limit=1)
            if sos_record:
                current_value = getattr(sos_record, 'order_qty', 0)
                sos_record.write({'order_qty': current_value + item.quantity})


    def action_top_management_esign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'top_management_reviewed_by',
        'top_management_reviewed_on',
        'sos_inventory.sos_management_user'
        )
        self.update_order_qty(self.line_ids_fg, 'sos_fg')
        self.update_order_qty(self.line_ids_fg_spare, 'sos_fg')
        self.update_order_qty(self.line_ids_sfg, 'sos_sfg')
        self.update_order_qty(self.line_ids_sfg_spare, 'sos_sfg')
        self.update_order_qty(self.line_ids_material, 'sos_material')
        self.update_order_qty(self.line_ids_material_spare, 'sos_material')
        self.update_order_qty(self.line_ids_installation_kit, 'sos_material')
        

