# -*- coding: utf-8 -*-
# @File  : balance_sap.py
# Created by cx on 2020/4/15
# xuan.chen@yunside.com

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class BalanceAccountItem(models.Model):
    _name = 'jd.init.balance.account.item'
    _description = u'凭证科目余额表'

    number = fields.Char(string=u'编号', required=True, default='/')
    company_id = fields.Many2one('res.company', string=u'组织', required=True)
    bukrs = fields.Char(string=u'公司代码', required=True)
    prctr = fields.Char(string=u'利润中心', required=True)
    account_item_id = fields.Many2one('jd.int.sap.account.item', string=u'凭证科目', required=True)
    currency_id = fields.Many2one('res.currency', string=u'币种', required=True)
    number_assist = fields.Char(string=u'辅助对象编码')
    assist_account = fields.Char(string=u'辅助核算')
    amount = fields.Float(string=u'余额', required=True, default=0)

    @api.model
    def create(self, values):
        """
        获取自动单号
        :param values:
        :return:
        """
        if values.get('number', '/') == '/':
            company_id = values.get('company_id', self.env.user.company_id.id)
            account_item_id = values.get('account_item_id')
            number_assist = values.get('number_assist', '')
            if company_id and account_item_id:
                cr = self.env.cr
                sql = """
                SELECT ai.number AS number_account
                FROM jd_int_sap_account_item ai
                WHERE ai.id = %(account_item_id)s
                LIMIT 1
                """
                params = {'account_item_id': account_item_id}
                cr.execute(sql, params)
                rec = cr.dictfetchone()
                if rec and rec.get('number_account'):
                    number_account = rec.get('number_account')
                    number = 'BA' + str(company_id) + number_account + number_assist
                    values.update({
                        'number': number
                    })
        return super(BalanceAccountItem, self).create(values)
    
    @api.multi
    def unlink(self):
        force_unlink = self.env.context.get('force_unlink')
        if not force_unlink:
            raise ValidationError(u'不能人工删除凭证科目余额表')

    @api.multi
    @api.depends('company_id', 'account_item_id')
    def name_get(self):
        result = []
        for item in self:
            name = '%s-%s' % (item.company_id.name, item.account_item_id.name)
            result.append((item.id, name))
        return result

    @api.model
    def get_balance(self, company_id, account_item_id, currency_id, number_assist):
        """
        获取最后一条流水的期末余额
        :param company_id:
        :param account_item_id:
        :param currency_id:
        :param number_assist: 辅助核算对象编码
        :return:
        """
        if not isinstance(company_id, int) and hasattr(company_id, 'id'):
            company_id = company_id.id
        if not isinstance(account_item_id, int) and hasattr(account_item_id, 'id'):
            account_item_id = account_item_id.id
        if not isinstance(currency_id, int) and hasattr(currency_id, 'id'):
            currency_id = currency_id.id
        if not number_assist:
            number_assist = ''
        info = {
            'number': '无科目余额',
            'amount': 0
        }
        cr = self.env.cr
        sql = '''
            SELECT
              ai.number              AS number,
              coalesce(ai.amount, 0) AS amount
            FROM jd_init_balance_account_item ai
            WHERE ai.company_id = %(company_id)s
                  AND ai.account_item_id = %(account_item_id)s
                  AND ai.currency_id = %(currency_id)s
                  AND coalesce(ai.number_assist, '') = %(number_assist)s
            ORDER BY ai.id DESC
            LIMIT 1
            '''
        params = {
            'company_id': company_id,
            'account_item_id': account_item_id,
            'currency_id': currency_id,
            'number_assist': number_assist
        }
        cr.execute(sql, params)
        rec = cr.dictfetchone()
        if rec and rec.get('number'):
            info = rec
        return info
