# -*- encoding: utf-8 -*-
"""
@File    : UserDeviceService.py
@Time    : 2022/11/18 11:40
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""
import logging

from django.db.models import Q

from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, UnicomDeviceInfo, \
    UIDModel, DeviceChannelUserSet, DeviceChannelUserPermission, DeviceSharePermission
from Service.CommonService import CommonService

LOGGER = logging.getLogger('info')


class UserDeviceService:

    @classmethod
    def query_device_list(cls, user_id, uid, nickname, page, line):
        """
        查询设备列表
        @param user_id: 用户user_id
        @param uid: uid
        @param nickname: 昵称
        @param page: 页数
        @param line: 每页条数
        @return: dv_list, uid_list
        """
        dv_qs = Device_Info.objects.filter(userID_id=user_id)
        # 过滤已重置的设备
        dv_qs = dv_qs.filter(~Q(isExist=2))
        if nickname:
            dv_qs = dv_qs.filter(NickName=nickname)
        if uid:
            dv_qs = dv_qs.filter(UID=uid)
        # 周视首页过滤网关以及插座类型
        dv_qs = dv_qs.exclude(Type__in=[200, 201])
        dv_qs = dv_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').order_by('-data_joined')
        dv_list = CommonService.qs_to_list(dv_qs)
        uid_list = []
        exist_uid = []
        unique_results = []
        for item in dv_qs:
            UID = item['UID']
            # 删除重复的uid数据
            if UID not in exist_uid:
                exist_uid.append(UID)
                unique_results.append(item)
            else:
                Device_Info.objects.filter(id=item['id']).delete()
                username = CommonService.get_username(user_id)
                LOGGER.info('{}删除重复uid{}'.format(username, UID))

        # 分页操作
        dv_list = unique_results[(page - 1) * line:page * line]
        uid_list = [item['UID'] for item in dv_list]

        # 处理 isPrimaryUser
        for item in dv_list:
            item['isPrimaryUser'] = 1 if item['primaryUserID'] and item['id'] == item['primaryUserID'] else 0
        return dv_list, uid_list

    @classmethod
    def query_device_uid_bucket(cls, uid_list):
        """
        查询uid关联存储桶套餐
        @param uid_list: uid集合
        @return: UID_Bucket
        """
        return UID_Bucket.objects.filter(uid__in=uid_list). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')

    @classmethod
    def query_device_preview(cls, uid_list):
        """
        查询设备uid预览图
        @param uid_list: uid集合
        @return: UID_Preview
        """
        return UID_Preview.objects.filter(uid__in=uid_list).order_by('channel') \
            .values('id', 'uid', 'channel')

    @classmethod
    def query_device_uid_set(cls, uid_list):
        """
        查询设备属性
        @return: UidSetModel
        """
        return UidSetModel.objects.filter(uid__in=uid_list) \
            .values('id', 'uid', 'version', 'nickname', 'ucode',
                    'detect_status', 'detect_group', 'new_detect_interval',
                    'detect_interval', 'isSupportFourPoint',
                    'region_alexa', 'is_alexa', 'deviceModel',
                    'TimeZone', 'TimeStatus', 'SpaceUsable',
                    'SpaceSum', 'MirrorType', 'RecordType',
                    'OutdoorModel', 'WIFIName', 'isDetector',
                    'DetectorRank', 'is_human', 'is_custom_voice',
                    'is_ptz', 'double_wifi', 'is_ai', 'mobile_4g',
                    'ai_type')

    @classmethod
    def query_device_channel(cls, uid_list):
        """
        获取设备通道配置属性
        @param uid_list: uid集合
        @return: uv_dict
        """
        us_qs = cls.query_device_uid_set(uid_list)
        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'],
                'new_detect_interval': us['new_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'],
                'is_ptz': us['is_ptz'],
                'double_wifi': us['double_wifi'],
                'mobile4G': us['mobile_4g'],
                'is_ai': us['is_ai'],
                'ai_type': us['ai_type'],
                'isSupportFourPoint': us['isSupportFourPoint'],
            }
            uv_dict[us['uid']]['channels'] = cls.query_device_channel_set(us['id'])
        return uv_dict

    @classmethod
    def query_device_channel_set(cls, uid):
        """
        查询通道配置
        @param uid: 设备uid
        @return: channels
        """
        ucs_qs = UidChannelSetModel.objects.filter(uid__id=uid)
        ucs_qs = ucs_qs.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)
        return channels

    @classmethod
    def get_sim_by_serial_number(cls, p_vo):
        """
        根据序列号获取SIM卡属性
        @param p_vo:
        @return:
        """
        if p_vo['serial_number']:
            u_device_info_qs = UnicomDeviceInfo.objects.filter(serial_no=p_vo['serial_number'])
            if u_device_info_qs.exists():
                card_type = u_device_info_qs.first().card_type
                if card_type == 5:  # 鼎芯国际
                    p_vo['iccid'] = u_device_info_qs.first().iccid[0:19]
                else:
                    p_vo['iccid'] = u_device_info_qs.first().iccid
                p_vo['iccidType'] = card_type

    @classmethod
    def get_uid_info(cls, p_vo, uid):
        """
        获取uid信息
        @param p_vo: 设备对象
        @param uid: 设备uid
        @return:
        """
        uid_qs = UIDModel.objects.filter(uid=uid).values('platform', 'init_string', 'init_string_app')
        if uid_qs.exists():
            p_vo['platform'] = uid_qs[0]['platform']
            p_vo['initString'] = uid_qs[0]['init_string']
            p_vo['initStringApp'] = uid_qs[0]['init_string_app']

    @classmethod
    def get_device_info_dto(cls, p_vo, p_uid, uv_dict, user_id=None):
        """
        获取设备信息DTO
        @param user_id: 用户ID
        @param p_vo: 设备信息
        @param p_uid: 设备uid
        @param uv_dict: 设备通道信息
        """
        uidversion = uv_dict[p_uid]['version']
        if len(uidversion) > 6:
            uidversion = uidversion[0: uidversion.rfind('.')]
        p_vo['uid_version'] = uidversion
        p_vo['ucode'] = '72V201233AA' if uv_dict[p_uid]['mobile4G'] == 1 else uv_dict[p_uid]['ucode']
        p_vo['detect_interval'] = uv_dict[p_uid]['detect_interval']
        p_vo['new_push_interval'] = uv_dict[p_uid]['new_detect_interval']
        p_vo['detect_status'] = uv_dict[p_uid]['detect_status']
        p_vo['detect_group'] = uv_dict[p_uid]['detect_group']
        p_vo['region_alexa'] = uv_dict[p_uid]['region_alexa']
        p_vo['is_alexa'] = uv_dict[p_uid]['is_alexa']
        p_vo['deviceModel'] = uv_dict[p_uid]['deviceModel']
        p_vo['TimeZone'] = uv_dict[p_uid]['TimeZone']
        p_vo['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
        p_vo['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
        p_vo['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
        p_vo['MirrorType'] = uv_dict[p_uid]['MirrorType']
        p_vo['RecordType'] = uv_dict[p_uid]['RecordType']
        p_vo['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
        p_vo['WIFIName'] = uv_dict[p_uid]['WIFIName']
        p_vo['isDetector'] = uv_dict[p_uid]['isDetector']
        p_vo['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
        p_vo['is_human'] = uv_dict[p_uid]['is_human']
        p_vo['is_custom_voice'] = uv_dict[p_uid]['is_custom_voice']
        p_vo['is_ptz'] = uv_dict[p_uid]['is_ptz']
        p_vo['channels'] = cls.get_channel_permission_by_user(user_id, p_vo['isShare'], p_uid,
                                                              uv_dict[p_uid]['channels'])
        p_vo['double_wifi'] = uv_dict[p_uid]['double_wifi']
        p_vo['mobile4G'] = uv_dict[p_uid]['mobile4G']
        p_vo['isCameraOpenCloud'] = 0 if uv_dict[p_uid]['mobile4G'] == 1 else p_vo['isCameraOpenCloud']
        p_vo['is_ai'] = uv_dict[p_uid]['is_ai']
        p_vo['ai_type'] = uv_dict[p_uid]['ai_type']
        p_vo['isSupportFourPoint'] = uv_dict[p_uid]['isSupportFourPoint']
        # 设备昵称 调用影子信息昵称，先阶段不可
        if uv_dict[p_uid]['nickname']:
            p_vo['NickName'] = uv_dict[p_uid]['nickname']

    @staticmethod
    def get_channel_permission_by_user(user_id, is_share, uid, channels):
        """
        根据用户获取设备通道权限
        @param user_id: 用户ID
        @param is_share: 是否分享设备
        @param uid: 设备UID
        @param channels: 通道信息
        @return: channels
        """
        try:
            if not is_share:
                return channels
            # 获取设备权限
            channel_set_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid).values('id', 'channels')
            if not channel_set_qs.exists() or not channels:
                return channels
            channel_list = [int(val) for val in channel_set_qs[0]['channels'].split(',')]
            channel_permission_qs = DeviceChannelUserPermission.objects \
                .filter(channel_user_id=channel_set_qs[0]['id']).values('permission_id')
            ids = [val['permission_id'] for val in channel_permission_qs]
            channel_permission_qs = DeviceSharePermission.objects \
                .all().values('id', 'code').order_by('sort')
            channel_permission_list = []
            default_permissions = []
            if not channel_permission_qs.exists():
                return channels

            for item in channel_permission_qs:
                default_permissions.append({'permissionId': item['id'], 'code': item['code'], 'isSelect': 0})
                p_data = {'permissionId': item['id'], 'code': item['code'], 'isSelect': 1 if item['id'] in ids else 0}
                channel_permission_list.append(p_data)

            for item in channels:
                channel = item['channel']
                if channel in channel_list:
                    item['channelPermissions'] = channel_permission_list
                else:
                    item['channelPermissions'] = default_permissions
            return channels
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return channels

    @staticmethod
    def update_device_channel(uid):
        """
        UID通道同步更新
        @param uid: 设备UID
        @return: True | False
        """
        try:
            uid_set_qs = UidSetModel.objects.filter(uid=uid).values('id', 'channel')
            if not uid_set_qs.exists():
                return False
            uid_set_id = uid_set_qs[0]['id']
            channel_index = uid_set_qs[0]['channel']
            uid_channel_qs = UidChannelSetModel.objects.filter(uid_id=uid_set_id).values('channel')
            if uid_channel_qs.exists() and uid_channel_qs.count() != channel_index:
                uid_channel_list = []
                channels = [val['channel'] for val in uid_channel_qs]
                for i in range(1, channel_index + 1):
                    if i in channels:
                        continue
                    channel_name = 'channel' + str(i)  # channel1,channel2...
                    UidChannelSet = UidChannelSetModel(uid_id=uid_set_id, channel=i, channel_name=channel_name)
                    uid_channel_list.append(UidChannelSet)
                if not uid_channel_list:
                    return True
                UidChannelSetModel.objects.bulk_create(uid_channel_list)
            return True
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return False
