# coding=utf-8
"""
 @Author: fu-zhe
 @FileName: dashboard_views.py
 @DateTime: 2024/5/20 17:34
 @Description: 
"""

import json,os
import traceback,time,codecs

from rest_framework import viewsets
from rest_framework.decorators import list_route, detail_route
from uebaMetricsAnalysis.utils.ext_logging import logger,logger_audit
from uebaMetricsAnalysis.lib.result import Result
from uebaMetricsAnalysis.utils import config
from uebaMetricsAnalysis.utils.dashboard_data_pg import entry
from uebaMetricsAnalysis.utils.dashboard_detail_data import detail_data_entry
from uebaMetricsAnalysis.utils.dashboard_summary_data import summary_data_entry

class DashboardViewSets(viewsets.GenericViewSet):
    # #写入大文件5M
    # def write_large_file(self,filename, data_list, chunk_size=1024*1024*5):
    #     with codecs.open(filename, 'w', encoding='utf-8') as f:
    #         for i in range(0, len(data_list), chunk_size):
    #             chunk = data_list[i:i + chunk_size]
    #             f.write(chunk)
    @list_route(methods=['GET'])
    def get_summary_data_list(self,request):
        try:
            data_type = request.GET.get('type')
            startTime =request.GET.get('startDate')
            endTime = request.GET.get('endDate')
            #1:ip,2:账号,3:接口,4:菜单
            logger.info("获取分析结构数据:"+data_type+";" + startTime +";"+ endTime) 
            return Result.ok(entry(data_type,startTime,endTime))
        except Exception, e:
            logger.error(traceback.format_exc())
            return Result.failed("查询失败", str(e))
    
    @list_route(methods=['POST'])
    def write_audit_log(self, request):
        try:
            body = json.loads(request.body)
            action =body.get("action")
            username = request.session.get('username',"unknown user")
            params = body.get("params")
            logger_audit.info("Audit_Log:"+username+","+action +",params:"+json.dumps(params))
        except Exception, e:
            logger_audit.info("Audit_Log:{}, err: {}, traceback: {}".format(username, str(e), traceback.format_exc()))
        return Result.ok("ok")

    @list_route(methods=['GET'])
    def get_default_rule(self,request):
        conf_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'conf')
        jsonfile_path = os.path.join(conf_path, 'defaultRule.json')
        rule_data = config.read_json_config(jsonfile_path)
        return Result.ok(rule_data)
    #获取主页面数据
    @list_route(methods=['GET'])
    def get_summary_data(self,request):
        try:
            data_type = request.GET.get('type')
            startTime =request.GET.get('startDate')
            endTime = request.GET.get('endDate')
            #1:ip,2:账号,3:接口,4:菜单
            logger.info("获取汇总数据:"+data_type+";" + startTime +";"+ endTime) 
            return Result.ok(summary_data_entry(startTime,endTime,data_type))
        except Exception, e:
            logger.error(traceback.format_exc())
            return Result.failed("查询失败", str(e))
        
    #获取明细页面数据
    @list_route(methods=['GET'])
    def get_detail_data(self,request):
        try:
            data_type = request.GET.get('type')
            startTime =request.GET.get('startDate')
            endTime = request.GET.get('endDate')
            keyWord = request.GET.get('keyWord')
            #1:ip,2:账号,3:接口,4:菜单
            logger.info("获取明细数据:"+data_type+";" + startTime +";"+ endTime+";"+keyWord)
            return Result.ok(detail_data_entry(startTime,endTime,data_type,keyWord))
        except Exception, e:
            logger.error(traceback.format_exc())
            return Result.failed("查询失败", str(e))

     #获取允许查询的最大天数
    @list_route(methods=['GET'])
    def get_search_limit(self,request):
        conf_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'conf')
        jsonfile_path = os.path.join(conf_path, 'sys_config.json')
        rule_data = config.read_json_config(jsonfile_path)
        return Result.ok(rule_data)

# if __name__ == '__main__':
#     get_summary_data_list