# -*- coding: utf-8 -*-
# 项目: jdg-hd-node-farm
# Copyright 2018 JDG <www.yunside.com>
# Created by LLH <lianghua.liu@yunside.com> at 2018/8/9

from odoo import models, fields, api

import logging

_logger = logging.getLogger(__name__)


class SapAccountItem(models.Model):
    """
    SAP 凭证科目表
    """
    _name = 'jd.int.sap.account.item'
    _description = u'凭证科目表'
    _rec_name = 'number'

    jdg_number = fields.Char(string=u'玉龙科目', required=True)
    number = fields.Char(string=u'总账科目', required=True)
    name = fields.Char(string=u'总账科目长文本', required=True)
    active = fields.Boolean(string=u'有效', default=True)
    note = fields.Text(string=u'备注')

    _sql_constraints = [
        ('name_uniq', 'unique (name)', u'总账科目长文本不能重复'),
        ('number_uniq', 'unique (number)', u'总账科目不能重复'),
    ]

    @api.multi
    def name_get(self):
        result = []
        for o in self:
            result.append((o.id, "%s(%s)" % (o.number, o.name)))
        return result

    @api.model
    def search_account_item(self, number):
        if not number:
            return None
        cr = self.env.cr
        sql = """
            SELECT a.id
            FROM jd_int_sap_account_item a
            WHERE a.number = %(number)s
            ORDER BY a.id DESC
            LIMIT 1
            """
        params = {
            'number': str(number)
        }
        cr.execute(sql, params)
        rec = cr.dictfetchone()
        if rec and rec.get('id'):
            return rec.get('id')
        else:
            return None
