# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, tools, api


class CorProjectReport(models.Model):
    _name = "cor.project.report"
    _description = "COR Project Report"
    # _order = 'project_id'
    _auto = False

    project_id = fields.Many2one('project.project', string='Project', readonly=True)
    employee_id = fields.Many2one('hr.employee', string='Consultant', readonly=True)
    #hours_type = fields.Char(string="Hours Type", readonly=True)
    price_unit = fields.Float("Hourly Rate")
    budgeted_qty = fields.Float(string='Budgeted Hours', digits=(16, 2))
    cost = fields.Float("Budgeted Revenue", default=0.0, store=True)
    hours = fields.Float("Timesheet Hour", digits=(16, 2), readonly=True, group_operator="sum")
    employee_price = fields.Float(string="Consultant Price")
    consultant_cost = fields.Float("Actual Cost")
    actual_revenue = fields.Float("Actual Revenue")
    profit = fields.Float('Profit', digits=(16, 2))
    profit_per = fields.Float('Porfit(%)', digits=(16, 2))
    # pricing_type = fields.Selection([
    #     ('fixed_rate', 'Fixed rate'),
    #     ('employee_rate', 'Consultant rate')
    # ], string="Pricing", readonly=True)
    # project_type = fields.Selection([
    #     ('hours_in_consultant', 'Hours are budgeted according to a consultant'),
    #     ('hours_no_limit', 'Total hours are budgeted without division to consultant'),
    # ], string="Project Type", readonly=True)

    def init(self):
        '''Create the view'''
        tools.drop_view_if_exists(self._cr, self._table)
        self._cr.execute("""
        CREATE OR REPLACE VIEW %s AS (
        SELECT ROW_NUMBER() OVER() as id, 
        aa.project_id AS project_id, 
        aa.employee_id AS employee_id, 
        bb.price_unit AS price_unit, 
        bb.budgeted_qty AS budgeted_qty, 
        bb.cost AS cost, 
        bb.employee_price AS employee_price, 
        SUM(aa.unit_amount) AS hours,
        (SUM(aa.unit_amount) * bb.employee_price) AS consultant_cost,
        (SUM(aa.unit_amount) * bb.price_unit) AS actual_revenue,
        ((SUM(aa.unit_amount) * bb.price_unit)- (SUM(aa.unit_amount) * bb.employee_price)) AS profit,
        ((((SUM(aa.unit_amount) * bb.price_unit)- (SUM(aa.unit_amount) * bb.employee_price))/(SUM(aa.unit_amount) * bb.price_unit))*100) AS profit_per
        FROM account_analytic_line aa
        Left JOIN project_sale_line_employee_map bb ON bb.project_id = aa.project_id and bb.employee_id = aa.employee_id
        GROUP BY aa.project_id, aa.employee_id,bb.price_unit,bb.budgeted_qty,bb.cost,bb.employee_price
        )""" % (self._table,))
