# -*- encoding: utf-8 -*-
# 项目：JDG-
# 模块名称：
# 描述：
# Copyright 2018 JDG <www.yunside.com>
# Created by wxh (xianhuo.weng@yunside.com) at  2019/8/8 - 5:33 PM

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


class TrustRpcSetting(models.Model):
    _name = 'jd.trust.rpc.setting'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'TRUST RPC设置'

    company_id = fields.Many2one('res.company', default=False)
    # name = fields.Char(required=False)
    data_node_id = fields.Many2one('jd.data.node', string=u'当前系统数据节点', readonly=True, required=True)

    accept_line_ids = fields.One2many('jd.trust.rpc.setting.accept.line', 'parent_id', string=u'可接受的节点',
                                      help=u'允许与本系统进行通信的节点列表')
    request_line_ids = fields.One2many('jd.trust.rpc.setting.request.line', 'parent_id', string=u'可请求的节点',
                                       help=u'本系统可进行主动请求的节点列表')

    @api.model
    def default_get(self, fields_list):
        result = super(TrustRpcSetting, self).default_get(fields_list)
        result['data_node_id'] = int(self.get_data_node_id())
        return result

    @api.multi
    @api.depends('data_node_id')
    def name_get(self):
        """
        名称显示格式：[XXX]YYY
        """
        result = []
        for item in self:
            name = u'【%s】TRUST RPC设置' % item.data_node_id.name or u'无'
            result.append((item.id, name))
        return result

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        for item in self:
            item.hide_edit_button = item.state in ('enable', 'discard')

    @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(TrustRpcSetting, self).create(values)

    @api.multi
    @api.constrains('data_node_id')
    def check_company(self):
        """
        一个系统中只会存在一条trust rpc设置
        :return:
        """
        for item in self:
            rec = self.sudo().search([('state', '!=', 'discard'), ('id', '!=', item.id)])
            if rec:
                raise ValidationError(u'已存在非作废状态的【%s】TRUST RPC设置' % item.number)

    @api.model
    def get_trust_rpc_accept(self):
        accept_setting = ''
        rec = self.sudo().search([('state', '=', 'enable')], limit=1, order='write_date desc')
        if rec:
            for line_id in rec.accept_line_ids:
                # trust_rpc登录配置项 (客户端ip,客户端data_node_id,客户端的识别token)
                accept_setting += line_id.ip + ',' + str(line_id.data_node_id.id) + ',' + line_id.token + ';'

        if not accept_setting:
            # 从配置文件中取用
            accept_setting = config.get('trust_rpc_accept_tokens', '')

        return accept_setting

    @api.model
    def get_trust_rpc_request(self):
        request_setting = ''
        rec = self.sudo().search([('state', '=', 'enable')], limit=1, order='write_date desc')
        if rec:
            for line_id in rec.request_line_ids:
                # trust_rpc登录配置项 (客户端可发出请求的ip,客户端可请求data_node_id,客户端token)
                request_setting += line_id.ip + ',' + str(line_id.data_node_id.id) + ',' + line_id.token + ';'

        if not request_setting:
            # 从配置文件中取用
            request_setting = config.get('trust_rpc_request_tokens', '')

        return request_setting


class SettingAcceptLine(models.Model):
    _name = 'jd.trust.rpc.setting.accept.line'
    _description = u'可接受的节点'

    parent_id = fields.Many2one('jd.trust.rpc.setting', string=u'TRUST RPC设置', ondelete='cascade', required=True)
    data_node_id = fields.Many2one('jd.data.node', string=u'客户端数据节点', required=True, help=u'客户端发出请求的数据节点')
    ip = fields.Char(string=u'客户端ip', required=True, help=u'客户端请求发出请求的ip地址')
    token = fields.Char(string=u'客户端token', required=True, help=u'客户端发出请求的token')
    note = fields.Text(string=u'备注')


class SettingRequestLine(models.Model):
    _name = 'jd.trust.rpc.setting.request.line'
    _description = u'可请求的节点'

    parent_id = fields.Many2one('jd.trust.rpc.setting', string=u'TRUST RPC设置', ondelete='cascade', required=True)
    data_node_id = fields.Many2one('jd.data.node', string=u'可请求的数据节点', required=True)
    ip = fields.Char(string=u'可发起请求的ip', required=True)
    token = fields.Char(string=u'请求的token', required=True)
    note = fields.Text(string=u'备注')
