import re
import time
import traceback
import threading
import logging

import requests
import simplejson as json
from django.utils import timezone
from Model.models import Device_User, Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, \
    UIDCompanySerialModel, iotdeviceInfoModel, UIDMainUser
from django.db.models import Q
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, BASE_DIR
from Object.ETkObject import ETkObject
import oss2
from django.http import JsonResponse
from Object.RedisObject import RedisObject
from Controller.DetectController import DetectControllerView


#     查询用户设备
def queryUserEquipmentInterface(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 = request_dict.get('token', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    if not userID:
        return response.json(309)
    dvqs = Device_Info.objects.filter(userID_id=userID)
    dvdict = CommonService.qs_to_dict(dvqs)
    uid_list = Device_Info.objects.filter(userID_id=userID, isShare=False). \
        values_list('UID', flat=True)
    ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
        values('bucket__content', 'status', 'channel', 'endTime', 'uid')
    res = []
    nowTime = int(time.time())
    for p in dvdict['datas']:
        p['fields']['vod'] = []
        for dm in ubqs:
            if p['fields']['UID'] == dm['uid']:
                if dm['endTime'] > nowTime:
                    p['fields']['vod'].append(dm)
                    # dm['valid'] = 1
                # else:
                #     dm['valid'] = 0
        # p['fields']['primaryUserID'] = ''
        res.append(p)
    return response.json(0, {'datas': res})


def addNewUserEquipmentInterface(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 = request_dict.get('token', None)
    deviceContent = request_dict.get('content', None)
    if not deviceContent:
        return response.json(444, 'content')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID

    try:
        deviceData = json.loads(deviceContent)
        UID = deviceData.get('UID', None)
        if not UID:
            return response.json(444, 'content')
        dValid = Device_Info.objects.filter(userID_id=userID, UID=UID)
        if dValid:
            return response.json(174)
        else:
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            UID = deviceData.get('UID', '')
            re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
            if re_uid.match(UID):
                userDevice = Device_Info(id=CommonService.getUserID(getUser=False), userID_id=userID,
                                         **deviceData)
                userDevice.save()
                if UID == '98UXAA8BRPA35VAL111A':
                    asy = threading.Thread(target=ModelService.add_log,
                                           args=(CommonService.get_ip_address(request), userID, 'addV0'))
                    asy.start()

                # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
                # # 判断是否有已绑定用户
                # if not is_bind.exists():
                #     userDevice = Device_Info(id=CommonService.getUserID(getUser=False), userID_id=userID,
                #                              **deviceData)
                #     userDevice.save()
                # else:
                #     # 分享添加
                #     if 'isShare' in deviceData:
                #         deviceData['isShare'] = True
                #     else:
                #         deviceData['isShare'] = True
                #     bind_userID = is_bind[0].userID_id
                #     userDevice = Device_Info(id=CommonService.getUserID(getUser=False),
                #                              userID_id=userID,
                #                              primaryUserID=bind_userID,
                #                              primaryMaster=ModelService.get_user_name(bind_userID),
                #                              **deviceData)
                #     userDevice.save()
            else:
                return response.json(444, 'UID')

    except Exception as e:
        errorInfo = traceback.format_exc()
        print('添加设备错误: %s ' % errorInfo)
        return response.json(178, repr(e))
    else:
        sqlDict = CommonService.qs_to_dict([userDevice])
        return response.json(0, sqlDict)


def delUserEquipmentInterface(request):
    '''
    删除用户设备
    :param request:
    :return:
    '''
    response = ResponseObject()
    request.encoding = 'utf-8'
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    id = request_dict.get('id', None)
    if not id:
        return response.json(444, 'id')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    # 主用户删除设备全部删除
    try:
        dv_qs = Device_Info.objects.filter(userID_id=userID, id=id)
        # redisObj = RedisObject(db=8)
        # redisObj.del_data(key='uid_qs_' + userID)

        if dv_qs.exists():
            uid = dv_qs[0].UID
            asy = threading.Thread(target=ModelService.add_log, args=(CommonService.get_ip_address(request), userID, 'deleteV1'))
            asy.start()

            print('删除')
            UID_Preview.objects.filter(uid=uid).delete()
            dv_qs.delete()
            Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
            asy = threading.Thread(target=ModelService.del_eq_info, args=(userID, uid))
            asy.start()

    except Exception as e:
        errorInfo = traceback.format_exc()
        print('删除数据库记录错误: %s' % errorInfo)
        return response.json(176, repr(e))
    else:
        return response.json(0)


def modifyUserEquipmentInterface(request):
    '''
    修改用户设备
    :param request:
    :return:
    '''
    response = ResponseObject()
    if request.method == 'POST':
        request.encoding = 'utf-8'
        request_dict = request.POST
    elif request.method == 'GET':
        request.encoding = 'utf-8'
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    deviceContent = request_dict.get('content', None)
    id = request_dict.get('id', None)
    if not deviceContent or not id:
        return response.json(444, 'content,id')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    if userID is None:
        return response.json(309)
    try:
        deviceData = json.loads(deviceContent)

        if deviceData.__contains__('userID_id'):
            asy = threading.Thread(target=ModelService.update_log,
                                   args=(CommonService.get_ip_address(request), userID, 'modifyV0', deviceData, id))
            asy.start()
            return response.json(10, '110')

        if deviceData.__contains__('UID'):
            del deviceData['UID']

        dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
        dev_info_qs.update(**deviceData)
    except Exception as e:
        return response.json(177, repr(e))
    else:
        qs = Device_Info.objects.filter(userID_id=userID, id=id)
        res = CommonService.qs_to_dict(qs)
        if qs.exists():
            uid = qs[0].UID
            if uid == '98UXAA8BRPA35VAL111A':
                asy = threading.Thread(target=ModelService.update_log,
                                       args=(CommonService.get_ip_address(request), userID, 'modifyV0', deviceContent, id))
                asy.start()
            nickname = qs[0].NickName
            # 增加设备影子信息修改昵称 start
            us_qs = UidSetModel.objects.filter(uid=uid)
            if us_qs.exists():
                us_qs.update(nickname=nickname)
            else:
                ChannelIndex = qs[0].ChannelIndex
                nowTime = int(time.time())
                uid_set_create_dict = {
                    'uid': uid,
                    'addTime': nowTime,
                    'updTime': nowTime,
                    'ip': CommonService.get_ip_address(request),
                    'channel': ChannelIndex,
                    'nickname': nickname,
                }
                UidSetModel.objects.create(**uid_set_create_dict)
            Device_Info.objects.filter(UID=uid).update(NickName=nickname)
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
        return response.json(0, res)


def showAllUserEquipmentInterface(request, *callback_args, **callback_kwargs):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        fieldDict = request.POST
    elif request.method == 'GET':
        fieldDict = request.GET
    else:
        return response.json(444)
    token = request.POST.get('token', None)
    type = request.POST.get('type', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    if not userID:
        return response.json(309)
    own_perm = ModelService.check_perm(userID=userID, permID=30)
    if not own_perm:
        return response.json(404)
    if type == 'PC':
        page = int(fieldDict['page'])
        line = int(fieldDict['line'])
        qs = Device_Info.objects.all()
        count = qs.count()
        res = qs[(page - 1) * line:page * line]
        sqlDict = CommonService.qs_to_dict(query_set=res)
        sqlDict['count'] = count
        return response.json(0, sqlDict)
    else:
        qs = Device_Info.objects.all()
        res = CommonService.qs_to_dict(qs)
        return response.json(0, res)


def findEquipmentInfoInterface(request, *callback_args, **callback_kwargs):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'GET':
        fieldDict = request.GET
    elif request.method == 'POST':
        fieldDict = request.POST
    else:
        return response.json(444)
    deviceContent = fieldDict.get('content', None)
    token = fieldDict.get('token', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    if deviceContent:
        try:
            searchCondition = json.loads(deviceContent)
        except Exception as e:
            print(repr(e))
            return response.json(10, repr(e))
        else:
            kwargs = CommonService.get_kwargs(data=searchCondition)
            qs = Device_Info.objects.filter(**kwargs)
            page = int(fieldDict['page'])
            line = int(fieldDict['line'])
            count = qs.count()
            res = qs[(page - 1) * line:page * line]
            send_dict = CommonService.qs_to_dict(query_set=res)
            for k, v in enumerate(send_dict["datas"]):
                for val in res:
                    if v['pk'] == val.id:
                        send_dict["datas"][k]['fields']['username'] = \
                            ModelService.get_user_mark(send_dict["datas"][k]['fields']['userID'])
                        send_dict["datas"][k]['fields']['primaryusername'] = \
                            ModelService.get_user_mark(send_dict["datas"][k]['fields']['primaryUserID'])
            send_dict['count'] = count
            return response.json(0, send_dict)
    else:
        qs = Device_Info.objects.all()
        page = int(fieldDict['page'])
        line = int(fieldDict['line'])
        count = qs.count()
        res = qs[(page - 1) * line:page * line]
        send_dict = CommonService.qs_to_dict(query_set=res)
        for k, v in enumerate(send_dict["datas"]):
            for val in res:
                if v['pk'] == val.id:
                    username = ModelService.get_user_name(send_dict["datas"][k]['fields']['userID'])
                    send_dict["datas"][k]['fields']['username'] = username
                    send_dict["datas"][k]['fields']['primaryusername'] = \
                        ModelService.get_user_mark(send_dict["datas"][k]['fields']['primaryUserID'])
        send_dict['count'] = count
        return response.json(0, send_dict)


# 添加设备字段
def addInterface(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 = request_dict.get('token', None)
    UID = request_dict.get('UID', None)
    NickName = request_dict.get('NickName', None)
    View_Account = request_dict.get('View_Account', None)
    View_Password = request_dict.get('View_Password', '')
    Type = request_dict.get('Type', None)
    ChannelIndex = request_dict.get('ChannelIndex', None)
    version = request_dict.get('version', '')
    isCheckMainUser = request_dict.get('isCheckMainUser', None)
    isMainUserExists = False
    if all([UID, NickName, View_Account, Type, ChannelIndex]):
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            userID = tko.userID
            re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
            if re_uid.match(UID):
                is_exist = Device_Info.objects.filter(UID=UID, userID_id=userID)
                if is_exist:
                    # 判断设备是否已存在
                    if is_exist[0].isExist == 1:
                        return response.json(174)
                    else:
                        is_exist.delete()
                if UID == '98UXAA8BRPA35VAL111A':
                    asy = threading.Thread(target=ModelService.add_log,
                                           args=(CommonService.get_ip_address(request), userID, 'addV1'))
                    asy.start()
                    return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
                pass

                pk = CommonService.getUserID(getUser=False)



                userName = Device_User.objects.get(userID=userID).username
                main_exist = Device_Info.objects.filter(UID=UID)
                main_exist = main_exist.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID', 'vodPrimaryMaster')
                vodPrimaryUserID = userID
                vodPrimaryMaster = userName
                if main_exist.exists():
                    vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
                    vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']

                is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'vodPrimaryUserID')
                # 判断是否有已绑定用户
                isvodPrimaryUserID = ''
                for forbind in is_bind:
                    if forbind['vodPrimaryUserID'] != '':
                        isvodPrimaryUserID = forbind['vodPrimaryUserID']

                if isCheckMainUser != '1':
                    if main_exist.exists():
                        vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
                        vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
                    else:
                        vodPrimaryUserID = ''
                        vodPrimaryMaster = ''

                isusermain = False
                if is_bind and isvodPrimaryUserID != userID and isvodPrimaryUserID != '':
                    isusermain = True

                # uid_main_exist = UIDMainUser.objects.filter(UID=UID).values('UID', 'user_id')
                # if uid_main_exist.exists():
                #     vodPrimaryUserID = uid_main_exist[0]['user_id']
                #     vodPrimaryMaster = Device_User.objects.get(userID=vodPrimaryUserID).username
                #
                #     if vodPrimaryUserID != userID:
                #         isusermain = True

                # 判断是否有已绑定用户
                if isCheckMainUser == '1' and isusermain:
                    res = {
                        'id': pk,
                        'userID': userID,
                        'NickName': NickName,
                        'UID': UID,
                        'View_Account': View_Account,
                        'View_Password': View_Password,
                        'ChannelIndex': ChannelIndex,
                        'Type': Type,
                        'isShare': False,
                        'primaryUserID': '',
                        'primaryMaster': '',
                        'vodPrimaryUserID': vodPrimaryUserID,
                        'vodPrimaryMaster': vodPrimaryMaster,
                        'data_joined': '',
                        'version': version,
                        'isVod': 0,
                        'isExist': 1,
                        'userID__userEmail': ''
                    }
                    res['vod'] = [
                        {
                            "status": 1,
                            "channel": ChannelIndex,
                            "endTime": '',
                            "bucket__content": '',
                            "uid": UID
                        }
                    ]
                    res['isMainUserExists'] = 1
                    return response.json(0, res)

                try:
                    # 判断是否有用户绑定
                    nowTime = int(time.time())
                    us_qs = UidSetModel.objects.filter(uid=UID)
                    if not us_qs.exists():
                        uid_set_create_dict = {
                            'uid': UID,
                            'addTime': nowTime,
                            'updTime': nowTime,
                            'ip': CommonService.get_ip_address(request),
                            'channel': ChannelIndex,
                            'nickname': NickName,
                            'version': version,
                        }
                        UidSetModel.objects.create(**uid_set_create_dict)
                    else:
                        us_qs.update(nickname=NickName)

                    userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
                                             NickName=NickName, View_Account=View_Account,
                                             View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex,
                                             version=version, vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
                    userDevice.save()
                    uid_serial_qs = UIDCompanySerialModel.objects.filter(
                        uid__uid=UID)
                    if uid_serial_qs.exists():
                        uid_serial = uid_serial_qs[0]
                        Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
                                                                   vodPrimaryMaster=vodPrimaryMaster,
                                                                   serial_number=uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark)
                    else:
                        Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
                                                                   vodPrimaryMaster=vodPrimaryMaster)
                    # if isCheckMainUser == '1':
                    #     uid_main_dict = {
                    #         'UID': UID,
                    #         'user_id': vodPrimaryUserID
                    #     }
                    #     UIDMainUser.objects.create(**uid_main_dict)
                # redisObj = RedisObject(db=8)
                    # redisObj.del_data(key='uid_qs_' + userID)
                except Exception as e:
                    return response.json(10, repr(e))
                else:
                    dvqs = Device_Info.objects.filter(id=pk).values('id', 'userID', 'NickName', 'UID',
                                                                    'View_Account',
                                                                    'View_Password', 'ChannelIndex', 'Type',
                                                                    'isShare',
                                                                    'primaryUserID', 'primaryMaster', 'vodPrimaryUserID', 'vodPrimaryMaster', 'userID__userEmail',
                                                                    'data_joined', 'version',
                                                                    'isVod', 'isExist', 'isCameraOpenCloud', 'serial_number')
                    dvql = CommonService.qs_to_list(dvqs)
                    ubqs = UID_Bucket.objects.filter(uid=UID). \
                        values('bucket__content', 'status', 'channel', 'endTime', 'uid')
                    res = dvql[0]
                    res['vod'] = list(ubqs)


                    # 新增获取IOT证书内容
                    iotqs = iotdeviceInfoModel.objects.filter(serial_number=dvql[0]['serial_number'])
                    if iotqs.exists():
                        res['iot'] = {
                                'endpoint': iotqs[0].endpoint,
                                'token_iot_number': iotqs[0].endpoint
                        }

                    if isMainUserExists:
                        res['isMainUserExists'] = 1
                    return response.json(0, res)


            else:
                return response.json(444, {'param': 'UID'})
        else:
            return response.json(tko.code)
    else:
        return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex,version'})


# 添加设备字段
def judgeInterface(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 = request_dict.get('token', None)
    uid = request_dict.get('uid', None)
    if all([uid, token]):
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
            if re_uid.match(uid):
                is_bind = Device_Info.objects.filter(UID=uid, isShare=False)
                # 判断是否有已绑定用户
                if is_bind:
                    qs = is_bind.values('userID__NickName', 'NickName')
                    nickname = qs[0]['NickName']
                    us_qs = UidSetModel.objects.filter(uid=uid).values('nickname')
                    if us_qs.exists():
                        nickname = us_qs[0]['NickName']
                    res = {
                        'bind_user': qs[0]['userID__NickName'],
                        'bind_device_name': nickname,
                    }
                    return response.json(15, res=res)
                else:
                    return response.json(0, 'no bind user')
            else:
                return response.json(444, {'param': 'UID'})
        else:
            return response.json(tko.code)
    else:
        return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})


# 管理员添加
def admin_addInterface(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 = request_dict.get('token', None)
    deviceContent = request_dict.get('content', None)
    ipdizhi = request_dict.get('ipdizhi', None)
    username = request_dict.get('username', None)
    if not username:
        return response.json(444, 'username')
    if not deviceContent:
        return response.json(444, 'content')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    own_perm = ModelService.check_perm(userID, 40)
    # 权限判断
    if own_perm is not True:
        return response.json(404)
    # 查询id
    user = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username))

    if user.exists():
        user_dict = CommonService.qs_to_dict(user)
        userID = user_dict.get('datas')[0].get('pk')
    else:
        return response.json(104)
    print(deviceContent)
    try:
        deviceData = json.loads(deviceContent)
        UID = deviceData.get('UID', None)
        if not UID:
            return response.json(444, 'content')
        dValid = Device_Info.objects.filter(userID_id=userID, UID=UID)
        if dValid:
            return response.json(174)
        else:
            UID = deviceData.get('UID', '')
            re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            if re_uid.match(UID):
                userDevice = Device_Info(id=CommonService.getUserID(getUser=False), userID_id=userID,
                                         **deviceData)
                userDevice.save()
                file_path = '/'.join((BASE_DIR, 'static/test.log'))

                file = open(file_path, 'a+')
                file.write(ipdizhi + "; username:" + username + "; time:" + time.strftime("%Y-%m-%d %H:%M:%S",
                                                                                          time.localtime()))
                file.write('\n')
                file.flush()
                file.close()

                # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
                # # 判断是否有已绑定用户
                # if not is_bind.exists():
                #     userDevice = Device_Info(id=CommonService.getUserID(getUser=False), userID_id=userID,
                #                              **deviceData)
                #     userDevice.save()
                # else:
                #     # 分享添加
                #     if 'isShare' in deviceData:
                #         deviceData['isShare'] = True
                #     else:
                #         deviceData['isShare'] = True
                #     bind_userID = is_bind[0].userID_id
                #     userDevice = Device_Info(id=CommonService.getUserID(getUser=False),
                #                              userID_id=userID,
                #                              primaryUserID=bind_userID,
                #                              primaryMaster=ModelService.get_user_name(bind_userID),
                #                              **deviceData)
                #     userDevice.save()
            else:
                return response.json(444, 'UID')

    except Exception as e:
        errorInfo = traceback.format_exc()
        print('添加设备错误: %s ' % errorInfo)
        return response.json(178, repr(e))
    else:
        sqlDict = CommonService.qs_to_dict([userDevice])
        return response.json(0, sqlDict)


# 超级管理员修改设备
def admin_modifyInterface(request):
    response = ResponseObject()
    if request.method == 'POST':
        request.encoding = 'utf-8'
        request_dict = request.POST
    elif request.method == 'GET':
        request.encoding = 'utf-8'
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    deviceContent = request_dict.get('content', None)
    username = request_dict.get('username', None)
    if not username:
        return response.json(444, 'username')
    id = request_dict.get('id', None)
    print(deviceContent)

    if not deviceContent or not id:
        return response.json(444, 'content,id')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    if userID is None:
        return response.json(309)
    own_perm = ModelService.check_perm(userID, 50)

    # 权限判断
    if own_perm is not True:
        return response.json(404)

    deviceData = json.loads(deviceContent)
    print(deviceData['UID'])
    # redisObj = RedisObject(db=8)
    # redisObj.del_data(key='uid_qs_' + userID)
    dValid = Device_Info.objects.filter(userID_id=userID, UID=deviceData['UID'])
    if dValid.exists():
        dValid_dict = CommonService.qs_to_dict(dValid)
        print(dValid_dict.get('datas')[0].get('pk'))
        if dValid_dict.get('datas')[0].get('pk') == id:
            print('可以编辑')
        else:
            return response.json(174)
        # 查询id
        user = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username))
        if user.exists():
            user_dict = CommonService.qs_to_dict(user)
            userID = user_dict.get('datas')[0].get('pk')
        try:

            # 更改的时间
            update_time = timezone.localtime(timezone.now())
            Device_Info.objects.filter(userID_id=userID, id=id).update(update_time=update_time, **deviceData)
        except Exception as e:
            return response.json(177, repr(e))
        else:
            qs = Device_Info.objects.filter(userID_id=userID, id=id)
            res = CommonService.qs_to_dict(qs)
            return response.json(0, res)
    else:
        # 查询id
        user = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username))
        if user.exists():
            user_dict = CommonService.qs_to_dict(user)
            userID = user_dict.get('datas')[0].get('pk')
        try:

            # 更改的时间
            update_time = timezone.localtime(timezone.now())
            Device_Info.objects.filter(userID_id=userID, id=id).update(update_time=update_time, **deviceData)
        except Exception as e:
            return response.json(177, repr(e))
        else:
            qs = Device_Info.objects.filter(userID_id=userID, id=id)
            res = CommonService.qs_to_dict(qs)
            return response.json(0, res)


# 新删除设备
def deleteInterface(request):
    '''
    删除用户设备
    :param request:
    :return:
    '''
    response = ResponseObject()
    request.encoding = 'utf-8'
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    id = request_dict.get('id', None)
    if not id:
        return response.json(444, 'id')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    # 主用户删除设备全部删除
    if not userID:
        return response.json(309)
    try:
        dv_qs = Device_Info.objects.filter(userID_id=userID, id=id)
        if dv_qs.exists():
            uid = dv_qs[0].UID
            asy = threading.Thread(target=ModelService.delete_log,
                                   args=(CommonService.get_ip_address(request), userID, 'deleteV2', uid))
            asy.start()
            if userID == dv_qs[0].vodPrimaryUserID:
                Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')

            if dv_qs[0].isShare:
                dv_qs.delete()
            else:
                # a.主用户删除设备
                dv_qs.delete()
                # 删除设备影子信息uid_set   外键关联删除设备推送配置信息 uid_push
                up_qs = UidPushModel.objects.filter(uid_set__uid=uid)
                DetectControllerView().do_delete_redis(uid)
                if up_qs.count() > 1:
                    UidPushModel.objects.filter(uid_set__uid=uid, userID_id=userID).delete()
                    redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
                    ykey = '{uid}_redis_qs'.format(uid=uid)
                    if ykey:
                        redisObj.del_data(key=ykey)
                else:
                    up_qs.delete()
                # b.分享获得用户假删除
                ud_dv_qs = Device_Info.objects.filter(UID=uid, isShare=True, primaryUserID=userID)
                if ud_dv_qs.exists():
                    ud_dv_qs.update(isExist=0)
                # 异步删除推送消息
            asy = threading.Thread(target=ModelService.del_eq_info, args=(userID, uid))
            asy.start()
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
        else:
            return response.json(14)
    except Exception as e:
        errorInfo = traceback.format_exc()
        print('删除数据库记录错误: %s' % errorInfo)
        return response.json(176, repr(e))
    else:
        return response.json(0)


# 新查询设备字段
def queryInterface(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 = request_dict.get('token', None)
    page = request_dict.get('page', None)
    line = request_dict.get('line', None)
    NickName = request_dict.get('NickName', None)
    uid = request_dict.get('uid', None)
    page = int(page)
    line = int(line)
    tko = TokenObject(token)
    response.lang = tko.lang
    if page <= 0:
        return response.json(0)
    if tko.code == 0:
        userID = tko.userID
        dvqs = Device_Info.objects.filter(userID_id=userID)
        # # 已重置的设备
        # dvqs = dvqs.filter(~Q(isExist=2))
        if NickName:
            dvqs = dvqs.filter(NickName__icontains=NickName)
        if uid:
            dvqs = dvqs.filter(UID=uid)
        # count = dvqs.count()
        dvql = dvqs[(page - 1) * line:page * line].values('id', 'userID', 'NickName', 'UID', 'View_Account',
                                                          'View_Password', 'ChannelIndex', 'Type', 'isShare',
                                                          'primaryUserID', 'primaryMaster', 'data_joined', 'version', 'vodPrimaryUserID', 'vodPrimaryMaster', 'userID__userEmail',
                                                          'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'serial_number')
        dvls = CommonService.qs_to_list(dvql)
        uid_list = []
        serial_number_list = []
        for dvl in dvls:
            if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
                dvl['isPrimaryUser'] = 1
            else:
                dvl['isPrimaryUser'] = 0
            uid_list.append(dvl['UID'])
            serial_number_list.append(dvl['serial_number'][0:6])


        #新增获取IOT证书内容
        iotqs = iotdeviceInfoModel.objects.filter(serial_number__in=serial_number_list)

        ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
        upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
        bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
        nowTime = int(time.time())
        data = []
        # 设备拓展信息表
        us_qs = UidSetModel.objects.filter(uid__in=uid_list).\
            values('uid', 'version', 'nickname', 'detect_interval')
        uv_dict = {}
        for us in us_qs:
            uv_dict[us['uid']] = {'version': us['version'],
                                  'nickname': us['nickname'],
                                  'detect_interval': us['detect_interval']}

        for p in dvls:
            #新增IOT
            p['iot'] = []
            for iot in iotqs:
                if p['serial_number'][0:6] == iot.serial_number:
                        p['iot'].append(
                            {
                                'endpoint':iot.endpoint,
                                'token_iot_number':iot.token_iot_number

                            }
                        )

            p['vod'] = []
            for dm in ubqs:
                if p['UID'] == dm['uid']:
                    if dm['endTime'] > nowTime:
                        p['vod'].append(dm)
            p['preview'] = []
            for up in upqs:
                if p['UID'] == up['uid']:
                    obj = 'uid_preview/{uid}/channel_{channel}.png'.\
                        format(uid=up['uid'], channel=up['channel'])
                    img_sign = bucket.sign_url('GET', obj, 300)
                    p['preview'].append(img_sign)
            p_uid = p['UID']
            if p_uid in uv_dict:
                # 设备版本号
                p['uid_version'] = uv_dict[p_uid]['version']
                p['detect_interval'] = uv_dict[p_uid]['detect_interval']
                # 设备昵称 调用影子信息昵称，先阶段不可
                if uv_dict[p_uid]['nickname']:
                    p['NickName'] = uv_dict[p_uid]['nickname']
            else:
                # 设备版本号
                p['uid_version'] = ''
            data.append(p)
        return response.json(0, data)
    else:
        return response.json(tko.code)


def uid_status(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 = request_dict.get('token', None)
    uid = request_dict.get('uid', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID

    # 调试
    logger = logging.getLogger('django')
    debugOne = int(time.time())

    # 判断用户是否绑定设备
    qs = UidSetModel.objects.filter(uid=uid).values('uid', 'detect_status', 'detect_interval', 'version', 'ucode',
                                                    'p2p_region', 'tz', 'video_code', 'channel', 'cloud_vod', 'id',
                                                    'detect_group', 'is_alexa', 'region_alexa')

    # 调试
    debugOnes = int(time.time())
    logger.error('————————debugOne_sec：', debugOnes - debugOne)

    # 判断uid配置表信息是否存在
    if qs.exists():
        # 获取uid推送是否添加过
        us_id = qs[0]['id']

        # 调试
        debugTwo = int(time.time())

        if UidPushModel.objects.filter(uid_set_id=us_id, userID_id=userID).exists():
            detect_status = qs[0]['detect_status']
        else:
            detect_status = 0
        data = {
            'push_status': detect_status,  # 推送状态
            'push_interval': qs[0]['detect_interval'],  # 推送间隔
            'ucode': qs[0]['ucode'],
            'version': qs[0]['version'],
            'p2p_region': qs[0]['p2p_region'],
            'tz': qs[0]['tz'],
            'video_code': qs[0]['video_code'],
            'channel': qs[0]['channel'],
            'cloud_vod': qs[0]['cloud_vod'],
            'detect_group': qs[0]['detect_group'],  # 推送组
            'is_alexa': qs[0]['is_alexa'],  # 推送组
            'region_alexa': qs[0]['region_alexa'],  # 推送组
        }

        # 调试
        debugTwos = int(time.time())
        logger.error('————————debugTwo_sec：', debugTwos - debugTwo)

        # 调试
        debugThere = int(time.time())

        # 查询云存储相关信息
        ubqs = UID_Bucket.objects.filter(uid=uid). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')

        # 调试
        debugTheres = int(time.time())
        logger.error('————————debugTheres_sec：', debugTheres - debugThere)

        nowTime = int(time.time())
        if ubqs.exists():
            if ubqs[0]['endTime'] > nowTime:
                data['vod'] = list(ubqs)
        return response.json(0, data)
    else:
        return response.json(0)

def uid_status_test(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 = request_dict.get('token', None)
    uid = request_dict.get('uid', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    # 判断用户是否绑定设备
    print(100000000000)
    qs = UidSetModel.objects.filter(uid=uid).values('uid', 'detect_status', 'detect_interval', 'version', 'ucode',
                                                    'p2p_region', 'tz', 'video_code', 'channel', 'cloud_vod', 'id',
                                                    'detect_group', 'is_alexa', 'region_alexa')
    # 判断uid配置表信息是否存在
    if qs.exists():
        # 获取uid推送是否添加过
        print(1111111111111)
        us_id = qs[0]['id']
        if UidPushModel.objects.filter(uid_set_id=us_id, userID_id=userID).exists():
            detect_status = qs[0]['detect_status']
        else:
            detect_status = 0
        data = {
            'push_status': detect_status,  # 推送状态
            'push_interval': qs[0]['detect_interval'],  # 推送间隔
            'ucode': qs[0]['ucode'],
            'version': qs[0]['version'],
            'p2p_region': qs[0]['p2p_region'],
            'tz': qs[0]['tz'],
            'video_code': qs[0]['video_code'],
            'channel': qs[0]['channel'],
            'cloud_vod': qs[0]['cloud_vod'],
            'detect_group': qs[0]['detect_group'],  # 推送组
            'is_alexa': qs[0]['is_alexa'],  # 推送组
            'region_alexa': qs[0]['region_alexa'],  # 推送组
        }
        print(22222222222)
        # 查询云存储相关信息
        ubqs = UID_Bucket.objects.filter(uid=uid). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
        nowTime = int(time.time())
        if ubqs.exists():
            if ubqs[0]['endTime'] > nowTime:
                data['vod'] = list(ubqs)
        print(3333333333333)
        return response.json(0, data)
    else:
        return response.json(0)



def update_uid_set(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 = request_dict.get('token', None)
    uid = request_dict.get('uid', None)
    version = request_dict.get('version', '')
    ucode = request_dict.get('ucode', '')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code == 0:
        userID = tko.userID
        nowTime = int(time.time())
        dvqs = Device_Info.objects.filter(userID_id=userID)
        # redisObj = RedisObject(db=8)
        # redisObj.del_data(key='uid_qs_' + userID)
        if dvqs.exists():
            us_qs = UidSetModel.objects.filter(uid=uid)
            if us_qs.exists():
                uid_set_update_dict = {
                    'updTime': nowTime,
                    'version': version,
                    'ucode': ucode,
                }
                us_qs.update(**uid_set_update_dict)
            else:
                uid_set_create_dict = {
                    'uid': uid,
                    'addTime': nowTime,
                    'updTime': nowTime,
                    'version': version,
                    'ucode': ucode,
                }
                UidSetModel.objects.create(**uid_set_create_dict)
            return response.json(0)
        else:
            return response.json(14)
    else:
        return response.json(tko.code)


# 测试环境
# test.shadow.dvema.com
# 生产环境
# shadow.dvema.com
# http://test.dvema.com/deviceShadow/update?etk=JVJWbFpFU0VOV1FsbEVTMFpOU2xKWFFURXhNVUU9Xz0=&ucode=1234&version=1324&p2p_region=CN
# 设备影子更新
def update_device_shadow(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)
    etk = request_dict.get('etk', None)
    eto = ETkObject(etk)
    uid = eto.uid
    if uid:
        # 重置按钮
        is_reset = request_dict.get('is_reset', None)
        # 传1则重置设备信息
        if is_reset == '1':

            UidSetModel.objects.filter(uid=uid).delete()
            # 重置设备，判断设备为已删除
            nowTime = int(time.time())
            uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=nowTime).values('id', 'has_unused').order_by('addTime')
            if not uid_bucket.exists():
                di_qs = Device_Info.objects.filter(UID=uid)
                di_qs.update(isExist=2)

            # 清除redis缓存
            # data = di_qs.values()
            # redisObj = RedisObject(db=8)
            # for di in data:
            #     key = 'uid_qs_' + di['userID_id']
            #     redis_value = redisObj.get_data(key=key)
            #     if redis_value is not False:
            #         redisObj.del_data(key)

        ucode = request_dict.get('ucode', None)
        version = request_dict.get('version', None)
        p2p_region = request_dict.get('p2p_region', None)
        tz = request_dict.get('tz', None)
        video_code = request_dict.get('video_code', None)
        ip = CommonService.get_ip_address(request)
        channel = request_dict.get('channel', None)
        cloud_vod = request_dict.get('cloud_vod', None)
        push_status = request_dict.get('push_status', None)
        pwd = request_dict.get('pwd', None)
        resetTime = request_dict.get('resetTime', None)
        is_alexa = request_dict.get('is_alexa', None)

        us_qs = UidSetModel.objects.filter(uid=uid)
        # 更新
        nowTime = int(time.time())

        print('-------')
        print(resetTime)
        print('-------')
        qs_dict = {
            'updTime': nowTime,
            'ip': ip
        }
        if channel:
            qs_dict['channel'] = channel
        if p2p_region:
            qs_dict['p2p_region'] = p2p_region
        if ucode:
            qs_dict['ucode'] = ucode
        if version:
            qs_dict['version'] = version
        if tz:
            qs_dict['tz'] = tz
        if video_code:
            qs_dict['video_code'] = video_code
        if cloud_vod:
            qs_dict['cloud_vod'] = cloud_vod
        if push_status:
            qs_dict['detect_status'] = push_status
        if pwd:
            qs_dict['pwd'] = pwd
        if is_alexa:
            qs_dict['is_alexa'] = is_alexa
        if us_qs.exists():
            us_qs.update(**qs_dict)
            # 如果推送状态开启，返回推送url
            return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
        # 新增
        else:
            qs_dict['uid'] = uid
            qs_dict['addTime'] = nowTime
            UidSetModel.objects.create(**qs_dict)
            # 如果推送状态开启，返回推送url
            return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
    else:
        return JsonResponse(status=200, data={'code': 403, 'msg': 'error etk'})
