# -*- coding: utf-8 -*-
from odoo import models, api, fields, _
from odoo.exceptions import ValidationError
import datetime


class SalesRefund(models.Model):
    _name = "sales.refund"
    _inherit = ['mail.thread']
    _description = u'退款單'

    name = fields.Char(string='退款單號')
    partner_id = fields.Many2one(
        comodel_name='res.partner', string='客戶', readonly=True)
    state = fields.Selection(
        selection=[('1', '草稿'), ('2', '已審核'), ('3', '駁回')], default='1', string='狀態')
    application_result = fields.Selection(
        selection=[('1', '批准'), ('2', '駁回')], string='申請結果', readonly=True)
    response_time = fields.Date(string='審核時間', readonly=True)
    refund = fields.Selection(selection=[(
        '1', '1.退款金額95%'), ('2', '2.退款金額90%'), ('3', '3.退款金額50%'), ('4', '4.退款金額1/3')], string='退款比例')
    refund_product = fields.One2many(
        comodel_name='sales.refund.line', inverse_name='sales_refund_id', string='退費明細')
    order_id = fields.Many2one(
        comodel_name='sale.order', string='關聯訂單', readonly=True)
    specialist = fields.Many2one(
        comodel_name='res.users', string='承辦專員', default=lambda self: self.env.uid, readonly=True)
    refund_date = fields.Date(string='申請退款日期', readonly=True)
    remarks = fields.Text(string='申請退款原因', readonly=True)
    turn_down_remarks = fields.Text(string='駁回原因')
    company_id = fields.Many2one(comodel_name='res.company')
    checkin_account_len = fields.Integer(compute='_compute_account_count')
    checkin_account_list = fields.One2many(
        comodel_name='account.invoice', inverse_name='sales_refund_id', string='會計憑證列表')
    all_amount_total = fields.Integer(
        string='退款總額', compute='_compute_all_amount_total', readonly=True)

    @api.depends('refund_product')
    def _compute_all_amount_total(self):
        all_amount_total = 0
        for line in self.refund_product:
            all_amount_total += line.amount_total
        self.all_amount_total = all_amount_total

    def open_account_list(self):
        action = self.env.ref('account.action_invoice_tree1').read()[0]
        action['domain'] = [('sales_refund_id', '=', self.id)]
        return action

    # 計算產生的發票有幾張
    def _compute_account_count(self):
        for partner in self:
            partner.checkin_account_len = len(partner.checkin_account_list)

    def approve_refund(self):
        self.response_time = datetime.date.today()
        self.application_result = '1'
        self.state = '2'
        return True

    def return_draft(self):
        self.state = '1'
        return True

    def create_refund(self):
        invoice_lines = []
        for line in self.refund_product:
            invoice_lines.append([0, 0, {
                'product_id': line.product_id.id,
                'company_id': self.order_id.company_id.id,
                'uom_id': line.product_id.uom_id.id,
                'quantity': line.quantity,
                'price_unit': line.amount_total,
                'invoice_line_tax_ids': [(6, 0, line.tax_ids.ids)],
                'name': line.product_id.name,
                'account_id': line.product_id.property_account_income_id.id or line.product_id.categ_id.property_account_income_categ_id.id,
            }])
        res = self.env['account.invoice'].create({
            'date_invoice': datetime.date.today(),
            'account_id': self.partner_id.property_account_receivable_id.id,
            'company_id': self.order_id.company_id.id,
            'partner_id': self.partner_id.id,
            'invoice_line_ids': invoice_lines,
            'user_id': self.specialist.id,
            'name': str(datetime.date.today().year) + str(datetime.date.today().month).zfill(2) + str(self.id),
            'sales_refund_id': self.id,
            'type': 'out_refund',
        })

    def reject_refund(self):
        self.response_time = datetime.date.today()
        self.application_result = '2'
        self.state = '2'
        return True

    @api.multi
    def write(self, values):
        is_changed = False
        msg = "<ul>"
        for object in self:
            if values.get('response_time'):
                is_changed = True
                msg += "<li>審核時間 : " + \
                    "%s</li>" % (values.get('response_time'))
            if values.get('application_result') and object.application_result != values.get('application_result'):
                is_changed = True
                state = dict(self._fields['application_result'].selection)
                msg += "<li>申請結果 : " + \
                    "%s</li>" % (state.get(values.get('application_result')))
            if values.get('state') and object.state != values.get('state'):
                is_changed = True
                state = dict(self._fields['state'].selection)
                msg += "<li>狀態 : " + \
                    "%s → %s</li>" % (state.get(object.state), state.get(values.get('state')))
                msg += "<li>退款總額 : " + \
                    "<b>%s</b></li>" % object.all_amount_total
            if values.get('turn_down_remarks') and object.turn_down_remarks != values.get('turn_down_remarks'):
                is_changed = True
                msg += "<li>駁回原因 : " + \
                    "%s</li>" % (values.get('turn_down_remarks'))
        if is_changed:
            msg += "</ul>"
            self.message_post(msg)
        return super().write(values)


class SalesRefundLine(models.Model):
    _name = "sales.refund.line"
    _description = u'退款單明細'

    sales_refund_id = fields.Many2one(comodel_name='sales.refund')
    order_id = fields.Many2one(
        comodel_name='sale.order', string='關聯訂單', readonly=True)
    refund = fields.Selection(selection=[(
        '1', '1.退款金額95%'), ('2', '2.退款金額90%'), ('3', '3.退款金額50%'), ('4', '4.退款金額1/3')], string='退款比例')
    product_id = fields.Many2one(
        comodel_name='product.product', string='課程', readonly=True)
    tax_ids = fields.Many2many(comodel_name='account.tax', string='稅')
    quantity = fields.Integer(string='數量', readonly=True)
    product_price = fields.Integer(string='售價', readonly=True)
    turn_down_remarks = fields.Char(string='駁回原因')
    company_id = fields.Many2one(comodel_name='res.company')

    @api.multi
    @api.depends('tax_ids','refund')
    def _compute_amount(self):
        refund_ratio = {'1': 0.95, '2': 0.9, '3': 0.5, '4': (1/3)}
        for refund in self:
            refund.amount_total = round(refund.product_price * refund.quantity * refund_ratio.get(refund.refund, 1), 0)
            # if len(refund.tax_ids) > 0:
            #     refund.amount_total = refund.product_price * refund.quantity
            #     tax_amount = 0
            #     for tax in refund.tax_ids:
            #         tax_amount += tax.amount
            #     refund.amount_total = refund.amount_total - ((refund.amount_total * tax_amount) / 100)
            # elif len(refund.tax_ids) <= 0:
            #     refund.amount_total = refund.product_price * refund.quantity

    amount_total = fields.Integer(
        string='退款金額', compute='_compute_amount', store=True)


class Account(models.Model):
    _inherit = 'account.invoice'
    sales_refund_id = fields.Many2one(
        comodel_name='sales.refund', string='退款單')
