#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import time

from django.db.models import Count
from django.views.decorators.csrf import csrf_exempt

from Model.models import UserAppFrequencyModel, AppFrequencyStatisticsModel, Device_User, \
    AppFrequencyYearStatisticsModel, Equipment_Info, EquipmentInfoExStatisticsModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject


@csrf_exempt
def statistcsAppFrequency(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)

    token = TokenObject(request_dict.get('token', None))
    if token.code != 0:
        return response.json(token.code)

    target_year = request_dict.get('year', None)
    target_month = request_dict.get('month', None)

    localtime = time.localtime()
    current_month = localtime.tm_mon
    current_year = localtime.tm_year

    if target_year and target_month:
        current_year = int(target_year)
        current_month = int(target_month)

    time_struct = [current_year, 1, 1, 0, 0, 0, 0, 0, 0]

    distance_time = 8 * 60 * 60

    # 该月的开始时间
    time_struct[1] = current_month
    start_time = time.mktime(tuple(time_struct))
    start_time = start_time - time.timezone - distance_time

    # 该月的结束时间
    time_struct[1] = current_month + 1
    end_time = time.mktime(tuple(time_struct))
    end_time = end_time - time.timezone - distance_time

    # 统计该月的数据
    uaf_qs = UserAppFrequencyModel.objects.filter(data_time__gte=start_time, data_time__lt=end_time) \
        .values('type').annotate(quantity=Count('id')).order_by()

    afs_qs = AppFrequencyStatisticsModel.objects.filter(year=current_year, month=current_month)

    if afs_qs.exists():
        afs_qs.update(data=json.dumps(uaf_qs))
    else:
        data = {
            'data': json.dumps(list(uaf_qs)),
            'month': current_month,
            'year': current_year
        }
        AppFrequencyStatisticsModel.objects.create(**data)
    return response.json(0)


@csrf_exempt
def statistcsAppFrequencyYear(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)

    token = TokenObject(request_dict.get('token', None))
    if token.code != 0:
        return response.json(token.code)

    year = request_dict.get('year', None)

    localtime = time.localtime()

    current_year = localtime.tm_year
    if year:
        current_year = int(year)

    afs_qs = AppFrequencyStatisticsModel.objects.filter(year=current_year).values('data', 'month')
    # num = Device_User.objects.count()
    num = 300000

    res = []
    result = {
        0: 0,
        1: 0,
        2: 0,
        3: 0,
        4: 0,
        5: 0,
        6: 0
    }
    quantity = 0
    for afs in afs_qs:
        data = json.loads(afs['data'])
        for item in data:
            result[item['type']] += item['quantity']
            quantity += item['quantity']

    tmps = []
    for k, v in result.items():
        tmp = {
            'type': k,
            'value': round(v / 12 / num, 3)
        }
        tmps.append(tmp)
    res.append({
        'year': current_year,
        'data': tmps
    })
    print(res)

    afys_qs = AppFrequencyYearStatisticsModel.objects.filter(year=current_year)
    #
    if afys_qs.exists():
        afys_qs.update(data=json.dumps(res))
    else:
        data = {
            'data': json.dumps(res),
            'year': current_year,
            'num': num
        }
        AppFrequencyYearStatisticsModel.objects.create(**data)
    return response.json(0)


@csrf_exempt
def statistcsPushDay(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)

    token = TokenObject(request_dict.get('token', None))
    if token.code != 0:
        return response.json(token.code)

    current_time = int(time.time())
    count = int((current_time + 8 * 3600) / (24 * 3600))
    end_time = count * 24 * 3600 - 8 * 3600
    start_time = end_time - 24 * 3600
    print(start_time)
    print(end_time)

    eq_qs = Equipment_Info.objects.filter(addTime__gte=start_time, addTime__lte=end_time)
    print(eq_qs.values())
    # 0：APNS推送，1：谷歌推送，2：极光推送
    now_time = int(time.time())
    jpush = EquipmentInfoExStatisticsModel(push_type=2, statistics_date=start_time, add_time=now_time, date_type=0)
    apns = EquipmentInfoExStatisticsModel(push_type=0, statistics_date=start_time, add_time=now_time, date_type=0)
    gcm = EquipmentInfoExStatisticsModel(push_type=1, statistics_date=start_time, add_time=now_time, date_type=0)
    total = EquipmentInfoExStatisticsModel(push_type=-1, statistics_date=start_time, add_time=now_time, date_type=0)
    for eq in eq_qs:
        if eq.push_type == 0:
            do_sum(eq, apns)
        elif eq.push_type == 1:
            do_sum(eq, gcm)
        elif eq.push_type == 2:
            do_sum(eq, jpush)
        do_sum(eq, total)
    datas = []
    datas.append(apns)
    datas.append(gcm)
    datas.append(jpush)
    datas.append(total)

    EquipmentInfoExStatisticsModel.objects.bulk_create(datas)
    return response.json(0)


@csrf_exempt
def statistcsPushMonth(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)

    token = TokenObject(request_dict.get('token', None))
    if token.code != 0:
        return response.json(token.code)

    gmtime = time.gmtime(int(time.time()) + 28800)
    current_month = gmtime.tm_mon - 1
    # print(current_month)

    time_struct = [gmtime.tm_year, current_month, 1, 0, 0, 0, 0, 0, gmtime.tm_isdst]
    start_time = int(time.mktime(tuple(time_struct))) - 28800
    # print(start_time)

    time_struct[1] = current_month + 1
    end_time = int(time.mktime(tuple(time_struct))) - 28800
    # print(end_time)

    eq_qs = EquipmentInfoExStatisticsModel.objects.filter(statistics_date__gte=start_time, statistics_date__lte=end_time, date_type=0)
    # 0：APNS推送，1：谷歌推送，2：极光推送
    now_time = int(time.time())
    jpush = EquipmentInfoExStatisticsModel(push_type=2, statistics_date=start_time, add_time=now_time, date_type=1)
    apns = EquipmentInfoExStatisticsModel(push_type=0, statistics_date=start_time, add_time=now_time, date_type=1)
    gcm = EquipmentInfoExStatisticsModel(push_type=1, statistics_date=start_time, add_time=now_time, date_type=1)
    total = EquipmentInfoExStatisticsModel(push_type=-1, statistics_date=start_time, add_time=now_time, date_type=1)
    for eq in eq_qs:
        if eq.push_type == 0:
            do_sum_two(eq, apns)
        elif eq.push_type == 1:
            do_sum_two(eq, gcm)
        elif eq.push_type == 2:
            do_sum_two(eq, jpush)
        elif eq.push_type == -1:
            do_sum_two(eq, total)
    datas = []
    datas.append(apns)
    datas.append(gcm)
    datas.append(jpush)
    datas.append(total)

    EquipmentInfoExStatisticsModel.objects.bulk_create(datas)
    return response.json(0)


def do_sum(eq: Equipment_Info, target: EquipmentInfoExStatisticsModel):
    if eq.push_server_status == 200:
        target.number_of_successes += 1
    else:
        target.number_of_failures += 1

    if eq.push_device_status == 1:
        target.number_of_arrival += 1


def do_sum_two(eq: EquipmentInfoExStatisticsModel, target: EquipmentInfoExStatisticsModel):
    target.number_of_successes += eq.number_of_successes
    target.number_of_failures += eq.number_of_failures
    target.number_of_arrival += eq.number_of_arrival
