# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by HJH <jiahao.huang@yunside.com> at 2022/05/30

from odoo import models, fields, api, tools
import logging

_logger = logging.getLogger(__name__)


class StatJdSystemAnalysisLogin(models.Model):
    _name = 'stat.jd.system.analysis.login'
    _description = u'用户登录行为多维分析'
    _auto = False
    _table = 'stat_jd_system_analysis_login'
    _order = 'user_id'

    user_id = fields.Many2one('res.users', string=u'操作用户')
    region = fields.Char(string=u'地区')
    hour_login = fields.Char(string=u'登录时段')
    times_login_success = fields.Integer(string=u'登录成功次数')
    times_login_fail = fields.Integer(string=u'登录失败次数')

    @api.model
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        return super(StatJdSystemAnalysisLogin, self.with_context(virtual_id=False)).read_group(domain, fields, groupby, offset=offset, limit=limit, lazy=lazy)

    @api.model_cr
    def init(self):
        tools.drop_view_if_exists(self._cr, 'stat_jd_system_analysis_login')
        self.reset_view()

    @api.model_cr
    def reset_view(self):
        sql = '''
          CREATE OR REPLACE VIEW stat_jd_system_analysis_login AS (
            SELECT
              row_number() OVER() AS id,
              log.user_id,
              log.region,
              log.hour_login,
              log.times_login_success,
              log.times_login_fail
            FROM jd_system_analysis_login log
          );
        '''
        self._cr.execute(sql)



