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

from odoo import models, fields, api

from odoo.exceptions import Warning, ValidationError, MissingError

from odoo import tools

import hashlib
from core.middleware.utils import random_num_get

import logging

_logger = logging.getLogger(__name__)


class OutSystemUser(models.Model):
    """
    维护外部系统对接业务系统时用来登陆的账号密码
    该账号密码登陆gateway，启用时需要创建并下发终端代理用户
    """
    _inherit = 'jdg.abstract.base'
    _name = 'jd.int.out.system.user'
    _description = u'外部系统回调用户'

    system_type = fields.Selection([
        ('bpm', 'BPM'),
        ('fssc', 'FSSC')
    ], string=u'系统类型', required=True, default='bpm')
    number = fields.Char(string=u'用户编码', required=True)
    login = fields.Char(string=u'登录名', required=True)
    password = fields.Char(string=u'密码', required=True)
    state = fields.Selection([('draft', u'草稿'),
                              ('enable', u'启用'),
                              ('disable', u'停用')], string=u'状态', required=True, default='draft')
    note = fields.Text(string=u'备注')

    time_enable = fields.Datetime(string=u'启用时间', readonly=True, help=u'由启用动作自动反写')
    time_disable = fields.Datetime(string=u'停用时间', readonly=True, help=u'由停用动作自动反写')

    uid_enable = fields.Many2one('res.users', string='启用者', readonly=True, help=u'由启用动作自动反写')
    uid_disable = fields.Many2one('res.users', string='停用者', readonly=True, help=u'由停用动作自动反写')

    SALT = '%g%d%j'

    _sql_constraints = [
        ('login_uniq', 'unique (login)', u'登录名不能重复！'),
        ('number_uniq', 'unique (number)', u'用户编码不能重复！')
    ]

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

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        """
        编辑按钮可见性：根据状态控制编辑按钮可见性。子类中可以覆盖该方法添加更详细的控制条件。
        :return:
        """
        for each in self:
            if each.state == 'draft':
                each.hide_edit_button = False
            elif each.state in ['enable', 'disable', 'discard']:
                each.hide_edit_button = True

    @api.multi
    def do_enable(self):
        """
        启用
        启用前校验，对同一个系统类型只能存在一条生效外部系统回调用户
        :return:
        """
        for i in self:
            if i.state not in ('draft', 'disable'):
                raise ValidationError('只有草稿与停用状态下的数据才能启用')
            # user_rec = self.search([('system_type', '=', i.system_type),
            #                         ('state', '=', 'valid')])
            # if len(user_rec) > 0:
            #     raise Warning(u'该系统类型已有启用中的用户记录')
            # if i.system_type == 'bpm':
            #     sys_user = self.env.ref('hd_menu.res_user_proxy_system_bpm')
            #     partner_type = 'bpm'
            # else:
            #     sys_user = self.env.ref('hd_menu.res_user_proxy_system_fssc')
            #     partner_type = 'fssc'
            # partner_id = sys_user.partner_id.id
            # partner_number = i.number
            #
            # proxy_user = self.env['jd.proxy.user'].search([('partner_id', '=', partner_id)], limit=1)
            #
            # # 代理用户存在时，更新其状态
            # if len(proxy_user) > 0:
            #     proxy_user.write({
            #         'state': 'enable',
            #         'uid_enable': self.env.user.id,
            #         'time_enable': fields.Datetime.now()
            #     })
            #
            # # 代理用户不存在时，则新建
            # else:
            #     data_node_id = self.env['ir.config_parameter'].sudo().get_param('jadedragon.microapp.data.node.id')
            #     if not data_node_id:
            #         raise MissingError(u'当前系统丢失节点id信息，启用失败')
            #     data_node_id = int(data_node_id)
            #
            #     remote_data_node = self.env['rm.jd.data.node'].browse(data_node_id)
            #     if not remote_data_node:
            #         raise MissingError(u'网关未能找到对应的节点')
            #
            #     db_name = tools.config.get('db_name', None)
            #     if not db_name:
            #         raise MissingError(u'缺失数据库名称配置项，启用失败')
            #
            #     proxy_user = self.env['jd.proxy.user'].create({
            #         'name': i.system_type + i.number,
            #         'partner_id': partner_id,
            #         'user_id': sys_user.id,
            #         'login': hashlib.md5(self.SALT + partner_type + partner_number).hexdigest(),
            #         'password': hashlib.md5(self.SALT + 'psd' + partner_type + partner_number).hexdigest()
            #     })
            #
            #     # 创建网关登陆用户
            #     user_val = {
            #         'name': i.system_type + i.number,
            #         'login': i.login,
            #         'password': i.password
            #     }
            #
            #     # 创建白名单记录
            #     self.env['jd.terminal.white.list'].create({
            #         'name': i.system_type + i.login,
            #         'proxy_user_id': proxy_user.id
            #     })
            #
            #     # 网关用户与数据节点关联记录
            #     self.env['hd.gw.user.node'].sudo().create_user_node_ref(user_val, {
            #         'name': remote_data_node[0].name + '-' + i.system_type + i.number,
            #         'data_node_id': remote_data_node[0].id,
            #         'db_name': db_name,
            #         'remote_partner_number': partner_number,
            #         'remote_partner_type': partner_type,
            #         'remote_model': i._name
            #     })

            i.write({
                'state': 'enable',
                'uid_enable': self.env.user.id,
                'time_enable': fields.Datetime.now()
            })

    @api.multi
    def do_disable(self):
        """
        停用数据，修改数据状态，当有业务逻辑需要添加在子类中覆盖该方法时注意逻辑完整
        同时修改代理用户
        :return:
        """
        for record in self:
            if record.state == 'enable':
                record.write({
                    'state': 'disable',
                    'uid_disable': self.env.user.id,
                    'time_disable': fields.Datetime.now()
                })
            else:
                raise ValidationError('只有启用状态下的数据才能停用')
