# -*- encoding: utf-8 -*-
# 项目：JDG-
# Copyright 2018 JDG <www.yunside.com>
# Created by wxh (xianhuo.weng@yunside.com) at
from odoo import fields, api, models, SUPERUSER_ID
from odoo.exceptions import AccessDenied
from passlib.context import CryptContext

from odoo.http import request
import logging

_logger = logging.getLogger(__name__)

default_crypt_context = CryptContext(
    ['pbkdf2_sha512', 'md5_crypt'],
    deprecated=['md5_crypt'],
)


class ProxyUser(models.Model):
    _name = 'jd.proxy.user'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'代理用户'

    number = fields.Char(u'编码', readonly=True, default='/')
    user_id = fields.Many2one('res.users', u'用户', help=u'对应的内部系统账号', required=True)
    partner_id = fields.Many2one('res.partner', u'伙伴', help=u'节点中对应的实体', required=True)
    login = fields.Char(u'用户名', required=True)
    password = fields.Char(u'密码', default='', help=u'用在form视图编辑的时候临时保存密码')
    crypt_password = fields.Char(u'加密密码', default='', compute='_get_crypt_password',
                                 invisible=True, store=True, help=u'经过加密的密码')
    device_ids = fields.One2many('jd.terminal.trusted.device', 'proxy_user_id', u'授信设备')
    company_id = fields.Many2one('res.company', string=u'公司', index=True, required=True,
                                 default=lambda self: self.env.user.company_id.id)

    # 每个代理用户只对应一个login，否则无法识别当前登录时哪个partner
    # 一个partner_id只能对应一个user_id
    _sql_constraints = [
        ('login_uniq', 'unique (login)', u'用户名已存在，请更换'),
        ('partner_uniq', 'unique (partner_id)', u'已经存在，不可重复设置')
    ]

    @api.model
    def create(self, values):
        values.update({'number': self.env['ir.sequence'].next_by_code(self._name)})
        record = super(ProxyUser, self).create(values)
        # 清空明文密码
        self.env.cr.execute(
            "UPDATE jd_proxy_user SET password=%s WHERE id=%s",
            ('', record.id)
        )
        return record

    @api.multi
    @api.depends('password')
    def _get_crypt_password(self):
        self.ensure_one()
        record = self[0]
        password = record.password
        record.crypt_password = default_crypt_context.encrypt(password)
        # 清空明文密码
        self.env.cr.execute(
            "UPDATE jd_proxy_user SET password=%s WHERE id=%s",
            ('', record.id)
        )

    def init(self):
        _logger.info("Hashing passwords, may be slow for databases with many users...")
        self.env.cr.execute("SELECT id, password FROM jd_proxy_user"
                   " WHERE password IS NOT NULL"
                   "   AND password != ''")
        for uid, pwd in self.env.cr.fetchall():
            self.sudo().browse(uid)._get_crypt_password()