# -*- coding: utf-8 -*-
"""
@Time ： 2021/1/8 12:00
@Auth ： liehaoquan
@File ：Cloudsum.py
@IDE ：PyCharm
"""
import json

from Ansjer.config import SERVER_TYPE
from Model.models import Order_Model, UID_Bucket, UserExModel, EquipmentLogModel
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from django.views import View

from Service.CommonService import CommonService
from Service.ModelService import Device_User, ModelService
from django.db.models import Count, Sum


class Cloudsum(View):
    def dispatch(self, requset, *args, **kwargs):
        return super(Cloudsum, self).dispatch(requset, *args, **kwargs)

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

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

    def validation(self, request_dict, request, operation):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        response.lang = tko.lang
        userID = tko.userID
        print('userID:', userID)
        if tko.code != 0:
            return response.json(tko.code)
        if userID is None or operation is None:
            return response.json(444, 'operation')
        if operation == 'cloudservicesum':
            return self.cloudservicesum(userID, response)
        if operation == 'userappversion':
            return self.userappversion(userID, response)
        if operation == 'usercount':
            return self.usercount(userID, request_dict, response)
        if operation == 'usercloud':
            return self.usercloud(userID, response)
        if operation == 'equipment_logs':
            return self.equipment_logs(userID, request_dict, response)

    # 类型：用户手机
    # 统计用户手机型号  已有
    # 统计某段时间内新用户的增长数√
    # 统计一天用户打开zosi app的频率   已有
    # 统计用户下载zosi app数，卸载人数
    # 统计用户使用zosi app的版本√

    # 统计用户使用zosi app的版本以及使用zosi app不同版本的用户数量
    def userappversion(self, userID, response):
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)
        res = UserExModel.objects.extra(tables=['app_info'],
                                        select={'appname': 'app_info.appName',
                                                'appversion': 'app_info.newAppversion'},
                                        where=["user_ex.appBundleId=app_info.appBundleId"]). \
            values('appBundleId', 'appname', 'appversion').annotate(dates=Count('appBundleId')).order_by()
        print(res.query)
        print(res)
        return response.json(0, list(res))

    # 统计某段时间内新用户的增长数
    def usercount(self, userID, request_dict, response):
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)

        # 优化代码
        # usercountyear = request_dict.get('usercountyear', None)
        # if usercountyear == None:
        #     return response.json(444)
        # usercountyear = int(usercountyear)
        # count = Device_User.objects.extra(select={'dates': "DATE_FORMAT(data_joined,'%%Y-%%m')"},
        #                                   where=["data_joined between '%s-01-01' and '%s-01-01' "],
        #                                   params=[usercountyear, usercountyear+1]).values(
        #     'dates').annotate(用户合计=Count('data_joined')).order_by('dates')
        count = Device_User.objects.extra(select={'dates': "DATE_FORMAT(data_joined,'%%Y-%%m')"}, ).values(
            'dates').annotate(用户合计=Count('data_joined')).order_by('dates')
        print(count.query)
        return response.json(0, list(count))

    # 类型：云存服务统计
    # 统计开通云存的设备有多少台√
    # 统计未支付，支付成功的订单√
    # 统计开通云存的增长率    (每个月开通云存套餐的总数)√
    # 统计已开通云存的各套餐总数√
    # 统计已支付的订单总金额√
    def cloudservicesum(self, userID, response):
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)
        uid_cloud = UID_Bucket.objects.values('uid').distinct().count()
        cloud_sum = UID_Bucket.objects.all().count()
        pay_0 = Order_Model.objects.filter(status='0').count()
        pay_1 = Order_Model.objects.filter(status='1').count()
        money = Order_Model.objects.filter(status='1').aggregate(Sum('price'))
        data_dict = {
            "开通云存的设备数": uid_cloud,
            "已开通云存的各套餐总数": cloud_sum,
            "未支付的订单数": pay_0,
            "已支付的订单数": pay_1,
            "已支付的订单总金额": money['price__sum'],
        }
        return response.json(0, data_dict)

    # 每个月开通云存套餐的总数
    def usercloud(self, userID, response):
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)
        a = Order_Model.objects.extra(select={'dates': "FROM_UNIXTIME(addTime,'%%Y-%%m')"}).values(
            'dates').filter(status=1).annotate(开通云存合计=Count('addTime')).order_by('dates')
        return response.json(0, list(a))

    def equipment_logs(self, userID, request_dict, response):
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        order = request_dict.get('order', '-id')
        if order == '':
            order = '-id'
        if not page or not line:
            return response.json(444, 'page,line')

        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is not True:
            return response.json(404)

        if SERVER_TYPE == 'Ansjer.formal_settings':
            logKey = 'logger'
        else:
            logKey = 'test_logger'
        # 判断redis列表长度
        redisObj = RedisObject()
        data_list = redisObj.lrange(logKey, 0, -1)
        redisObj.del_data(key=logKey)
        add_batch_log(data_list)

        qs = EquipmentLogModel.objects.all().order_by(order)
        if qs.exists():
            count = qs.count()
            res = qs[(page - 1) * line:page * line]
            send_json = CommonService.qs_to_dict(res)
            send_json['count'] = count
            return response.json(0, send_json)
        return response.json(0, {'datas': [], 'count': 0})

# 访问日志批量添加
def add_batch_log(data_list):
    try:
        if data_list:
            querysetlist = []
            for i in data_list:
                data = json.loads(i.decode('utf-8'))
                querysetlist.append(EquipmentLogModel(**data))
            EquipmentLogModel.objects.bulk_create(querysetlist)
        else:
            return
    except Exception as e:
        print('ggga')
        print(repr(e))
        return False
    else:
        return True
