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

import logging
from odoo import models, api, SUPERUSER_ID, fields, _
from passlib.context import CryptContext

_logger = logging.getLogger(__name__)


class ResUsersRecentCompany(models.Model):
    _name = "jd.res.users.recent.company"
    """
    记录用户最近访问的组织
    """
    
    recent_company_id = fields.Many2one('res.company', string=u'组织')
    user_id = fields.Many2one('res.users', string=u'用户')

    @api.model
    def get_recent_companys(self, user_id):
        """
        获取用户最近访问的5个组织
        :param user_id
        :return:
        """
        recs = self.sudo().search([('user_id', '=', user_id)], limit=5, order='create_date desc')
        companys = []
        for rec in recs:
            companys.append(rec.recent_company_id.name)
        companys = list(set(companys))
        return companys


class JdResUsers(models.Model):
    _inherit = "res.users"
    """
    记录用户最近访问的组织
    """

    @api.multi
    def write(self, vals):
        before_company_id, after_company_id = None, None
        for item in self:
            before_company_id = item.company_id.id
        result = super(JdResUsers, self).write(vals)
        for item in self:
            after_company_id = item.company_id.id
        if before_company_id != after_company_id:
            company_id = item.company_id.id
            user_id = item.id
            recent_vals = {
                'recent_company_id': company_id,
                'user_id': user_id
            }
            self.env['jd.res.users.recent.company'].sudo().create(recent_vals)
        return result
