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

from odoo import models, fields, api


class SOS_SalesOrder(models.Model):
    _name = 'sos_sales_order'
    _description = 'Delivery Plan / Sales Order'
    _rec_name = 'order_id'
    _order = 'id desc' 

    order_id = fields.Char(string="Order Id",default=lambda self: self._generate_id(),readonly= True, required= True)
    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)
    line_ids = fields.One2many('sos_sales_order_line', 'ref_id',copy=True)
    customer_name = fields.Many2one('sos_inventory_customers',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")
    qty = fields.Integer(string="Quantity")
    purpose_of_delivery = fields.Selection([('sales', 'Sales'),('demo', 'Demo'),('warranty', 'Warranty'),('validation', 'Validation')],string="Purpose of Delivery",required=True)
    payment_status= fields.Selection([('credit_after_delivery', 'Payment After Delivery'),('received', 'Received'),('demo', 'Demo'),('warranty', 'Warranty'),('validation', 'Validation')],string="Payment Status",required=True)
    payment_terms= fields.Text(string="Payment Terms",required=True)
    billing_address = fields.Text(string="Billing Address",required=True)
    shipping_address = fields.Text(string="Shipping Address",required=True)
    gst_no = fields.Char(string="GST No",required=True)
    contact_person= fields.Char(string="Contact Person",required=True)
    contact_no =  fields.Char(string="Contact Number",required=True)
    test_report = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="Test Report")
    sdcard_data = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="SD card Data")
    cloud_data = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="Cloud Data")
    user_manual = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="User Manual")
    installation_video = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="Installation Video")
    wiring_diagram = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="Wiring Diagram")
    warranty_card = fields.Selection([('yes', 'Yes'),('no', 'No'),('na', 'NA')], default='yes',string="Warranty Card")
    customer_specific=fields.Html(string="Specific Requirements")
    specification_line_ids = fields.One2many('sos_sales_order_line', 'ref_id',copy=True,compute="_compute_specifications", inverse="_inverse_specifications", store=True)
    email_to =fields.Many2many('res.users', string='Share Order via Email')
    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")
    order_copy = fields.Binary(string="Order/PO Copy")
    order_copy_filename=fields.Char(string="PO DocumentFile Name")
    def action_report_esign_btn(self):
        sos_deliverables_boq_line = self.env['sos_deliverables_boq'].create({
            'sales_id':self.id,
            'fg_name':self.fg_name,
            'quantity':self.qty,
            'customer_name':self.customer_name.customer_name,
            'lead_time':self.lead_time,
            'customer_po_no':self.customer_po_no,
            'customer_po_date':self.customer_po_date

        })
        if sos_deliverables_boq_line:
            record = self.env['sos_deliverables_config'].search([('fg_name', '=', self.fg_name)], limit=1)
            if record:
                sos_deliverables_boq_line.line_ids_fg = [(5, 0, 0)]
                sos_deliverables_boq_line.line_ids_sfg = [(5, 0, 0)]
                sos_deliverables_boq_line.line_ids_material = [(5, 0, 0)]
                sos_deliverables_boq_line.line_ids_installation_kit = [(5, 0, 0)]
                for field_name, source_field in [
                    ('line_ids_fg', record.fg_ids),
                    ('line_ids_sfg', record.sfg_ids),
                    ('line_ids_material', record.material_ids),
                    ('line_ids_installation_kit', record.installation_kit_ids)
                ]:
                    lines = []
                    for line_id in source_field:
                        line_vals = {
                            'ref_id': sos_deliverables_boq_line.id,
                            'component_id': line_id.component_id.id,
                            'uom': line_id.uom,
                            'singet_set_qty': line_id.quantity,
                        }
                        lines.append((0, 0, line_vals))
                    setattr(sos_deliverables_boq_line, field_name, lines)
        self.env['sos_audit_log'].create_log('Request', 'Sales Order Generated')
        # Email part
        body_html = f"""
        <p>Below <b>Sales Order</b> is waiting for  Deliverables/BOQ Update</p>
        """
        send_email = self.env['sos_common_scripts']
        send_email.send_group_email(self.env,'sos_deliverables_boq',sos_deliverables_boq_line.id,"deenalaura.m@sosaley.in","Deliverables Request",body_html,'sos_inventory.sos_ce_user')

        # Email part ends
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.action_assign_signature(
        self, 
        'prepared_by_name',
        'prepared_on'
    )

            
 
    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_sales_order','SALES', 'order_id')

    # @api.model
    # def create(self, vals):
    #     customer_name = vals.get('customer_name')
    #     if customer_name:
    #         existing = self.env['sos_inventory_customers'].search([('customer_name', '=', customer_name)], limit=1)
    #         if not existing:
    #             self.env['sos_inventory_customers'].create({'customer_name': customer_name})

    #     return super(SOS_SalesOrder, self).create(vals)

class SOS_SalesOrder_Line(models.Model):
    _name = 'sos_sales_order_line'
    _description = 'Sales order Lines'

    ref_id = fields.Many2one('sos_sales_order',  ondelete="cascade")
    specification = fields.Many2one('sos_deliverables', string='Deliverables Name')
    uom = fields.Selection([('nos', 'Nos'), ('Packs', 'Packs'),('coils', 'Coils'),('mtrs', 'Meters'),('litre', 'litre')],default="nos", string="UOM")
    single_set_qty = fields.Integer(string="Single Set Qty")
    total_qty = fields.Integer(string="Total Qty",compute="_compute_total_qty")
    remarks = fields.Text(string="Remarks")
    description = fields.Text(string="Description")

    @api.depends('single_set_qty', 'ref_id.qty')
    def _compute_total_qty(self):
        for record in self:
            record.total_qty = record.single_set_qty * record.ref_id.qty

    @api.onchange('single_set_qty', 'ref_id')
    def _onchange_total_qty(self):
        for record in self:
            record.total_qty = record.single_set_qty * record.ref_id.qty
