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
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',
                       'version',
                       'isVod', 'isExist', 'NotificationMode')
            dvls = CommonService.qs_to_list(dvql)
            uid_list = []
            for dvl in dvls:
                uid_list.append(dvl['UID'])
                # if dvl['isShare'] is False:
                #     uid_list.append(dvl['UID'])
            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')
            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']}
            for p in dvls:
                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']
                    # 设备昵称 调用影子信息昵称，先阶段不可
                    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', 'NickName', 'UID', 'ChannelIndex', 'Type', 'isShare')
        res = CommonService.qs_to_list(dvql)
        return response.json(0, res)
