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

from odoo import models, fields, api
import logging

_logger = logging.getLogger(__name__)


class JdSystemLogAccess(models.Model):
    _name = 'jd.system.log.access'
    _description = u'访问日志'

    user_id = fields.Many2one('res.users', string=u'用户')
    user_login = fields.Char(string=u'账号', compute='_get_user_login')
    time_access = fields.Datetime(string=u'访问时间')
    action_id = fields.Many2one('ir.actions.actions', string=u'访问动作')
    model_id = fields.Many2one('ir.model', string=u'访问单据')

    @api.model
    def do_logging(self, action_id, model_name):
        log_access_on_off = self.env['ir.config_parameter'].jdg_sudo().get_param("log_access_on_off")
        log_access_on_off = str(log_access_on_off) if log_access_on_off else 'off'
        if log_access_on_off == 'on':
            user_id = self.env.user.id
            cr = self.env.cr
            sql = """
              SELECT
                id
              FROM ir_model
              WHERE model = %s
                AND transient = FALSE;
            """
            cr.execute(sql, (model_name, ))
            rec = cr.dictfetchone()
            if rec and rec.get('id'):
                model_id = rec['id']
                sql = """
                  INSERT INTO jd_system_log_access (
                    create_uid, create_date, write_uid, write_date,
                    user_id, time_access, action_id, model_id
                  )
                  VALUES (
                    1, CURRENT_TIMESTAMP AT TIME ZONE 'UTC', 1, CURRENT_TIMESTAMP AT TIME ZONE 'UTC',
                    %s, CURRENT_TIMESTAMP AT TIME ZONE 'UTC', %s, %s
                  );
                """
                cr.execute(sql, (user_id, action_id, model_id, ))
                self.env['jd.system.analysis.biz'].jdg_sudo().add_biz_times(user_id, model_id, 'access')
    
    @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
