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

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


class PosOrder(models.Model):
    _inherit = 'pos.order'

    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')

    @api.model
    def default_get(self, fields):
        res = super(PosOrder, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'enterprise_id': enterprise_id.id})
        return res

    @api.model
    def create(self, values):
        print "CREATE POS ORDER:::::::::::"
        print values
        partner_id,folio_id,booking_line_id=False,False,False
        if 'partner_id' in values:
            partner_id = values['partner_id']
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                self._cr.execute("""select r.partner_id,f.id as folio_id,b.id as booking_line_id
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g, etourism_enterprise_folio f 
where r.booking_id=b.id and b.booking_group_id=g.id and f.booking_group_id=g.id and b.state in ('hosted') and b.enterprise_id=%s and r.partner_id=%s limit 1
"""%(enterprise_id.id,partner_id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        folio_id=res[1]
                        booking_line_id=res[2]
            if folio_id and booking_line_id:
                booking_rec = self.env['etourism.booking'].browse(booking_line_id)
                if 'lines' in values:
                    for line in values['lines']:
                        print "LINE:::::::::::::::::"
                        print line[2]['product_id']
                        product_id = line[2]['product_id']
                        if product_id:
                            product_rec = self.env['product.product'].browse(product_id)
                            quantity = line[2]['qty']
                            price_unit = line[2]['price_unit']
                            self.env['etourism.enterprise.folio.line'].create({
							'folio_id': folio_id,
							'checkin_date': booking_rec.checkin,
							'checkout_date': booking_rec.checkout,
							'product_id': product_id,
							'client_id': partner_id,
							'product_uom_qty': quantity,
							'price_unit': price_unit,
							'booking_line_id': booking_line_id,
							'product_uom': product_rec.product_tmpl_id.uom_id.id
                            })
        return super(PosOrder, self).create(values)

class ReportSaleDetails(models.AbstractModel):

    _name = 'report.etourism_point_of_sale.report_saledetails'

    @api.model
    def get_sale_details(self, date_start=False, date_stop=False, configs=False):
        """ Serialise the orders of the day information

        params: date_start, date_stop string representing the datetime of order
        """
        if not configs:
            configs = self.env['pos.config'].search([])

        today = fields.Datetime.from_string(fields.Date.context_today(self))
        if date_start:
            date_start = fields.Datetime.from_string(date_start)
        else:
            # start by default today 00:00:00
            date_start = today

        if date_stop:
            # set time to 23:59:59
            date_stop = fields.Datetime.from_string(date_stop)
        else:
            # stop by default today 23:59:59
            date_stop = today + timedelta(days=1, seconds=-1)

        # avoid a date_stop smaller than date_start
        date_stop = max(date_stop, date_start)

        date_start = fields.Datetime.to_string(date_start)
        date_stop = fields.Datetime.to_string(date_stop)

        orders = self.env['pos.order'].search([
            ('date_order', '>=', date_start),
            ('date_order', '<=', date_stop),
            ('state', 'in', ['paid','invoiced','done']),
            ('config_id', 'in', configs.ids)])

        user_currency = self.env.user.company_id.currency_id

        total = 0.0
        products_sold = {}
        taxes = {}
        for order in orders:
            if user_currency != order.pricelist_id.currency_id:
                total += order.pricelist_id.currency_id.compute(order.amount_total, user_currency)
            else:
                total += order.amount_total
            currency = order.session_id.currency_id

            for line in order.lines:
                key = (line.product_id, line.price_unit, line.discount)
                products_sold.setdefault(key, 0.0)
                products_sold[key] += line.qty

                if line.tax_ids_after_fiscal_position:
                    line_taxes = line.tax_ids_after_fiscal_position.compute_all(line.price_unit * (1-(line.discount or 0.0)/100.0), currency, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
                    for tax in line_taxes['taxes']:
                        taxes.setdefault(tax['id'], {'name': tax['name'], 'total':0.0})
                        taxes[tax['id']]['total'] += tax['amount']

        st_line_ids = self.env["account.bank.statement.line"].search([('pos_statement_id', 'in', orders.ids)]).ids
        if st_line_ids:
            self.env.cr.execute("""
                SELECT aj.name, sum(amount) total
                FROM account_bank_statement_line AS absl,
                     account_bank_statement AS abs,
                     account_journal AS aj 
                WHERE absl.statement_id = abs.id
                    AND abs.journal_id = aj.id 
                    AND absl.id IN %s 
                GROUP BY aj.name
            """, (tuple(st_line_ids),))
            payments = self.env.cr.dictfetchall()
        else:
            payments = []

        return {
            'total_paid': user_currency.round(total),
            'payments': payments,
            'company_name': self.env.user.company_id.name,
            'taxes': taxes.values(),
            'products': sorted([{
                'product_id': product.id,
                'product_name': product.name,
                'code': product.default_code,
                'quantity': qty,
                'price_unit': price_unit,
                'discount': discount,
                'uom': product.uom_id.name
            } for (product, price_unit, discount), qty in products_sold.items()], key=lambda l: l['product_name'])
        }

    @api.multi
    def render_html(self, docids, data=None):
        company = request.env.user.company_id
        date_start = self.env.context.get('date_start', False)
        date_stop = self.env.context.get('date_stop', False)
        data = dict(data or {}, date_start=date_start, date_stop=date_stop)
        data.update(self.get_sale_details(date_start, date_stop, company))
        return self.env['report'].render('point_of_sale.report_saledetails', data)
