#!/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/12/17 15:50
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: AliPayObject.py
@Contact: pzb3076@163.com
"""

import re
import time
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.views.generic.base import View
import datetime, simplejson as json
from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
from Model.models import Device_Info, Role, UserExModel, Device_User
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject, RedisObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
class UserExView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(UserExView, 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):
        response = ResponseObject()
        if operation is None:
            return response.json(444, 'error path')
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if operation == 'adminDelete':
            return self.do_admin_delete(request_dict, userID, response)
        elif operation == 'adminQuery':
            return self.do_admin_query(request_dict, userID, response)
        else:
            return response.json(444, 'error path')

    # 管理员删除
    def do_admin_delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 10)
        if own_perm is True:
            id = request_dict.getlist('id', None)
            ue = UserExModel.objects.filter(id=id)
            if ue.exists():
                ue.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(404)

    # 管理员查询接口
    def do_admin_query(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is not True:
            return response.json(404)
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        content = request_dict.get('content', None)
        rstime = request_dict.get('rstime', None)
        retime = request_dict.get('retime', None)
        app_id = request_dict.get('app_id', '')

        response = ResponseObject()
        if page is not None and line is not None:
            page = int(page)
            line = int(line)
        else:
            return response.json(10, 'page,line is none')

        if app_id == "":
            if content is None:
                queryset = Device_User.objects.all().order_by('-data_joined')
            else:
                try:
                    content = json.loads(content)
                    search_kwargs = CommonService.get_kwargs(data=content)
                    queryset = Device_User.objects.filter(**search_kwargs)
                except Exception as e:
                    return response.json(444, repr(e))
            if rstime is not None and rstime != '' and retime is not None and retime != '':
                startt = datetime.datetime.fromtimestamp(int(rstime))
                rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
                endt = datetime.datetime.fromtimestamp(int(retime))
                retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
                queryset = queryset.filter(data_joined__range=(rstime, retime))
            elif rstime is not None and rstime != '':
                startt = datetime.datetime.fromtimestamp(int(rstime))
                rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
                queryset = queryset.filter(data_joined__gte=rstime)
            elif retime is not None and retime != '':
                endt = datetime.datetime.fromtimestamp(int(retime))
                retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
                queryset = queryset.filter(data_joined__lte=retime)
            if queryset.exists():
                count = queryset.count()
                res = queryset[(page - 1) * line:page * line]
                sqlDict = CommonService.qs_to_dict(res)
                for k, v in enumerate(sqlDict["datas"]):
                    if len(v['fields']['role']) > 0:
                        role_query_set = Role.objects.get(rid=v['fields']['role'][0])
                        sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
                    for val in res:
                        if v['pk'] == val.userID:
                                redisObj = RedisObject(db=3)
                                if redisObj.get_data(key=val.userID):
                                    sqlDict["datas"][k]['fields']['online'] = True
                                else:
                                    sqlDict["datas"][k]['fields']['online'] = False

                    ue = UserExModel.objects.filter(userID=v['pk'])
                    if ue.exists():
                        sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
                    else:
                        sqlDict["datas"][k]['fields']['appBundleId'] = ''
                sqlDict['count'] = count
                return response.json(0, sqlDict)
            return response.json(0, {'datas': [], 'count': 0})
        else:
            ue = UserExModel.objects.filter(appBundleId=app_id)
            if ue.exists():
                count = ue.count()
                res = ue[(page - 1) * line:page * line]
                sqlDict1 = CommonService.qs_to_dict(res)
                user_id=[]
                for k1, v1 in enumerate(sqlDict1["datas"]):
                    user_id.extend([v1['fields']['userID']])
                print(user_id)
                queryset = Device_User.objects.filter(userID__in=user_id)
                sqlDict = CommonService.qs_to_dict(queryset)
                for k, v in enumerate(sqlDict["datas"]):
                    if len(v['fields']['role']) > 0:
                        role_query_set = Role.objects.get(rid=v['fields']['role'][0])
                        sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
                    for val in queryset:
                        if v['pk'] == val.userID:
                            redisObj = RedisObject(db=3)
                            if redisObj.get_data(key=val.userID):
                                sqlDict["datas"][k]['fields']['online'] = True
                            else:
                                sqlDict["datas"][k]['fields']['online'] = False
                    ue = UserExModel.objects.filter(userID=v['pk'])
                    if ue.exists():
                        sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
                    else:
                        sqlDict["datas"][k]['fields']['appBundleId'] = ''
                sqlDict['count'] = count
                return response.json(0, sqlDict)
            return response.json(0, {'datas': [], 'count': 0})

