# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Create by Carmen <carmen.ling@yunside.com> at 2018/5/17

from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.osv import expression
import datetime

FIN_STATE = [('draft', u'新建'),
             ('confirm', u'确认'),
             ('audit', u'审核'),
             ('unaudit', u'反审核'),
             ('closed', u'关账'),
             ('cancel', u'作废')]


class AbstractBaseBizFinance(models.AbstractModel):
    """
    财务类业务单据(涉及大金额往来或出入库，需要关账)抽象基类，所有财务类业务单据继承实现，如果有特殊行为和属性，可以覆盖重新定义
    _sql_constraints数据库约束需实现类自行定义
    """

    _name = 'jdg.abstract.base.biz.fin'
    _inherit = 'jdg.abstract.base.biz'
    _description = u"财务单据基类"
    _order = 'number desc'

    state = fields.Selection(FIN_STATE, string=u'状态', default='draft', help=u'控制数据是否有效')
    time_post = fields.Datetime(string=u'关账时间', readonly=True)
    uid_post = fields.Many2one('res.users', string=u'关账者', readonly=True)
    is_post = fields.Boolean(string=u'是否待关账', default=False, readonly=True, help=u'关账时以该字段为筛选条件')

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        for item in self:
            item.hide_edit_button = item.state in ('audit', 'confirm', 'closed')
    
    @api.multi
    def get_is_post(self):
        """
        修改是否待关账
        将是否待关账修改为True, 关账动作以这个字段为筛选条件
        :return:
        """
        for i in self:
            i.jdg_sudo().write({
                'is_post': True
            })

    @api.multi
    def get_no_post(self):
        """
        是否待关账改为false
        :return:
        """
        for i in self:
            i.jdg_sudo().write({
                'is_post': False
            })
    
    @api.multi
    def do_audit(self):
        """
        增加审核条件:确认、反审核状态单据才可审核。
        Updated By YGJ @2018/5/23
        :return:
        """
        for record in self:
            record.get_is_post()
        super(AbstractBaseBizFinance, self).do_audit()

    @api.multi
    def do_unaudit(self):
        """
        反审核动作，改变单据状态，子类覆盖该方法时注意逻辑
        :return:
        """
        for record in self:
            record.get_no_post()
        super(AbstractBaseBizFinance, self).do_unaudit()

    @api.multi
    def do_cancel(self):
        """
        作废动作，改变单据状态，子类覆盖该方法时注意逻辑
        :return:
        """
        for record in self:
            record.get_no_post()
        return super(AbstractBaseBizFinance, self).do_cancel()

    @api.multi
    def do_post(self):
        """
            关账动作，改变单据状态，子类覆盖该方法时注意逻辑
        :return:
        """
        for record in self:
            if record.is_post:
                record.jdg_sudo().write({
                    'state': 'closed',
                    'uid_post': self.env.user.id,
                    'time_post': fields.Datetime.now()
                })
                record.get_no_post()
            else:
                raise ValidationError('只有待关账的单据才能进行关账操作：%s' % self._description + '-' + record.number)
