#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD019
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2019/10/9 11:50
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: AliPayObject.py
@Contact: pzb3076@163.com
"""

from django.views.generic.base import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from Service.ModelService import ModelService
from Model.models import User_Brand,Device_User
from django.utils import timezone
import traceback,time,json,urllib.request
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from collections import Counter
from Ansjer.config import DOMAIN_HOST,AWS_DynamoDB_REGION,AWS_DynamoDB_ACCESS_KEY,AWS_DynamoDB_SECRET_KEY
from Object.RedisObject import RedisObject
from Service.MiscellService import MiscellService
import datetime, simplejson as json
import time
'''
http://192.168.136.39:8000/dynamoDBLog/searchByAdmin?search_value=154390905041313800138000&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTQzOTA5MDUwNDEzMTM4MDAxMzgwMDAiLCJsYW5nIjoiY24iLCJ1c2VyIjoiMTM4MDAxMzgwMDEiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1NzMyNjc3OTR9.YWNEHKKrzFfEc4liz6N8ANQl8C1VfhhLv_MEOqf3yV4&page=1&line=12


http://192.168.136.39:8000/dynamoDBLog/connector?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTQzOTA5MDUwNDEzMTM4MDAxMzgwMDAiLCJsYW5nIjoiY24iLCJ1c2VyIjoiMTM4MDAxMzgwMDEiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1NzMyNjc3OTR9.YWNEHKKrzFfEc4liz6N8ANQl8C1VfhhLv_MEOqf3yV4

 '''
class DynamoDBLog(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(DynamoDBLog, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        self.clientIP = CommonService.get_ip_address(request)
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            userID = tko.userID
            if operation == 'searchByAdmin':
                return self.search_info(request_dict, userID, response)
            elif operation == 'connector':
                return self.connector_info(request_dict, userID, response)
            elif operation == 'daySearch':
                return self.get_day_search(request_dict, userID, response)
            else:
                return response.json(444)
        else:
            return response.json(tko.code)

    # 查询搜索表（可以通过用户名，和接口名称，ip地址搜索等）
    def search_info(self, request_dict, userID,response):
        search_value = request_dict.get('search_value',None)
        check_perm = ModelService.check_perm(userID=userID,permID=30)
        if check_perm is True:
            if search_value is None or search_value is '':
                return response.json(0, {'datas': {}, 'count': 0})
            else:
                if DOMAIN_HOST == 'www.dvema.com':
                    user_brand = 'access_log'
                else:
                    user_brand = 'test_access_log'
                # 查询
                user_ID = Device_User.objects.filter(username=search_value).values('userID', 'NickName')
                try:
                    search_value = user_ID[0]['userID']
                except Exception:
                    search_value = search_value
                items = MiscellService.get_item_log( user_brand ,search_value)
                for k, v in enumerate(items):
                    user_ID = Device_User.objects.filter(userID=items[k]['userID']).values('username')
                    try:
                        items[k]['userID'] = user_ID[0]['username']
                    except Exception:
                        items[k]['userID'] = ''
                return response.json(0, {'datas': items, 'count': len(items)})
        else:
            return response.json(404)

    # 查询接口的访问量的对应数量
    def connector_info(self, request_dict, userID,response):
        check_perm = ModelService.check_perm(userID=userID,permID=30)
        if check_perm is True:
            if DOMAIN_HOST == 'www.dvema.com':
                user_brand = 'access_log'
            else:
                user_brand = 'test_access_log'
            table_value = MiscellService.item_get_brand(user_brand)
            send_jsons = []
            counts = 0
            for i in table_value:
                send_jsons.append(table_value[counts]['operation'])
                counts = counts + 1
            send_jsons = Counter(send_jsons)
            return response.json(0, {'datas': send_jsons,'counts':counts})
        else:
            return response.json(404)

    # 通过传过来日期天来搜索，访问量，并返回对应小时的访问数量
    def get_day_search(self, request_dict,userID, response):
        check_perm = ModelService.check_perm(userID=userID, permID=30)
        if DOMAIN_HOST == 'www.dvema.com':
            user_brand = 'access_log'
        else:
            user_brand = 'test_access_log'
        time_stamp = int(request_dict.get('timestamp', None))
        if check_perm is True:
            # 分割小时再去搜索
            times = datetime.datetime.fromtimestamp(time_stamp)
            time_dict = CommonService.getTimeDict(times)
            res = {}
            for k, v in time_dict.items():
                start_date = time_dict[k]
                end_date = time_dict[k] + datetime.timedelta(hours=1)
                start_date = int(start_date.timestamp())
                end_date = int(end_date.timestamp())
                count = MiscellService.get_item_time(user_brand,start_date, end_date)
                if count:
                    res[k] = count
                else:
                    res[k] = 0

            # res = MiscellService.get_item_date(user_brand,time_stamp)
            return response.json(0, {'count': res})
        else:
            return response.json(404)