from odoo import api, fields, models, _
import logging
_logger = logging.getLogger(__name__)
from odoo.exceptions import ValidationError
from datetime import datetime
from odoo.exceptions import UserError

#import weasyprint
#import base64
import os

class SOS_Production_Plan(models.Model):
    _name = 'sos_production_plan'
    _description = 'FG Production Plan'
    _rec_name = 'plan_ref_no'
    

    plan_ref_no = fields.Char(
         required=True, string='Plan ID'
    )
    fg_name = fields.Many2one('sos_fg',string="FG Name",readonly=True)
    qp_no = fields.Integer(string="QP No",readonly=True)
    required_qty = fields.Integer(string='Required Qty',readonly=True,group_operator=False)
    total = fields.Integer(string='Completed Qty', readonly=True, compute='_compute_total')
    target_date = fields.Date(string='Target Date',readonly=True )
    indent_start_date = fields.Date(string="Indent Start Date")
    line_ids = fields.One2many('sos_transfer_challan_summary_lines', 'ref_id', string="Finished Goods",copy=True, ondelete='cascade')

    planned_week_1 = fields.Integer(string='Planned')
    actual_week_1 = fields.Integer(string='Actual')
    qc_week_1 = fields.Integer(string='QC Tested')

    planned_week_2 = fields.Integer(string='Planned')
    actual_week_2 = fields.Integer(string='Actual')
    qc_week_2 = fields.Integer(string='QC Tested')

    planned_week_3 = fields.Integer(string='Planned')
    actual_week_3 = fields.Integer(string='Actual')
    qc_week_3 = fields.Integer(string='QC Tested')

    planned_week_4 = fields.Integer(string='Planned')
    actual_week_4 = fields.Integer(string='Actual')
    qc_week_4 = fields.Integer(string='QC Tested')

    planned_week_5 = fields.Integer(string='Planned')
    actual_week_5 = fields.Integer(string='Actual')
    qc_week_5 = fields.Integer(string='QC Tested')

    planned_week_6 = fields.Integer(string='Planned')
    actual_week_6 = fields.Integer(string='Actual')
    qc_week_6 = fields.Integer(string='QC Tested')

    planned_week_7 = fields.Integer(string='Planned')
    actual_week_7 = fields.Integer(string='Actual')
    qc_week_7 = fields.Integer(string='QC Tested')

    planned_week_8 = fields.Integer(string='Planned')
    actual_week_8 = fields.Integer(string='Actual')
    qc_week_8 = fields.Integer(string='QC Tested')

    status = fields.Selection([
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
        ('held', 'Held'),
        ('cancelled', 'Cancelled')
    ], default='in_progress',string='Status')

    @api.depends('qc_week_1', 'qc_week_2', 'qc_week_3', 'qc_week_4', 'qc_week_5', 'qc_week_6', 'qc_week_7', 'qc_week_8')
    def _compute_total(self):
        for record in self:
            total = (
                record.qc_week_1 +
                record.qc_week_2 +
                record.qc_week_3 +
                record.qc_week_4 +
                record.qc_week_5 +
                record.qc_week_6 +
                record.qc_week_7 +
                record.qc_week_8
            )
            record.total = total
            if record.total >= record.required_qty:
                record.status = 'completed'
            else:
                record.status = 'in_progress'
    @api.constrains('planned_week_1', 'planned_week_2', 'planned_week_3', 'planned_week_4', 'planned_week_5', 'planned_week_6', 'planned_week_7', 'planned_week_8')
    def _check_total_planned(self):
        for record in self:
            total_planned = (
                record.planned_week_1 +
                record.planned_week_2 +
                record.planned_week_3 +
                record.planned_week_4 +
                record.planned_week_5 +
                record.planned_week_6 +
                record.planned_week_7 +
                record.planned_week_8
            )
            if total_planned > record.required_qty or total_planned < record.total:
                raise ValidationError("The total planned quantity for the weeks cannot exceed the required quantity.")

    @api.model
    def action_report_production_btn(self, from_date, to_date,force_download=True):
        
        self.env.cr.execute("""
           select a.id,a.name,b.required_qty,b.target_date from sos_fg a JOIN sos_production_plan b ON a.id = b.fg_name where b.target_date >= %s AND b.target_date <= %s;
        """,(from_date, to_date))

        productiondatas = self.env.cr.fetchall()
        if productiondatas:
            htmltableformat = self.generate_html_table(productiondatas)
            common_scripts  = self.env['sos_common_scripts']
            attachment = common_scripts.generate_html_report("Production Report",htmltableformat)
            
            if force_download:
                return {
                    'type': 'ir.actions.act_url',
                    'url': '/web/content/{}?download=true'.format(attachment.id),  # Link to the file
                    'target': 'new',  # Open in a new tab or download dialog
                }
            else:
                return attachment
        else:
            raise UserError("No data found for the selected date range.")

    def generate_html_table(self, productiondatas):
        """
        Generate an HTML table for the provided data.
        """

        #print("table 1")

        table_html = "<table style='border: solid 1px black; border-collapse: collapse;'>"
        table_html += '<tr><th style="border: solid 1px black;background-color: #808080; {font_style} ">SNO</th><th style="border: solid 1px black;background-color: #808080; {font_style} ">Name</th><th style="border: solid 1px black;background-color: #808080; {font_style} ">Production Qty</th><th style="border: solid 1px black;background-color: #808080; {font_style}">Target Date</th></tr>'

         # Define your custom font style
        font_style = "font-family: Arial, sans-serif; font-size: 12px; color: #000000;"
        #print("table 2")
        sno = 1
        for row in productiondatas:
            table_html += f'<tr><td style="border: solid 1px black; {font_style}">{sno}</td><td style="border: solid 1px black; {font_style}">{row[1]}</td><td style="border: solid 1px black; {font_style} ">{row[2]}</td><td style="border: solid 1px black; {font_style} ">{row[3]}</td></tr>'
            sno = sno+1
        #print("table 3")  
        table_html += "</table><br/><br/>"
        return table_html

class TC_Prod_Summ_Line(models.Model):
    _name = 'sos_transfer_challan_summary_lines'
    _description = 'tc summary Lines'

    ref_id = fields.Many2one('sos_production_plan')
    name = fields.Many2one('res.users',string="Name",readonly=True)
    date = fields.Char(string="Date")
    quantity = fields.Char(string="Quantity")
