from odoo import models, fields, api

class SosCaseDiaryReport(models.Model):
    _name = 'sos_case_diary_report'
    _description = 'Case Diary Report'

    customer_name = fields.Many2one('sos_case_diary', string="Customer Name")
    action_plan_date = fields.Date(string="Action Plan Date")
    currency_id = fields.Many2one('res.currency', string='Currency')
    current_state_value = fields.Monetary(currency_field='currency_id',string="Value(In Lakhs)")
    action_plan = fields.Text(string="Action Plan")
    notes = fields.Text(string="Remarks")
    spenco_status = fields.Selection([('Suspects','Suspects'),('Prospects','Prospects'),('Engaged','Engaged'),('Negotiation','Negotiation'),('Commercial Order','Commercial Order')], string='Status')
    status_changed_on = fields.Date(string="Status Changed On")
    spenco_summary = fields.Text(string="SPENCO Summary")
    reporting_to = fields.Many2one('res.users', string='Reporting To')
    sales_person = fields.Many2one('res.users', string='Sales Executive')

    @api.model
    def create(self, vals):
        create_uid = vals.get('create_uid', self.env.uid)
        create_user = self.env['res.users'].browse(create_uid)
        vals['reporting_to'] = create_user.reporting_to.id 
        return super(SosCaseDiaryReport, self).create(vals)
    @api.model
    def action_generate_report(self, from_date, to_date, sales_person_id=None, customer=None):
        self.search([]).unlink()
        domain = []
        if customer:
            domain.append(('ref_id.customer_name', '=', customer.customer_name))
        if from_date:
            domain.append(('status_changed_on', '>=', from_date))
        if to_date:
            domain.append(('status_changed_on', '<=', to_date))
        if sales_person_id:
            domain.append(('ref_id.sales_person', '=', sales_person_id))
        
        if not domain:
            sos_lines = self.env['sos_case_diary_line'].search([], order='id desc')
        else:
            sos_lines = self.env['sos_case_diary_line'].search(domain, order='id desc')

        if sos_lines:
            # Sort sos_lines by sales_person name to ensure proper grouping
            sos_lines = sorted(sos_lines, key=lambda l: l.ref_id.sales_person.name if l.ref_id.sales_person else '')

            created_records = []
            spenco_summary_data = {
                'Suspects': {'count': 0, 'total_value': 0},
                'Prospects': {'count': 0, 'total_value': 0},
                'Engaged': {'count': 0, 'total_value': 0},
                'Negotiation': {'count': 0, 'total_value': 0},
                'Commercial Order': {'count': 0, 'total_value': 0},
            }
            latest_lines = []

            for line in sos_lines:
                ref_id = line.ref_id.id
                if ref_id not in latest_lines:
                    latest_lines.append(ref_id)

                    if line.spenco_status in spenco_summary_data:
                        spenco_summary_data[line.spenco_status]['count'] += 1
                        spenco_summary_data[line.spenco_status]['total_value'] += line.current_state_value or 0

                    record = self.create({
                        'customer_name': line.ref_id.id,
                        'sales_person': line.ref_id.sales_person.id,
                        'action_plan_date': line.action_plan_date,
                        'current_state_value': line.current_state_value,
                        'action_plan': line.action_plan,
                        'notes': line.notes,
                        'spenco_status': line.spenco_status,
                        'status_changed_on': line.status_changed_on,
                    })
                    created_records.append(record.id)

            # Prepare summary text for the first record
            summary_text = "\n".join(
                f"{status}: Count = {data['count']}, Total Value = {data['total_value']}" 
                for status, data in spenco_summary_data.items()
            )

            if created_records:
                self.browse(created_records[0]).write({'spenco_summary': summary_text})

            return self.env.ref('sos_sales.action_case_diary_report').report_action(self.browse(created_records))

        else:
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'message': "No Records Found",
                    'type': 'danger',
                    'sticky': False
                }
            }

class SosCaseDiaryReportSummary(models.Model):
    _name = 'sos_case_diary_report_summary'
    _description = 'Case Diary Report Summary'

    session_id = fields.Char(string="Session ID", index=True, required=True)
    status = fields.Selection([('Suspects','Suspects'),('Prospects','Prospects'),('Engaged','Engaged'),('Negotiation','Negotiation'),('Commercial Order','Commercial Order')], string='Status')
    count = fields.Integer(string="Count")
