#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/6/1 10:20
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: DeviceManage.py
@Contact: chanjunkai@163.com
"""
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
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 Service.CommonService import CommonService
from Model.models import Device_Info
import traceback,datetime
from django.utils import timezone
from Object.RedisObject import RedisObject
'''
http://192.168.136.40:8077/device/manage?operation=query&token=test&page=1&line=10
http://192.168.136.40:8077/device/manage?operation=delete&id=1&id=2
http://192.168.136.45:8077/device/manage?operation=findByUser&token=test&username=13800138001&page=1&line=10
-----------------------

'''


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

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

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

    def validation(self, request_dict, *args, **kwargs):
        operation = request_dict.get('operation', None)
        response = ResponseObject()
        if not operation:
            return response.json(444,'operation')
        token = request_dict.get('token', None)
        if token is not None:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code == 0:
                userID = tko.userID
                if userID is not None:
                    if operation == 'query':
                        return self.query(request_dict, userID, response)
                    elif operation == 'findByUser':
                        return self.findByUser(request_dict, userID, response)
                    elif operation == 'delete':
                        return self.delete(request_dict, userID, response)
                return response.json(444, 'operation')
            else:
                return response.json(tko.code)
        else:
            return response.json(309)

    def query(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is True:
            page = int(request_dict.get('page', None))
            line = int(request_dict.get('line', None))
            if page is not None and line is not None:
                queryset = Device_Info.objects.all()
                if queryset.exists():
                    count = queryset.count()
                    res = queryset[(page - 1) * line:page * line]
                    send_dict = CommonService.qs_to_dict(res)
                    for k, v in enumerate(send_dict["datas"]):
                        for val in res:
                            if v['pk'] == val.id:
                                if send_dict["datas"][k]['fields']['Online'] is True:
                                    dl_time = val.update_time+datetime.timedelta(minutes=60)
                                    now_time = timezone.localtime(timezone.now())
                                    if now_time > dl_time:
                                        pass
                                        # send_dict["datas"][k]['fields']['Online'] = False
                                username= ModelService.get_user_name(send_dict["datas"][k]['fields']['userID'])
                                send_dict["datas"][k]['fields']['username']=username
                                primary= ModelService.get_user_name(send_dict["datas"][k]['fields']['primaryUserID'])
                                send_dict["datas"][k]['fields']['primaryusername']=primary
                    send_dict['count'] = count
                    return response.json(0, send_dict)
                return response.json(0,{'count':0})
            else:
                return response.json(444,'page,line')
        else:
            return response.json(404)

    def delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=10)
        # redisObj = RedisObject(db=8)
        # redisObj.del_data(key='uid_qs_' + userID)
        if own_perm is True:
            id = request_dict.get('id', None)
            if id:
                Device_Info.objects.filter(id=id).delete()
                return response.json(0)
            else:
                return response.json(444,'id must list')
        else:
            return response.json(404)

    def findByUser(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is True:
            page = int(request_dict.get('page', None))
            line = int(request_dict.get('line', None))
            username = request_dict.get('username', None)
            param_flag = CommonService.get_param_flag(data=[page, line, username])
            if param_flag is True:
                userID_id= ModelService.get_userID_byname(username=username)
                print(userID_id)
                queryset = Device_Info.objects.filter(userID_id=userID_id)
                if queryset.exists():
                    count = queryset.count()
                    res = queryset[(page - 1) * line:page * line]
                    send_dict = CommonService.qs_to_dict(res)
                    for k, v in enumerate(send_dict["datas"]):
                        for val in res:
                            if v['pk'] == val.id:
                                if send_dict["datas"][k]['fields']['Online'] is True:
                                    dl_time = val.update_time + datetime.timedelta(minutes=1)
                                    now_time = timezone.localtime(timezone.now())
                                    if now_time > dl_time:
                                        send_dict["datas"][k]['fields']['Online'] = False
                                send_dict["datas"][k]['fields']['username']=username
                                primary= ModelService.get_user_name(send_dict["datas"][k]['fields']['primaryUserID'])
                                send_dict["datas"][k]['fields']['primaryusername']=primary
                    send_dict['count'] = count
                    return response.json(0, send_dict)
                return response.json(0,{'count':0})
            else:
                return response.json(444)
        else:
            return response.json(404)


@csrf_exempt
def Devices(request, UID):
    # 获取指定用户指定设备详细信息
    if request.method == 'GET':
        request.encoding = 'utf-8'
        token = request.GET.get('token', None)
        response = ResponseObject()
        if token is not None:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code == 0:
                userID = tko.userID
                res = Device_Info.objects.filter(userID_id=userID,UID=UID)
                send_dict = CommonService.qs_to_dict(res)
                return response.json(0, send_dict)
            else:
                return response.json(tko.code)
        else:
            return response.json(309)


