# -*- coding: utf-8 -*-
# 项目: jdg-hd-node-farm
# Copyright 2018 JDG <www.yunside.com>
# Created by LLH <lianghua.liu@yunside.com> at 2019/1/25

from odoo import models, fields, api

from odoo.exceptions import ValidationError

import logging

_logger = logging.getLogger(__name__)


class JdReportLog(models.Model):
    """
    报表使用监控记录
    提供创建监控记录的接口，各报表各自调用，监控各报表查询人与查询时间
    """
    _name = 'jd.report.log'
    _inherit = 'jdg.abstract.core'
    _description = u'报表使用监控记录'
    _seq_prefix = 'RL'
    _order = 'id desc'

    # module = fields.Selection(lambda self: self._get_module_selection, string=u'模块')
    number = fields.Char(string=u'编码', required=True, default='/')
    module_id = fields.Many2one('ir.module.module', string=u'模块')
    report_name = fields.Char(string=u'报表名称', required=True)
    biz_uid = fields.Many2one('res.users', string=u'查询用户', required=True)
    biz_time = fields.Datetime(string=u'查询时间', required=True, default=fields.Datetime.now())

    @api.model
    def create(self, vals):
        vals = vals or {}
        if vals.get('number', '/') == '/':
            vals.update({'number': self.env['ir.sequence'].sudo().next_by_code(self._name)})
        return super(JdReportLog, self).create(vals)

    @api.model
    def _get_module_selection(self):
        """
        获取ir_module_module
        拼成data_list
        :return:
        """
        module_list = []
        module_recs = self.env['ir.module.module'].sudo().search([])
        for rec in module_recs:
            module_list.append((rec.name, rec.summary))
        return module_list

    @api.model
    def make_history(self, report_name, biz_user_id=None, module_name=None):
        """
        创建报表使用记录
        :param report_name:
        :param biz_user_id:
        :param module_name:
        :return:
        """
        if not report_name:
            raise ValidationError(u'报表名称未传入，不能生成报表使用记录')
        if not biz_user_id:
            biz_user_id = self.env.user.id
        module_id = None
        if module_name:
            module_id = self.env['ir.module.module'].sudo().search([('name', '=', module_name)], limit=1).id
        history_vals = {
            'module_id': module_id,
            'report_name': report_name,
            'biz_uid': biz_user_id,
            'biz_time': fields.Datetime.now()
        }
        self.env['jd.report.log'].sudo().create(history_vals)



