#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import operator
import time

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

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
    AWS_SES_ACCESS_REGION, UNUSED_SERIAL_REDIS_LIST
from Model.models import Device_Info, UidSetModel, LogModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
    VodHlsModel, ExperienceContextModel, DeviceTypeModel, Equipment_Info, UidUserModel, ExperienceAiModel, AiService, \
    AppBundle, App_Info, AppDeviceType, DeviceNameLanguage, AppVersionNumber, UIDCompanySerialModel, UIDModel, \
    CompanySerialModel, UidPushModel
from Object.AWS.AmazonS3Util import AmazonS3Util
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.EquipmentInfoService import EquipmentInfoService
from Service.ModelService import ModelService
from Service.VodHlsService import SplitVodHlsObject


class DeviceManagement(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):
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        if operation == 'addDeviceType':
            return self.addDeviceType(request, request_dict, response)
        elif operation == 'delDeviceData':  # 删除设备数据
            return self.del_device_data(request_dict, response)
        elif operation == 'getDeviceIcon':  # app获取设备图标
            response = ResponseObject(language)
            return self.get_device_icon(request_dict, response)
        elif operation == 'addAppDeviceType':  # 添加app设备类型数据并上传图标
            return self.add_app_device_type(request_dict, response, request)
        else:
            tko = TokenObject(
                request.META.get('HTTP_AUTHORIZATION'),
                returntpye='pc')
            if tko.code != 0:
                return response.json(tko.code)
            response.lang = tko.lang
            userID = tko.userID
            if not userID:
                return response.json(444, 'userID')
            if operation == 'getDeviceInfoList':  # 获取设备信息数据
                return self.get_device_info_list(request_dict, response)
            elif operation == 'deleteDevice':
                return self.deleteDevice(request_dict, response)
            elif operation == 'resetVod':  # 重置云存
                return self.resetVod(request, request_dict, response)
            elif operation == 'resetAi':  # 重置AI
                return self.reset_ai(request, request_dict, response)
            elif operation == 'resetPrimaryUser':
                return self.resetPrimaryUser(request, request_dict, response)
            elif operation == 'getDeviceTypeList':
                return self.getDeviceTypeList(request_dict, response)
            elif operation == 'deleteDeviceType':
                return self.deleteDeviceType(request_dict, response)
            elif operation == 'getAppDeviceTypeList':  # 获取app设备类型数据
                return self.get_app_device_type_list(request_dict, response)
            elif operation == 'getAppBundleIdList':  # 获取app包id数据
                return self.get_app_bundle_id_list(response)
            elif operation == 'editAppDeviceType':  # 编辑app设备类型数据
                return self.edit_app_device_type(request_dict, response)
            elif operation == 'deleteAppDeviceType':  # 删除app设备类型数据
                return self.delete_app_device_type(request_dict, response)
            elif operation == 'getAppBundle':  # 获取app版本包
                return self.get_app_bundle(response)
            elif operation == 'resetAll':  # 重置设备主用户/云存/AI
                return self.reset_all(request, request_dict, response)
            else:
                return response.json(444, 'operation')

    @classmethod
    def get_app_bundle(cls, response):
        """
        获取app版本id
        """
        app_bundle_qs = AppBundle.objects.all().values('id', 'app_bundle_id')
        if not app_bundle_qs.exists():
            return response.json(0)
        app_bundle_list = []
        for app_bundle in app_bundle_qs:
            app_bundle_qs.exists()
            app_bundle_list.append(app_bundle)
        return response.json(0, app_bundle_list)

    @classmethod
    def get_device_info_list(cls, request_dict, response):
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        UID = request_dict.get('UID', None)
        serialNumber = request_dict.get('serialNumber', None)
        NickName = request_dict.get('NickName', None)
        username = request_dict.get('username', None)
        version = request_dict.get('version', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)

        try:
            if any([UID, serialNumber, NickName, username, version]):  # 条件查询
                if UID:
                    device_info_qs = Device_Info.objects.filter(UID__icontains=UID)
                if serialNumber:
                    device_info_qs = Device_Info.objects.filter(serial_number__icontains=serialNumber[:9])
                if NickName:
                    device_info_qs = Device_Info.objects.filter(NickName__icontains=NickName)
                if username:
                    device_info_qs = Device_Info.objects.filter(Q(userID__username__icontains=username) |
                                                                Q(userID__userEmail__icontains=username) |
                                                                Q(userID__phone__icontains=username))
                if version:
                    uid_list = UidSetModel.objects.filter(version__icontains=version).values_list('uid', flat=True)
                    device_info_qs = Device_Info.objects.filter(UID__in=uid_list)
                total = device_info_qs.count()
                if not total:
                    return response.json(0, {'list': {}, 'total': 0})
                device_info_qs = device_info_qs[(page - 1) * line:page * line]
            else:  # 查询全部
                total = Device_Info.objects.filter().count()
                device_info_qs = Device_Info.objects.filter()[(page - 1) * line:page * line]
                if not device_info_qs.exists():
                    return response.json(0, {'list': {}, 'total': 0})

            device_info_list = CommonService.qs_to_dict(device_info_qs)
            for k, v in enumerate(device_info_list["datas"]):
                for device_info in device_info_qs:
                    if v['pk'] == device_info.id:
                        # 设备的用户名和主用户
                        username = ModelService.get_user_name(device_info_list["datas"][k]['fields']['userID'])
                        device_info_list["datas"][k]['fields']['username'] = username
                        device_info_list["datas"][k]['fields']['vodPrimaryMaster'] = \
                            device_info_list["datas"][k]['fields']['vodPrimaryMaster']
                        # 是否支持移动侦测
                        iSNotification = '开' if device_info_list["datas"][k]['fields']['iSNotification'] == 1 else '关'
                        device_info_list["datas"][k]['fields']['iSNotification'] = iSNotification
                        # 设备类型,是否支持Alexa和ip
                        type = device_info_list["datas"][k]['fields']['Type']
                        device_type_qs = DeviceTypeModel.objects.filter(type=type).values('name')
                        if device_type_qs.exists():
                            device_info_list["datas"][k]['fields']['Type'] = device_type_qs[0]['name']
                        uid_set_qs = UidSetModel.objects.filter(
                            uid=device_info_list["datas"][k]['fields']['UID']).values('is_alexa', 'ip', 'version',
                                                                                      'is_ai', 'is_human', 'cloud_vod',
                                                                                      'ucode', 'device_type')
                        if uid_set_qs.exists():
                            isAlexa = '是' if uid_set_qs[0]['is_alexa'] else '否'
                            isHuman = '是' if uid_set_qs[0]['is_human'] else '否'
                            cloud_vod = CommonService.is_cloud_device(uid_set_qs[0]['ucode'],
                                                                      uid_set_qs[0]['device_type'])
                            if cloud_vod:
                                cloud_vod = '支持'
                            else:
                                cloud_vod = '不支持'
                            if uid_set_qs[0]['is_ai'] == 2:
                                isAI = '不支持'
                            elif uid_set_qs[0]['is_ai'] == 1:
                                isAI = '开启'
                            else:
                                isAI = '关闭'
                            device_info_list["datas"][k]['fields']['isHuman'] = isHuman
                            device_info_list["datas"][k]['fields']['isAI'] = isAI
                            device_info_list["datas"][k]['fields']['isAlexa'] = isAlexa
                            device_info_list["datas"][k]['fields']['cloudVod'] = cloud_vod
                            device_info_list["datas"][k]['fields']['ip'] = uid_set_qs[0]['ip']
                            device_info_list["datas"][k]['fields']['version'] = uid_set_qs[0]['version']
                        uid_bucket_qs = UID_Bucket.objects.filter(
                            uid=device_info_list["datas"][k]['fields']['UID']).values('status')
                        #  0是关闭，1是开启
                        if uid_bucket_qs.exists():
                            res = []
                            for uid_bucket in uid_bucket_qs:
                                status = uid_bucket['status']
                                res.append(status)
                            if 1 in res:
                                device_info_list["datas"][k]['fields']['status'] = 1
                            else:
                                device_info_list["datas"][k]['fields']['status'] = 0
                        else:
                            device_info_list["datas"][k]['fields']['status'] = 0
            return response.json(0, {'list': device_info_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 根据id删除设备
    def deleteDevice(self, request_dict, response):
        deviceID = request_dict.get('deviceID', None)
        userID = request_dict.get('userID', None)
        uid = request_dict.get('uid', None)
        if not all([deviceID, userID, uid]):
            return response.json(444)

        try:
            with transaction.atomic():
                Device_Info.objects.filter(id=deviceID).delete()
                UidPushModel.objects.filter(uid_set__uid=uid).delete()
                # 删除推送消息
                for val in range(1, 8):
                    EquipmentInfoService.get_equipment_info_model('', val). \
                        filter(device_user_id=userID, device_uid=uid).delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 重置设备主用户
    def resetPrimaryUser(self, request, request_dict, response):
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(404)
        try:
            # 记录操作日志
            ip = CommonService.get_ip_address(request)
            content = json.loads(json.dumps(request_dict))
            log = {
                'ip': ip,
                'user_id': 2,
                'status': 200,
                'time': int(time.time()),
                'url': 'deviceManagement/resetPrimaryUser',
                'content': json.dumps(content),
                'operation': '{}重置设备主用户'.format(uid),
            }
            LogModel.objects.create(**log)
            Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 重置设备云存
    def resetVod(self, request, request_dict, response):
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(444)
        try:
            # 记录操作日志
            ip = CommonService.get_ip_address(request)
            content = json.loads(json.dumps(request_dict))
            log = {
                'ip': ip,
                'user_id': 2,
                'status': 200,
                'time': int(time.time()),
                'url': 'deviceManagement/resetVod',
                'content': json.dumps(content),
                'operation': '{}重置云存'.format(uid),
            }
            with transaction.atomic():
                LogModel.objects.create(**log)
                # 删除和更新设备云存相关数据
                UID_Bucket.objects.filter(uid=uid).delete()
                Unused_Uid_Meal.objects.filter(uid=uid).delete()
                Order_Model.objects.filter(UID=uid, order_type=0).delete()
                StsCrdModel.objects.filter(uid=uid).delete()
                VodHlsModel.objects.filter(uid=uid).delete()
                # 删除vod_hls分表数据
                split_vod_hls_obj = SplitVodHlsObject()
                split_vod_hls_obj.del_vod_hls_data(uid=uid)
                ExperienceContextModel.objects.filter(uid=uid).delete()
                Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def reset_ai(request, request_dict, response):
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(444)
        try:
            # 记录操作日志
            ip = CommonService.get_ip_address(request)
            content = json.loads(json.dumps(request_dict))
            log = {
                'ip': ip,
                'user_id': 2,
                'status': 200,
                'time': int(time.time()),
                'url': 'deviceManagement/resetAi',
                'content': json.dumps(content),
                'operation': '{}重置AI'.format(uid),
            }
            with transaction.atomic():
                LogModel.objects.create(**log)
                # 删除和更新设备AI相关数据
                ExperienceAiModel.objects.filter(uid=uid).delete()
                AiService.objects.filter(uid=uid).delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 获取设备类型数据
    def getDeviceTypeList(self, request_dict, response):
        name = request_dict.get('name', None)
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)
        try:
            if name:
                device_type_qs = DeviceTypeModel.objects.filter(name__contains=name).values()
                total = len(device_type_qs)
            else:
                device_type_qs = DeviceTypeModel.objects.filter().values()[(page - 1) * line:page * line]
                total = DeviceTypeModel.objects.filter().count()
            if not device_type_qs.exists():
                return response.json(173)
            device_type_list = []
            for device_type in device_type_qs:
                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')

                icon = device_type['icon']
                url = 'device_type/' + icon
                device_type['icon'] = bucket.sign_url('GET', url, 3600)
                device_type_list.append(device_type)
            return response.json(0, {'list': device_type_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 删除设备类型
    def deleteDeviceType(self, request_dict, response):
        deviceTypeID = request_dict.get('deviceTypeID', None)
        if not deviceTypeID:
            return response.json(444)
        try:
            DeviceTypeModel.objects.filter(id=deviceTypeID).delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    # 添加设备类型
    def addDeviceType(self, request, request_dict, response):
        iconFile = request.FILES.get('iconFile', None)
        name = request_dict.get('name', None)
        model = request_dict.get('model', None)
        type = request_dict.get('type', None)
        ptz_type = request_dict.get('ptz_type', None)

        if not all([iconFile, name, model, type, ptz_type]):
            return response.json(444)
        try:
            model = int(model)
            ptz_type = int(ptz_type)
            icon = iconFile.name
            now_time = int(time.time())
            # 上传文件到阿里云OSS
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
            key = 'device_type/' + icon  # 图片文件存放于 device_type 目录下
            # https://oss.console.aliyun.com/bucket/oss-cn-shenzhen/ansjer-static-resources/object?path=device_type%2F
            bucket.put_object(key=key, data=iconFile)
            DeviceTypeModel.objects.create(name=name, model=model, type=type, ptz_type=ptz_type, icon=icon,
                                           add_time=now_time, update_time=now_time)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def del_device_data(request_dict, response):
        uidList = request_dict.get('uidList', None)
        delDataOptions = request_dict.get('delDataOptions', None)
        serialNumberList = request_dict.get('serialNumberList', None)
        if not all([uidList or serialNumberList, delDataOptions]):
            return response.json(444)
        try:
            with transaction.atomic():
                if uidList:
                    #  uid
                    uidList = uidList.splitlines()  # 按行('\r', '\r\n', \n')切割字符串返回列表
                else:
                    #  序列号
                    serialNumberList = serialNumberList.splitlines()  # 按行('\r', '\r\n', \n')切割字符串返回列表
                    serial_number_list = []
                    for serial_number in serialNumberList:
                        serial_number_list.append(serial_number[0:6])
                    uid_company_serial_qs = UIDCompanySerialModel.objects.filter(
                        company_serial__serial_number__in=serial_number_list).values('uid__uid')
                    uidList = [item[key] for item in uid_company_serial_qs for key in item]

                # 根据删除项删除相关数据
                if '设备信息数据' in delDataOptions:
                    Device_Info.objects.filter(UID__in=uidList).delete()
                    UidPushModel.objects.filter(uid_set__uid__in=uidList).delete()
                if '设备配置数据' in delDataOptions:
                    UidSetModel.objects.filter(uid__in=uidList).delete()
                if '设备推送数据' in delDataOptions:
                    Equipment_Info.objects.filter(devUid__in=uidList).delete()
                if '设备AP信息数据' in delDataOptions:
                    UidUserModel.objects.filter(UID__in=uidList).delete()
                if '设备AI数据' in delDataOptions:
                    ExperienceAiModel.objects.filter(uid__in=uidList).delete()
                    Order_Model.objects.filter(UID__in=uidList, order_type=1).delete()
                if '设备云存数据' in delDataOptions:
                    UID_Bucket.objects.filter(uid__in=uidList).delete()
                    StsCrdModel.objects.filter(uid__in=uidList).delete()
                    VodHlsModel.objects.filter(uid__in=uidList).delete()
                    # 删除vod_hls分表数据
                    split_vod_hls_obj = SplitVodHlsObject()
                    split_vod_hls_obj.del_vod_hls_data(uid__in=uidList)
                    Unused_Uid_Meal.objects.filter(uid__in=uidList).delete()
                    ExperienceContextModel.objects.filter(uid__in=uidList).delete()
                    Order_Model.objects.filter(UID__in=uidList, order_type=0).delete()
                    Device_Info.objects.filter(UID__in=uidList).update(vodPrimaryUserID='', vodPrimaryMaster='')

                # 上传序列号文件且选中序列号解绑uid
                if serialNumberList is not None and '序列号解绑uid' in delDataOptions:
                    # 解绑uid数据
                    UIDModel.objects.filter(uid__in=uidList).update(status=0)
                    UIDCompanySerialModel.objects.filter(uid__uid__in=uidList).delete()
                    CompanySerialModel.objects.filter(serial_number__in=serial_number_list).update(status=1)
                    UidPushModel.objects.filter(uid_set__uid__in=uidList).delete()
                    # 序列号加入重置状态redis列表
                    redis_obj = RedisObject()
                    for serial in serial_number_list:
                        redis_obj.rpush(UNUSED_SERIAL_REDIS_LIST, serial)

                # 记录日志
                content = json.loads(json.dumps(request_dict))
                device_list = uidList if serialNumberList is None else serial_number_list
                log = {
                    'user_id': 2,
                    'status': 200,
                    'time': int(time.time()),
                    'url': 'deviceManagement/delDeviceData',
                    'content': json.dumps(content),
                    'operation': '删除数据的设备列表:{}'.format(device_list),
                }
                LogModel.objects.create(**log)

            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def get_app_device_type_list(request_dict, response):
        app_bundle_id = request_dict.get('app_bundle_id', None)
        lang = request_dict.get('lang', 'cn')
        model = request_dict.get('model', None)
        type = request_dict.get('type', None)
        name = request_dict.get('name', None)

        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)

        try:
            if not app_bundle_id:
                app_bundle_id = 'com.ansjer.zccloud'
            app_bundle_qs = AppBundle.objects.filter(app_bundle_id=app_bundle_id)
            if lang:
                app_bundle_qs = app_bundle_qs.filter(app_device_type__devicenamelanguage__lang=lang)

            app_bundle_qs = app_bundle_qs.annotate(
                model=F('app_device_type__model'), type=F('app_device_type__type'), icon=F('app_device_type__icon'),
                lang=F('app_device_type__devicenamelanguage__lang'),
                name=F('app_device_type__devicenamelanguage__name'),
                sort=F('app_device_type__devicenamelanguage__sort')).values('id', 'app_device_type__id', 'model',
                                                                            'type', 'icon',
                                                                            'app_device_type__devicenamelanguage__id',
                                                                            'lang', 'name', 'sort',
                                                                            'app_device_type__app_version_number_id').order_by(
                'app_device_type__devicenamelanguage__sort')
            if not app_bundle_qs.exists():
                return response.json(0)
            app_bundle_qs = app_bundle_qs.all()
            if name:
                app_bundle_qs = app_bundle_qs.filter(name=name)
            if model:
                app_bundle_qs = app_bundle_qs.filter(model=model)
            if type:
                app_bundle_qs = app_bundle_qs.filter(type=type)
            total = app_bundle_qs.count()
            app_bundle_qs = app_bundle_qs[(page - 1) * line:page * line]
            app_device_type_list = []
            for app_bundle in app_bundle_qs:
                app_bundle['version_number'] = app_bundle.pop('app_device_type__app_version_number_id')
                app_device_type_list.append(app_bundle)
            return response.json(0, {'list': app_device_type_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def get_app_bundle_id_list(response):
        try:
            app_info_qs = App_Info.objects.filter().values('id', 'appBundleId', 'appName')
            appBundleIdList = list(app_info_qs)
            return response.json(0, {'list': appBundleIdList})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def edit_app_device_type(request_dict, response):
        # app_device_type表数据
        app_device_type_id = request_dict.get('app_device_type__id', None)
        model = request_dict.get('model', None)
        type = request_dict.get('type', None)
        icon = request_dict.get('icon', None)
        # device_name_language表数据
        device_name_language_id = request_dict.get('app_device_type__devicenamelanguage__id', None)
        lang = request_dict.get('lang', None)
        name = request_dict.get('name', None)
        sort = request_dict.get('sort', None)

        if not all([app_device_type_id, model, type, icon, device_name_language_id, lang, name, sort]):
            return response.json(444)

        try:
            with transaction.atomic():
                AppDeviceType.objects.filter(id=app_device_type_id).update(model=model, type=type, icon=icon)
                DeviceNameLanguage.objects.filter(id=device_name_language_id).update(lang=lang, name=name, sort=sort)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def delete_app_device_type(request_dict, response):
        app_bundle_id = request_dict.get('appBundleId', None)
        app_device_type_id = request_dict.get('appDeviceTypeId', None)
        if not all([app_bundle_id, app_device_type_id]):
            return response.json(444)
        try:
            app_bundle_qs = AppBundle.objects.get(id=app_bundle_id)
            app_device_type_qs = AppDeviceType.objects.filter(id=app_device_type_id)
            app_bundle_qs.app_device_type.remove(*app_device_type_qs)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def reset_all(request, request_dict, response):
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(444)
        try:
            # 记录操作日志
            ip = CommonService.get_ip_address(request)
            content = json.loads(json.dumps(request_dict))
            with transaction.atomic():
                # 删除主用户
                Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
                # 删除云存
                UID_Bucket.objects.filter(uid=uid).delete()
                Unused_Uid_Meal.objects.filter(uid=uid).delete()
                Order_Model.objects.filter(UID=uid, order_type=0).delete()
                StsCrdModel.objects.filter(uid=uid).delete()
                VodHlsModel.objects.filter(uid=uid).delete()
                # 删除vod_hls分表数据
                split_vod_hls_obj = SplitVodHlsObject()
                split_vod_hls_obj.del_vod_hls_data(uid=uid)
                ExperienceContextModel.objects.filter(uid=uid).delete()
                # 删除AI
                ExperienceAiModel.objects.filter(uid=uid).delete()
                AiService.objects.filter(uid=uid).delete()
                log = {
                    'ip': ip,
                    'user_id': 2,
                    'status': 200,
                    'time': int(time.time()),
                    'url': 'deviceManagement/resetAll',
                    'content': json.dumps(content),
                    'operation': '{}重置所有'.format(uid),
                }
                LogModel.objects.create(**log)
                return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def add_app_device_type(request_dict, response, request):
        """
        添加app设备类型数据并上传图标
        @param request_dict: 请求参数
        @request_dict lang: 语言
        @request_dict app_bundle_id: app包id
        @request_dict version_number: app版本号
        @request_dict model: 设备类型
        @request_dict type: 设备型号
        @request_dict name: 设备名称
        @request_dict sort: 升序排序
        @request_dict file: 文件
        @param response: 响应对象
        @return:
        """
        # 添加APP设备类型
        app_bundle_id = request_dict.get(
            'app_bundle_id', '')[
                        1:-1].split(',')  # '[1,2]' -> ['1','2']
        # 版本号
        version_number = request_dict.get('version_number', None)
        # app_device_type表数据
        model = request_dict.get('model', None)
        type = request_dict.get('type', None)
        # device_name_language表数据
        name = request_dict.get('name', None)
        sort = request_dict.get('sort', None)
        # 上传图标
        file = request.FILES.get('iconFile', None)
        if not all([model, type, name, sort, version_number, file]):
            return response.json(444, 'model, type, file, name, sort, version_number')
        fileName = file.name
        type = int(type)
        data_name = eval(name)
        try:
            with transaction.atomic():
                for k, v in data_name.items():
                    app_bundle_qs = AppBundle.objects.filter(id__in=app_bundle_id,
                                                             app_device_type__devicenamelanguage__lang=k,
                                                             app_device_type__app_version_number_id=version_number,
                                                             app_device_type__type=type,
                                                             app_device_type__model=model)
                    #  数据是否重复
                    if app_bundle_qs.exists():
                        return response.json(174)
                    # 是否存在相同的url
                    response_url = 'https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/' + format(
                        fileName)
                    app_bundle_qs = AppDeviceType.objects.filter(appbundle__id__in=app_bundle_id, type=type,
                                                                 model=model, icon=response_url)
                    if not app_bundle_qs.exists():
                        # 上传设备图标至存储桶
                        bucket_name = 'ansjerfilemanager'
                        file_key = 'app/device_type_images/{}'.format(fileName)
                        s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
                        # 地址：https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/camera_c190.png
                        s3.upload_file_obj(
                            bucket_name,
                            file_key,
                            file,
                            {'ContentType': file.content_type, 'ACL': 'public-read'})
                #  创建
                for k, v in data_name.items():
                    for app_id in app_bundle_id:
                        app_bundle_qs = AppBundle.objects.filter(id=app_id).values('id')
                        app_device_type_qs = AppDeviceType.objects.create(model=model, type=type, icon=response_url,
                                                                          app_version_number_id=version_number)
                        DeviceNameLanguage.objects.create(lang=k, name=v, sort=sort,
                                                          app_device_type_id=app_device_type_qs.id)
                        #  关联app包
                        app_device_type_qs.appbundle_set.add(app_bundle_qs[0]['id'])
                return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def get_device_icon(self, request_dict, response):
        """
        查询设备信息图标
        @param request_dict: 请求参数
        @request_dict lang: 语言
        @request_dict app_bundle_id: app版本id
        @request_dict version_number: app版本号
        @param response: 响应对象
        @return:
        """
        lang = request_dict.get('lang', 'en')
        app_bundle_id = request_dict.get('appBundleId', None)
        version_number = request_dict.get('versionNumber', None)
        if not all([lang, app_bundle_id, version_number]):
            return response.json(444)
        try:
            # tc是ios繁体字语言类型
            if lang == 'tc':
                lang = 'cn_tw'
            app_bundle_qs = AppBundle.objects.filter(app_bundle_id=app_bundle_id).values(
                'app_device_type__app_version_number_id').distinct().order_by('app_device_type__app_version_number_id')
            #  判断版本是否存在， 不存在则获取输入版本范围内最接近的输入版本
            version_number_list = []
            app_bundle_list = []
            for version in app_bundle_qs:
                version_number_list.append(version['app_device_type__app_version_number_id'])
            new_version_number = CommonService.compare_version_number(version_number, version_number_list)
            app_device_qs = DeviceNameLanguage.objects.filter(lang=lang)
            if not app_device_qs.exists():
                lang = 'en'
            # 版本号对应的设备信息图标
            for version_number in new_version_number:
                app_bundle_qs = AppBundle.objects.filter(app_bundle_id=app_bundle_id,
                                                         app_device_type__devicenamelanguage__lang=lang,
                                                         app_device_type__app_version_number_id=version_number). \
                    annotate(
                    model=F('app_device_type__model'), type=F('app_device_type__type'), icon=F('app_device_type__icon'),
                    name=F('app_device_type__devicenamelanguage__name'),
                    sort=F('app_device_type__devicenamelanguage__sort'),
                    app_version_number_id=F('app_device_type__app_version_number_id')).values('model', 'type', 'icon',
                                                                                              'name', 'sort',
                                                                                              'app_device_type__app_version_number_id')
                for app_bundle in app_bundle_qs:
                    app_bundle_list.append({
                        'model': app_bundle['model'],
                        'type': app_bundle['type'],
                        'icon': app_bundle['icon'],
                        'name': app_bundle['name'],
                        'sort': app_bundle['sort'],
                        'app_device_type__app_version_number_id': app_bundle['app_device_type__app_version_number_id'],
                    })
            dvr_list = [app_bundle for app_bundle in app_bundle_list if app_bundle['model'] == 1]
            ipc_list = [app_bundle for app_bundle in app_bundle_list if app_bundle['model'] == 2]
            res = {
                'deviceDvr': sorted(dvr_list, key=operator.itemgetter('sort')),
                'deviceIpc': sorted(ipc_list, key=operator.itemgetter('sort')),
            }

            return response.json(0, res)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
