# -*- coding: utf-8 -*-
# 项目: jdg-core-base
# Copyright 2018 JDG <www.yunside.com>
# Created by bjccdsrlcr <longjie.jiang@yunside.com> at 2019/12/30

"""
sap 推送记录
"""

from odoo import models, fields, api, exceptions
import logging
from odoo.exceptions import ValidationError
from suds.client import Client
import simplejson
import json

_logger = logging.getLogger(__name__)


class SAPRecord(models.Model):
    """
    SAP推送记录；
    1. 提供请求接口
    2. 提供撤销接口
    3. 提供回调接口
    对正在发起请求的业务单据锁止操作（写、删除）

    """
    _name = 'jd.int.sap.record'
    _description = u'SAP推送记录'

    number = fields.Char(string=u'编码', readonly=True, help=u'SAP系统返回的付款流水号')
    date = fields.Datetime(string=u'日期', default=fields.Date.context_today)
    uid_push = fields.Many2one('res.users', string=u'推送人')
    state = fields.Selection([('valid', u'生效'),
                              ('done', u'已完成'),
                              ('refused', u'已拒绝'),
                              ('invalid', u'失效')], string=u'状态', required=True, default='valid')
    note = fields.Text(string=u'备注')
    res_order = fields.Reference(string=u'来源单据', selection='_reference_models', readonly=True)

    @api.model
    def check_exit(self, origin_rec):
        """
        检查来源单据是否有正在推送的sap记录。
        Created By YGJ.
        :param origin_rec: 拼接格式为 '模型名,记录id'  如：'model.biz.order,id'
        :return:
        """
        pass

    @api.multi
    def do_done(self):
        """
        状态由生效转变为已完成
        :return:
        """
        for record in self:
            if record.state == 'valid':
                return record.write({
                    'state': 'done'
                })
            else:
                raise ValidationError('只有生效的记录才可以完成')

    @api.multi
    def do_refused(self):
        """
        状态由生效转变为已拒绝
        :return:
        """
        for record in self:
            if record.state == 'valid':
                return record.write({
                    'state': 'refused'
                })
            else:
                raise ValidationError('只有生效的记录才可以拒绝')

    @api.model
    def _reference_models(self):
        models = self.env['ir.model'].search([('state', '!=', 'manual')])
        return [(model.model, model.name)
                for model in models
                if not model.model.startswith('ir.')]

    def get_sap_config(self):
        """
        下游实现
        从接口配置模型下获取sap连接配置
        :return: data
        """
        pass

    def do_sap_post(self):
        """
        下游实现
        推送sap
        :return:
        """

    def do_callback(self, data):
        """
        下游实现
        sap回调接口
        :return:
        """
        pass