import time
import traceback

import oss2
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from django.views.generic.base import View

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Ansjer.config import SERVER_DOMAIN
from Model.models import Device_Info, VodHlsModel, Equipment_Info
from Model.models import Device_User
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.UidTokenObject import UidTokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService

'''
http://192.168.136.45:8077/equipment/info?token=test&operation=add&devUid=2N1K3LE78TYJ38CE111A&Channel=0&eventType=1&eventTime=1234567890&operation=add&alarm=21342134&receiveTime=1234567891234567
http://test.dvema.com/equipment/info?token=test&operation=query&page=1&line=10
http://192.168.136.45:8077/equipment/info?token=test&operation=delete&devUid=UKPAH63V23U4ZHEB111A&id=5&id=6&id=7
http://192.168.136.40:8077/equipment/info?token=test&operation=update&devUid=UKPAH63V23U4ZHEB111A&id=3&id=4
http://192.168.136.45:8077/equipment/info?token=test&operation=queryByAdmin&page=1&line=10&userID_id=151547867345163613800138001
http://192.168.136.45:8077/equipment/info?token=test&operation=deleteByAdmin&id=5&id=6&id=7

'''


class EquipmentInfo(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(EquipmentInfo, 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):
        token = request_dict.get('token', None)
        response = ResponseObject()
        tko = TokenObject(token)
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        operation = request_dict.get('operation', None)
        if not userID:
            return response.json(309)
        if operation == 'query':
            return self.query_info(request_dict, userID, response)
        elif operation == 'add':
            return self.add_info(request_dict, userID, response)
        elif operation == 'update':
            return self.update_info(request_dict, userID, response)
        elif operation == 'delete':
            return self.delete_info(request_dict, userID, response)
        elif operation == 'findByTime':
            return self.findByTime_info(request_dict, userID, response)
        if operation == 'queryByAdmin':
            return self.query_all_info(request_dict, userID, response)
        if operation == 'deleteByAdmin':
            return self.delete_by_admin(request_dict, userID, response)
        else:
            return response.json(444, {"parm": "operation"})

    def add_info(self, request_dict, userID, response):
        devUid = request_dict.get('devUid', None)
        Channel = request_dict.get('Channel', None)
        eventType = request_dict.get('eventType', None)
        eventTime = request_dict.get('eventTime', None)
        receiveTime = request_dict.get('receiveTime', None)
        alarm = request_dict.get('alarm', None)
        if not devUid or not Channel or not eventType or not eventTime or not alarm or not receiveTime:
            return response.json(444, 'devUid, Channel, eventType, eventTime, alarm, receiveTime')
        own_device = ModelService.check_own_device(userID, UID=devUid)
        if own_device is not True:
            return response.json(14)
        device_info = Device_Info.objects.filter(UID=devUid, userID_id=userID)
        if not device_info.exists():
            return response.json(14)
        try:

            nowTime = int(time.time())
            equipment_info = Equipment_Info(
                userID_id=userID,
                devUid=devUid,
                Channel=Channel,
                eventType=eventType,
                receiveTime=receiveTime,
                eventTime=eventTime,
                devNickName=device_info[0].NickName,
                addTime=nowTime,
                alarm=alarm)
            equipment_info.save()
        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(500, errorInfo)
        else:
            if equipment_info.id:
                return response.json(0, {'infoID': equipment_info.id,
                                         'devUid': devUid,
                                         'Channel': Channel,
                                         'alarm': alarm,
                                         'eventType': eventType,
                                         'eventTime': eventTime,
                                         'receiveTime': receiveTime,
                                         'devNickName': equipment_info.devNickName})
            else:
                return response.json(500)

    def query_info(self, request_dict, userID, response):
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        if not page or not line:
            return response.json(444, 'page,line')
        qs = Equipment_Info.objects.filter(userID_id=userID)
        uid = request_dict.get('uid', None)
        if uid:
            qs = qs.filter(devUid=uid)
            dvqs = Device_Info.objects.filter(UID=uid).values('Type', 'NickName')
            uid_type_dict = {uid: {'type': dvqs[0]['Type'], 'NickName': dvqs[0]['NickName']}}
        else:
            dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
            uid_type_dict = {}
            for dv in dvqs:
                uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
        if not qs.exists():
            return response.json(0, {'datas': [], 'count': 0})
        count = qs.count()
        res = qs[(page - 1) * line:page * line]
        send_json = CommonService.qs_to_dict(res)
        res = []
        for p in send_json['datas']:
            p['fields']['viewAccont'] = ''
            p['fields']['viewPwd'] = ''
            devUid = p['fields']['devUid']
            if devUid in uid_type_dict.keys():
                p['fields']['uid_type'] = uid_type_dict[devUid]['type']
                p['fields']['devNickName'] = uid_type_dict[devUid]['NickName']
            else:
                p['uid_type'] = ''
            res.append(p)
        return response.json(0, {'datas': res, 'count': count})


    def update_info(self, request_dict, userID, response):
        is_update_all = request_dict.get('is_update_all', 0)
        eventType = request_dict.get('eventType', None)
        if int(is_update_all) == 1:
            try:
                eq = Equipment_Info.objects.filter(userID_id=userID)
                if eventType:
                    eq = eq.filter(eventType=int(eventType))
                is_update = eq.update(status=1)
                return response.json(0, {'update_count': is_update})
            except Exception as e:
                print(repr(e))
            return response.json(0, {'update_success': 'all'})
        else:
            id_list = request_dict.getlist('id[]', None)
            if id_list is None or len(id_list) < 1:
                id_list = request_dict.getlist('id', None)
            param_flag = CommonService.get_param_flag(data=[id_list])
            if param_flag is True:
                count = 0
                for id in id_list:
                    try:
                        eq = Equipment_Info.objects.filter(id=int(id))
                        if eq.exists():
                            own_dev = ModelService.check_own_device(userID, eq[0].devUid)
                            if own_dev is True:
                                count += 1
                                eq.update(status=1)
                    except Exception as e:
                        print(repr(e))
                return response.json(0, {'update_success': count})
            else:
                return response.json(444)

    def delete_info(self, request_dict, userID, response):
        id_list = request_dict.getlist('id[]', None)
        if id_list is None or len(id_list) < 1:
            id_list = request_dict.getlist('id', None)
        param_flag = CommonService.get_param_flag(data=[id_list])
        if param_flag is True:
            try:
                for id in id_list:
                    eq = Equipment_Info.objects.filter(id=id)
                    if eq.exists():
                        own_dev = ModelService.check_own_device(userID, eq[0].devUid)
                        if own_dev is True:
                            eq.delete()
            except Exception as e:
                errorInfo = traceback.format_exc()
                print(errorInfo)
                return response.json(424, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(444)

    def findByTime_info(self, request_dict, userID, response):
        startTime = request_dict.get('startTime')
        endTime = request_dict.get('endTime')
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        if not startTime or not endTime or not page or not line:
            return response.json(444, 'startTime, endTime, page, line')
        uid_list = Device_Info.objects.filter(userID_id=userID).values_list('UID', flat=True)
        if not len(uid_list):
            return response.json(0, {'datas': [], 'count': 0})
        qs = Equipment_Info.objects.filter(userID_id=userID,
                                           eventTime__range=(startTime, endTime)).order_by('-id')
        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)

    # 管理员查询指定用户的推送信息接口
    def query_all_info(self, request_dict, userID, response):
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        username = request_dict.get('username', None)
        uid = request_dict.get('uid', None)
        devNickName = request_dict.get('devNickName', None)
        Channel = request_dict.get('Channel', None)
        if not page or not line:
            return response.json(444, 'page,line')
        check_perm = ModelService.check_perm(userID=userID, permID=30)
        if not check_perm:
            return response.json(404)

        if not username and not uid and not devNickName and not Channel:
            qs = Equipment_Info.objects.all().order_by('-id')
        elif username:
            user = Device_User.objects.filter(username=username)
            users = CommonService.qs_to_dict(user)
            # 从字典类型中找到对应的pk值，即是userID
            user_id = users.get('datas')[0].get('pk')
            if not user.exists():
                return response.json(104)

            uid_list = Device_Info.objects.filter(userID_id=user_id).values_list('UID', flat=True)
            if not len(uid_list):
                return response.json(0, {'datas': [], 'count': 0})
            qs = Equipment_Info.objects.filter(userID_id=user_id).order_by('-id')
        elif uid:
            qs = Equipment_Info.objects.filter(devUid=uid).order_by('-id')
        elif devNickName:
            qs = Equipment_Info.objects.filter(devNickName=devNickName).order_by('-id')
        elif Channel:
            qs = Equipment_Info.objects.filter(Channel=Channel).order_by('-id')
        if not qs.exists():
            return response.json(0, {'datas': [], 'count': 0})
        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)

    # 管理员的删除推送信息的接口
    def delete_by_admin(self, request_dict, userID, response):
        id_list = request_dict.getlist('id', None)
        if not len(id_list):
            return response.json(444, 'id is None or not list')
        check_perm = ModelService.check_perm(userID=userID, permID=10)
        if check_perm is True:
            try:
                is_delete = Equipment_Info.objects.filter(id__in=id_list).delete()
            except Exception as e:
                errorInfo = traceback.format_exc()
                print(errorInfo)
                return response.json(424, {'details': repr(e)})
            else:
                return response.json(0, {'delete_count': is_delete[0]})
        else:
            return response.json(404)


'''
use information_schema;
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='Ansjer81';
'''
# 删除访问日志
def deleteExpireEquipmentInfo(request):
    response = ResponseObject()
    import time
    nowTime = int(time.time())
    try:
        for i in range(5):
            ei = Equipment_Info.objects.filter(addTime__lte=str(nowTime - 3600 * 24 * 7))[0:10000]
            id_list = list(ei.values_list("id", flat=True))
            Equipment_Info.objects.filter(id__in=id_list).delete()
        return response.json(0)
    except Exception as e:
        return response.json(500, repr(e))


# 按季度删除访问日志
def deleteExpireEquipmentInfoById(request):
    response = ResponseObject()
    id = int(request.GET.get('id', None))

    if id is None:
        return response.json(0)

    Equipment_Info.objects.filter(id__lte=id).delete()
    return response.json(0)


