import re
import threading
import time
import traceback

import requests

from Controller.CheckUserData import RandomStr
import oss2, base64
from django.db.models import Q
from django.views.generic.base import View

from Controller.DeviceConfirmRegion import Device_Region
from Object.RedisObject import RedisObject
from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, BASE_DIR
from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel, \
    Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UIDMainUser
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
import time, json


class EquipmentManagerV3(View):

    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()
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        if tko.code != 0:
            return response.json(tko.code)
        response.lang = tko.lang
        userID = tko.userID
        # 手机端添加设备，查询，修改
        if operation == 'add':
            return self.do_add(userID, request_dict, response, request)
        elif operation == 'query':
            return self.do_query(userID, request_dict, response)
        elif operation == 'modify':
            return self.do_modify(userID, request_dict, response, request)
        elif operation == 'modifyChannelName':
            return self.do_modify_channel_name(userID, request_dict, response, request)
        elif operation == 'fuzzyQuery':
            return self.do_fuzzy_query(userID, request_dict, response)
        elif operation == 'mainUserDevice':
            return self.do_mainUserDevice( request_dict, response)
        elif operation == 'getDeviceFeatures':
            return self.do_get_device_features(request_dict, response)
        else:
            return response.json(414)

    def do_add(self, userID, request_dict, response, request):
        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', '')
        encrypt_pass = View_Password
        print("准备解密")
        View_Password = self.decode_pwd(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 not all([UID, NickName, View_Account, Type, ChannelIndex]):  # Type和ChannelIndex可能为0
            return response.json(444, {'param': 'UID, NickName, View_Account, Type, ChannelIndex'})

        Type = int(Type)
        ChannelIndex = int(ChannelIndex)

        re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
        if not re_uid.match(UID):
            return response.json(444, {'param': 'UID'})

        device_info_qs = Device_Info.objects.filter(UID=UID, userID_id=userID)
        if device_info_qs:
            # 判断设备是否已存在
            if device_info_qs[0].isExist == 1:
                return response.json(174)
            else:
                device_info_qs.delete()

        id = 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

        # 判断是否有已绑定用户
        if isCheckMainUser == '1' and isusermain:
            res = {
                'id': id,
                '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 us_qs.exists():
                us_qs.update(nickname=NickName)
                UidSet_id = us_qs.first().id
            else:
                ip = CommonService.get_ip_address(request)
                region_id = Device_Region().get_device_region(ip)
                region_alexa = 'CN' if region_id == 1 else 'ALL'
                uid_set_create_dict = {
                    'uid': UID,
                    'addTime': nowTime,
                    'updTime': nowTime,
                    'ip': CommonService.get_ip_address(request_dict),
                    'channel': ChannelIndex,
                    'nickname': NickName,
                    'version': version,
                    'region_alexa': region_alexa,
                }
                UidSet = UidSetModel.objects.create(**uid_set_create_dict)
                UidSet_id = UidSet.id

            # 查询uid_channel表有无该uid的数据
            uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
            if not uid_channel_set.exists():
                # 多通道设备设置通道名
                multi_channel_list = [1, 2, 3, 4, 10001]
                if Type in multi_channel_list:
                    UidChannelSet_bulk = []
                    for i in range(1, ChannelIndex+1):
                        channel_name = 'channel'+str(i)  # channel1,channel2...
                        UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
                        UidChannelSet_bulk.append(UidChannelSet)
                    UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)

            userDevice = Device_Info(id=id, 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 not us_qs.exists():
                us_qs = UidSetModel.objects.filter(uid=UID)

            if us_qs.exists() and us_qs[0].is_alexa == 1:
                asy = threading.Thread(target=ModelService.notify_alexa_add,
                                       args=(UID, userID, NickName, encrypt_pass))
                asy.start()

        except Exception as e:
            return response.json(10, repr(e))
        else:
            dvqs = Device_Info.objects.filter(id=id).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)

            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
                }

            return response.json(0, res)


    def do_modify(self, userID, request_dict, response, request):
        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)
        deviceData = None
        dev_info_qs = None
        try:
            # deviceData = json.loads(deviceContent)
            deviceData = eval(deviceContent)
            if deviceData.__contains__('userID_id'):
                asy = threading.Thread(target=ModelService.update_log,
                                       args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
                asy.start()
                return response.json(10, '110')

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

            # print(deviceData['View_Password'])
            if deviceData.__contains__('View_Password'):
                encrypt_pwd = deviceData['View_Password']
                deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
            dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
            dev_info_qs.update(**deviceData)
        except Exception as e:
            print(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
                nickname = qs[0].NickName
                # 增加设备影子信息修改昵称 start
                us_qs = UidSetModel.objects.filter(uid=uid)
                if us_qs.exists():
                    if deviceData.__contains__('NickName'):
                        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)
                di_qs = Device_Info.objects.filter(UID=uid)
                di_qs.update(NickName=nickname)
                if deviceData is not None and deviceData.__contains__('NickName') and us_qs[0].is_alexa == 1:
                    password = encrypt_pwd if deviceData.__contains__('View_Password') else ''
                    asy = threading.Thread(target=ModelService.notify_alexa_add, args=(uid, userID, nickname, password))
                    asy.start()
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            return response.json(0, res)

    # 编辑通道名
    def do_modify_channel_name(self, userID, request_dict, response):
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        channel_name = request_dict.get('channel_name', None)
        if not all([uid, channel, channel_name]):
            return response.json(444)
        # 更新通道名
        UidChannelSetModel.objects.filter(uid__uid=uid).update(channel_name=channel_name)
        return response.json(0)

    # 新查询设备字段
    def do_query(self, userID, request_dict, response):
        token = request_dict.get('token', None)
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        NickName = request_dict.get('NickName', None)
        if not token or not page or not line:
            return response.json(444)

        page = int(page)
        line = int(line)
        uid = request_dict.get('uid', None)
        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))
            dvql = dvqs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
                               'View_Password', 'ChannelIndex', 'Type', 'isShare',
                               'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID', 'vodPrimaryMaster',
                               'userID__userEmail',
                               'version', '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('id', 'uid', 'version', 'nickname', 'ucode',
                                                                        'detect_status', 'detect_group',
                                                                        'detect_interval',
                                                                        'region_alexa', 'is_alexa', 'deviceModel',
                                                                        'TimeZone', 'TimeStatus', 'SpaceUsable',
                                                                        'SpaceSum', 'MirrorType', 'RecordType',
                                                                        'OutdoorModel', 'WIFIName', 'isDetector',
                                                                        'DetectorRank', 'is_human', 'is_custom_voice')
            uv_dict = {}
            for us in us_qs:
                uv_dict[us['uid']] = {
                    'version': us['version'],
                    'nickname': us['nickname'],
                    'ucode': us['ucode'],
                    'detect_interval': us['detect_interval'],
                    'detect_group': us['detect_group'],
                    'detect_status': us['detect_status'],
                    'region_alexa': us['region_alexa'],
                    'is_alexa': us['is_alexa'],
                    'deviceModel': us['deviceModel'],
                    'TimeZone': us['TimeZone'],
                    'TimeStatus': us['TimeStatus'],
                    'SpaceUsable': us['SpaceUsable'],
                    'SpaceSum': us['SpaceSum'],
                    'MirrorType': us['MirrorType'],
                    'RecordType': us['RecordType'],
                    'OutdoorModel': us['OutdoorModel'],
                    'WIFIName': us['WIFIName'],
                    'isDetector': us['isDetector'],
                    'DetectorRank': us['DetectorRank'],
                    'is_human': us['is_human'],
                    'is_custom_voice': us['is_custom_voice']
                }
                # 从uid_channel里面取出通道配置信息
                ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values('channel', 'channel_name',
                                                                                    'pir_audio', 'mic_audio',
                                                                                    'battery_status', 'battery_level',
                                                                                    'sleep_status', 'sleep_time',
                                                                                    'light_night_model',
                                                                                    'light_alarm_type',
                                                                                    'light_alarm_level',
                                                                                    'light_alarm_man_en',
                                                                                    'light_alarm_vol',
                                                                                    'light_long_light'
                                                                                    )
                channels = []
                for ucs in ucs_qs:
                    channels_dict = {
                        'channel': ucs['channel'],
                        'channel_name': ucs['channel_name'],
                        'pir_audio': ucs['pir_audio'],
                        'mic_audio': ucs['mic_audio'],
                        'battery_status': ucs['battery_status'],
                        'battery_level': ucs['battery_level'],
                        'sleep_status': ucs['sleep_status'],
                        'sleep_time': ucs['sleep_time'],
                        'light_night_model': ucs['light_night_model'],
                        'light_alarm_type': ucs['light_alarm_type'],
                        'light_alarm_level': ucs['light_alarm_level'],
                        'light_alarm_man_en': ucs['light_alarm_man_en'],
                        'light_alarm_vol': ucs['light_alarm_vol'],
                        'light_long_light': ucs['light_long_light']
                    }
                    channels.append(channels_dict)
                uv_dict[us['uid']]['channels'] = channels

            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['ucode'] = uv_dict[p_uid]['ucode']
                    p['detect_interval'] = uv_dict[p_uid]['detect_interval']
                    p['detect_status'] = uv_dict[p_uid]['detect_status']
                    p['detect_group'] = uv_dict[p_uid]['detect_group']
                    p['region_alexa'] = uv_dict[p_uid]['region_alexa']
                    p['is_alexa'] = uv_dict[p_uid]['is_alexa']
                    p['deviceModel'] = uv_dict[p_uid]['deviceModel']
                    p['TimeZone'] = uv_dict[p_uid]['TimeZone']
                    p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
                    p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
                    p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
                    p['MirrorType'] = uv_dict[p_uid]['MirrorType']
                    p['RecordType'] = uv_dict[p_uid]['RecordType']
                    p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
                    p['WIFIName'] = uv_dict[p_uid]['WIFIName']
                    p['isDetector'] = uv_dict[p_uid]['isDetector']
                    p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
                    p['is_human'] = uv_dict[p_uid]['is_human']
                    p['is_custom_voice'] = uv_dict[p_uid]['is_custom_voice']
                    p['channels'] = uv_dict[p_uid]['channels']
                    # 设备昵称 调用影子信息昵称，先阶段不可
                    if uv_dict[p_uid]['nickname']:
                        p['NickName'] = uv_dict[p_uid]['nickname']
                else:
                    # 设备版本号
                    p['uid_version'] = ''
                    p['ucode'] = ''
                data.append(p)
            result = data

            if NickName:
                # print('NickName搜索缓存')
                data = []
                for index, item in enumerate(result):
                    if NickName == item['NickName']:
                        # 加密
                        item['View_Password'] = self.encrypt_pwd(item['View_Password'])
                        data.append(item)
                        return response.json(0, data)
            if uid:
                # print('uid搜索缓存')
                data = []
                for index, item in enumerate(result):
                    if uid == item['UID']:
                        # 加密
                        item['View_Password'] = self.encrypt_pwd(item['View_Password'])
                        data.append(item)
                        return response.json(0, data)
            items = []
            # print('缓存分页')
            for index, item in enumerate(result):
                if (page - 1) * line <= index:
                    if index < page * line:
                        # 加密
                        item['View_Password'] = self.encrypt_pwd(item['View_Password'])
                        print(item)
                        items.append(item)
            print(items)
            return response.json(0, items)
        else:
            return response.json(tko.code)

    def do_fuzzy_query(self, userID, request_dict, response):
        fuzzy = request_dict.get('fuzzy', None)
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)

        if page and line:
            page = int(page)
            line = int(line)
            device_qs = Device_Info.objects.filter(userID=userID)
            device_qs = device_qs.filter(~Q(isExist=2))
            if device_qs.exists():
                if fuzzy:
                    device_qs = device_qs.filter(Q(UID__contains=fuzzy) | Q(NickName__contains=fuzzy))

                device_qs = device_qs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
                                             'View_Password', 'ChannelIndex', 'Type', 'isShare',
                                             'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID',
                                             'vodPrimaryMaster', 'userID__userEmail',
                                             'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'serial_number')

                dvls = CommonService.qs_to_list(device_qs)
                uid_list = []
                serial_number_list = []
                for dvl in dvls:
                    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('id', 'uid', 'version', 'nickname', 'ucode',
                                                                            'detect_status', 'detect_group',
                                                                            'detect_interval',
                                                                            'region_alexa', 'is_alexa', 'deviceModel',
                                                                            'TimeZone', 'TimeStatus', 'SpaceUsable',
                                                                            'SpaceSum', 'MirrorType', 'RecordType',
                                                                            'OutdoorModel', 'WIFIName', 'isDetector',
                                                                            'DetectorRank')
                uv_dict = {}
                for us in us_qs:
                    uv_dict[us['uid']] = {
                        'version': us['version'],
                        'nickname': us['nickname'],
                        'ucode': us['ucode'],
                        'detect_interval': us['detect_interval'],
                        'detect_group': us['detect_group'],
                        'detect_status': us['detect_status'],
                        'region_alexa': us['region_alexa'],
                        'is_alexa': us['is_alexa'],
                        'deviceModel': us['deviceModel'],
                        'TimeZone': us['TimeZone'],
                        'TimeStatus': us['TimeStatus'],
                        'SpaceUsable': us['SpaceUsable'],
                        'SpaceSum': us['SpaceSum'],
                        'MirrorType': us['MirrorType'],
                        'RecordType': us['RecordType'],
                        'OutdoorModel': us['OutdoorModel'],
                        'WIFIName': us['WIFIName'],
                        'isDetector': us['isDetector'],
                        'DetectorRank': us['DetectorRank']
                    }
                    # 从uid_channel里面取出通道配置信息
                    ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
                    channels = []
                    for ucs in ucs_qs:
                        channel = {
                            'channel': ucs['channel'],
                            'channel_name': ucs['channel_name'],
                            'pir_audio': ucs['pir_audio'],
                            'mic_audio': ucs['mic_audio'],
                            'battery_status': ucs['battery_status'],
                            'battery_level': ucs['battery_level'],
                            'sleep_status': ucs['sleep_status'],
                            'sleep_time': ucs['sleep_time'],
                            'light_night_model': ucs['light_night_model'],
                            'light_alarm_type': ucs['light_alarm_type'],
                            'light_alarm_level': ucs['light_alarm_level'],
                            'light_alarm_man_en': ucs['light_alarm_man_en'],
                            'light_alarm_vol': ucs['light_alarm_vol'],
                            'light_long_light': ucs['light_long_light']
                        }
                        channels.append(channel)
                    uv_dict[us['uid']]['channels'] = channels

                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['ucode'] = uv_dict[p_uid]['ucode']
                        p['detect_interval'] = uv_dict[p_uid]['detect_interval']
                        p['detect_status'] = uv_dict[p_uid]['detect_status']
                        p['detect_group'] = uv_dict[p_uid]['detect_group']
                        p['region_alexa'] = uv_dict[p_uid]['region_alexa']
                        p['is_alexa'] = uv_dict[p_uid]['is_alexa']
                        p['deviceModel'] = uv_dict[p_uid]['deviceModel']
                        p['TimeZone'] = uv_dict[p_uid]['TimeZone']
                        p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
                        p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
                        p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
                        p['MirrorType'] = uv_dict[p_uid]['MirrorType']
                        p['RecordType'] = uv_dict[p_uid]['RecordType']
                        p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
                        p['WIFIName'] = uv_dict[p_uid]['WIFIName']
                        p['isDetector'] = uv_dict[p_uid]['isDetector']
                        p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
                        p['channels'] = uv_dict[p_uid]['channels']
                        # 设备昵称 调用影子信息昵称，先阶段不可
                        if uv_dict[p_uid]['nickname']:
                            p['NickName'] = uv_dict[p_uid]['nickname']
                    else:
                        # 设备版本号
                        p['uid_version'] = ''
                        p['ucode'] = ''
                    data.append(p)
                result = data
                items = []
                # print('缓存分页')
                for index, item in enumerate(result):
                    if (page - 1) * line <= index:
                        if index < page * line:
                            # 加密
                            item['View_Password'] = self.encrypt_pwd(item['View_Password'])
                            print(item)
                            items.append(item)
                print(items)
                return response.json(0, items)
            else:
                return response.json(0, [])
        else:
            return response.json(444)

    # 加密
    def encrypt_pwd(self, userPwd):
        for i in range(1, 4):
            if i == 1:
                userPwd = RandomStr(3, False) + userPwd + RandomStr(3, False)
                userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
            if i == 2:
                userPwd = RandomStr(2, False) + str(userPwd) + RandomStr(2, False)
                userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
            if i == 3:
                userPwd = RandomStr(1, False) + str(userPwd) + RandomStr(1, False)
                userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
        return userPwd

    # 解密
    def decode_pwd(self, password):
        for i in range(1, 4):
            if i == 1:
                # 第一次先解密
                password = base64.b64decode(password)
                password = password.decode('utf-8')
                # 截去第一位，最后一位
                password = password[1:-1]
            if i == 2:
                # 第2次先解密
                password = base64.b64decode(password)
                password = password.decode('utf-8')
                # 去前2位，后2位
                password = password[2:-2]
            if i == 3:
                # 第3次先解密
                password = base64.b64decode(password)
                password = password.decode('utf-8')
                # 去前3位，后3位
                password = password[3:-3]
        return password

    def do_mainUserDevice(self, request_dict, response):
        UID = request_dict.get('UID')
        dvq = Device_Info.objects.filter(UID=UID)
        dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
        qs = {}
        if dvq.exists():
            qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username',
                                                                                      'userEmail', 'phone')
            NickName = qs[0]['username']
            userEmail = qs[0]['userEmail']
            phone = qs[0]['phone']
            username = qs[0]['username']
            qs = CommonService.qs_to_list(qs)
            if NickName == '':
                qs[0]['NickName'] = username

            # if userEmail == '':
            #     qs[0]['userEmail'] = NickName

            if phone == '':
                qs[0]['phone'] = NickName

        # if not qs:
        #     uidq = UIDMainUser.objects.filter(UID=UID).values('user_id')
        #     if uidq.exists():
        #         qs = Device_User.objects.filter(userID=uidq[0]['user_id']).values('userID', 'NickName', 'username', 'userEmail', 'phone')
        #         qs = CommonService.qs_to_list(qs)

        return response.json(0, qs)

    def do_get_device_features(self, request_dict, response):
        uid = request_dict.get('uid', None)

        if uid:
            uid = CommonService.decode_data(uid)

            if uid:
                uid_qs = UidSetModel.objects.filter(uid=uid)
                if uid_qs.exists():
                    uid_qs = uid_qs.values('is_alexa', 'is_human', 'is_custom_voice', 'double_wifi')
                    return response.json(0, uid_qs[0])
                else:
                    return response.json(173)
            else:
                return response.json(444)

        else:
            return response.json(444)
