import re
import threading
import time
import traceback

import oss2
from django.db.models import Q
from django.views.generic.base import View

from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel, \
    iotdeviceInfoModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


class EquipmentManagerV2(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:
            response.lang = tko.lang
            userID = tko.userID
            # if operation == 'add':
            #     return self.do_add(userID, request_dict, response)
            if operation == 'query':
                return self.do_query(userID, request_dict, response)
            elif operation == 'query_reset':
                return self.do_query_reset(userID, request_dict, response)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_add(self, userID, request_dict, response, request):
        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)
        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()
                    # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
                    # # 判断是否有已绑定用户
                    # if is_bind:
                    #     return response.json(15)
                    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,
                            }
                            UidSetModel.objects.create(**uid_set_create_dict)
                        else:
                            us_qs.update(nickname=NickName)
                        pk = CommonService.getUserID(getUser=False)
                        userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
                                                 NickName=NickName, View_Account=View_Account,
                                                 View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex)
                        userDevice.save()
                    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',
                                                                        'data_joined', 'version',
                                                                        'isVod', 'isExist')
                        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)
                        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'})

    # 新查询设备字段
    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))

            if NickName:
                dvqs = dvqs.filter(NickName__icontains=NickName)
            if uid:
                dvqs = dvqs.filter(UID=uid)
            dvql = dvqs[(page - 1) * line:page * line]. \
                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('uid', 'version', 'nickname', 'ucode','detect_interval', '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'],
                    'is_human': us['is_human'],
                    'is_custom_voice': us['is_custom_voice'],
                }
            for p in dvls:
                # 新增云分配UID
                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['is_human'] = uv_dict[p_uid]['is_human']
                    p['is_custom_voice'] = uv_dict[p_uid]['is_custom_voice']
                    # 设备昵称 调用影子信息昵称，先阶段不可
                    if uv_dict[p_uid]['nickname']:
                        p['NickName'] = uv_dict[p_uid]['nickname']
                else:
                    # 设备版本号
                    p['uid_version'] = ''
                    p['ucode'] = ''
                    p['detect_interval'] = ''
                data.append(p)
            return response.json(0, data)
        else:
            return response.json(tko.code)

    # 新查询设备字段

    def do_query_reset(self, userID, request_dict, response):
        dvqs = Device_Info.objects.filter(userID_id=userID, 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'])

        # 新增获取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('channel', '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'],
                    '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['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

        return response.json(0, result)
