# -*- coding: utf-8 -*-
# 项目: jdg-core-base
# Copyright 2018 JDG <www.yunside.com>
# Created by HJH <jiahao.huang@yunside.com> at 2022/05/12

from odoo import models, fields, api
import logging

_logger = logging.getLogger(__name__)

RESULT = [
    ('success', u'登录成功'),
    ('fail', u'登录失败')
]


class JdSystemLogLogin(models.Model):
    _name = 'jd.system.log.login'
    _description = u'系统登录日志'

    user_id = fields.Many2one('res.users', string=u'登录用户')
    user_login = fields.Char(string=u'登录账号', compute='_get_user_login')
    time_login = fields.Datetime(string=u'登录时间')
    result = fields.Selection(RESULT, string=u'登录结果')
    ip = fields.Char(string=u'登录ip')
    country = fields.Char(string=u'国家')
    city = fields.Char(string=u'城市')

    @api.model
    def do_logging(self, user_id, result, ip, country, city):
        cr = self.env.cr
        sql = """
          INSERT INTO jd_system_log_login (
            create_uid, create_date, write_uid, write_date,
            user_id, time_login, result, ip, country, city
          )
          VALUES (
            1, CURRENT_TIMESTAMP AT TIME ZONE 'UTC', 1, CURRENT_TIMESTAMP AT TIME ZONE 'UTC',
            %s, CURRENT_TIMESTAMP AT TIME ZONE 'UTC', %s, %s, %s, %s
          );
        """
        cr.execute(sql, (user_id, result, ip, country, city, ))
        self.env['jd.system.analysis.login'].jdg_sudo().add_login_times(user_id, country, city, result)
    
    @api.multi
    @api.depends('user_id')
    def _get_user_login(self):
        for item in self:
            if item.user_id and item.user_id.login:
                item.user_login = item.user_id.login
