# -*- 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

from odoo.exceptions import Warning

import logging

_logger = logging.getLogger(__name__)


class Voucher(models.Model):
    """
    凭证定义
    凭证定义的每一条记录定义一类需要推送的凭证
    主要数据是定义的来源单据模型以及输入输出参数
    """
    _name = 'jd.int.voucher'
    _description = u'凭证定义'

    name = fields.Char(string=u'名称', required=True)
    number = fields.Char(string=u'编码', readonly=True, default='/', required=True)
    category_id = fields.Many2one('jd.int.voucher.category', string=u'凭证分类')
    type_id = fields.Many2one('jd.int.voucher.type', string=u'类型', required=True)
    config_id = fields.Many2one('jd.int.config', string=u'推送通道', required=True,
                                domain=[('active', '=', True)])
    description = fields.Char(string=u'业务描述')
    res_model = fields.Char(string=u'来源单据模型')
    is_gather = fields.Boolean(string=u'是否汇总凭证', default=False)
    active = fields.Boolean(string=u'有效', default=True)
    input_param = fields.Text(string=u'凭证主表动态参数')
    output_param = fields.Text(string=u'输出参数')
    note = fields.Text(string=u'备注')
    line_ids = fields.One2many('jd.int.voucher.line', 'voucher_id', string=u'凭证定义明细')

    _sql_constraints = [
        ('type_res_model_uniq', 'unique (type_id, res_model)', u'该类型与来源单据模型已有凭证定义！')
    ]

    @api.multi
    def search_voucher(self, res_model, type_name):
        """
        根据传入的type_name,查询type_id
        根据type_id与传入的res_model,返回凭证设置记录
        :param res_model: {type: string} 来源模型
        :param type_name: {type: string} 凭证类型名称
        :return:
        """
        voucher_type_rec = self.env['jd.int.voucher.type'].sudo().search([('name', '=', type_name),
                                                                    ('active', '=', True)], limit=1)
        if len(voucher_type_rec) == 0:
            raise Warning('没有找到名称为"[%s]"的有效凭证类型记录' % type_name)
        voucher_rec = self.sudo().search([('res_model', '=', res_model),
                                   ('type_id', '=', voucher_type_rec.id),
                                   ('active', '=', True)], limit=1)
        if len(voucher_rec) == 0:
            raise Warning('没有找到符合条件的有效凭证设置记录：来源模型为[%s],凭证类型为[%s]' % (res_model, type_name))
        return voucher_rec

    @api.model
    def create(self, values):
        """
        获取自动单号
        :param values:
        :return:
        """
        if values.get('number', '/') == '/':
            values.update({
                'number': self.env['ir.sequence'].next_by_code(self._name)
            })
        return super(Voucher, self).create(values)


class VoucherLine(models.Model):
    """
    凭证定义凭证行明细
    SAP凭证推送时需要两个参数，相当于一个主表与多条明细，明细至少需要两行
    """
    _name = 'jd.int.voucher.line'
    _description = u'凭证定义凭证明细行明细'

    voucher_id = fields.Many2one('jd.int.voucher', string=u'凭证定义', ondelete='cascade')
    group = fields.Integer(string=u'组号', required=True)
    sap_subject_id = fields.Many2one('jd.int.sap.account.item', string=u'科目', required=True)
    input_param = fields.Text(string=u'明细行动态参数')
