# -*- 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 suds.client import Client
from suds.transport.http import HttpAuthenticated

import urllib2

import logging

_logger = logging.getLogger(__name__)


class Config(models.Model):
    """
    异构系统集成推送配置
    """
    _name = 'jd.int.config'
    _description = u'系统集成推送配置'

    system_type = fields.Selection([
        ('sap', 'SAP'),
        ('bpm', 'BPM'),
        ('fssc', 'FSSC')
    ], string=u'推送系统', required=True, default='sap', help=u'不同的推送系统可能会对应不同的推送逻辑')
    wsdl_link = fields.Char(string=u'wsdl地址', required=True)
    link = fields.Char(string=u'地址', required=True)
    login = fields.Char(string=u'账号', required=True)
    password = fields.Char(string=u'密码', required=True)
    active = fields.Boolean(string=u'有效', default=True)
    type = fields.Selection([('push', u'推送'),
                             ('revoke', u'撤销')], string=u'类型', required=True, default='push')
    note = fields.Text(string=u'备注')

    _sql_constraints = [
        ('system_type_uniq', 'unique (system_type, type)', u'该推送系统与类型已有推送接口配置！')
    ]

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

    def set_false_null(self, data):
        """
        当字段值在数据库中为空时，在Odoo中的表现为false
        需要将该false处理为null
        :param data:
        :return:
        """
        if isinstance(data, bool):
            return ''
        else:
            return data

    @api.multi
    def get_client(self):
        """
        获取sap_client
        SAP凭证推送与撤销逻辑可复用
        :return:
        """

        self.ensure_one()

        # 取wsdl地址、推送地址、用户名与密码
        url, url_push, username, pwd = self.wsdl_link, self.link, self.login, self.password

        # 校验身份
        t = HttpAuthenticated(username=username, password=pwd)
        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, url, username, pwd)
        t.handler = urllib2.HTTPBasicAuthHandler(passman)
        t.urlopener = urllib2.build_opener(t.handler)
        client = Client(url, location=url_push, transport=t)
        return client
