# -*- encoding: utf-8 -*-
"""
@File    : EquipmentFamilyController.py
@Time    : 2022/5/13 15:50
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""

import time

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

from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
from Controller.DeviceConfirmRegion import Device_Region
from Controller.SensorGateway.SmartSocketController import SmartSocketView
from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
    iotdeviceInfoModel, UIDModel, Device_User, UserFamily, FamilyMember, FamilyMemberPermission, \
    FamilyRoomDevice, FamilyRoom, FamilyMemberJoin, GatewaySubDevice, CountryModel, SocketInfo
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService


# 家庭设备管理
class EquipmentFamilyView(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):

        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
        lang = request_dict.get('lang', None)
        if lang:
            response = ResponseObject(lang)
        else:
            response = ResponseObject(token.lang) if token.lang else ResponseObject()

        if token.code != 0:
            return response.json(token.code)
        user_id = token.userID

        # 手机端添加设备，查询，修改
        if operation == 'add':
            return self.do_save(user_id, request_dict, response, request)
        # 分页获取未添加房间设备
        elif operation == 'family-device-query':
            return self.get_device_not_in_room(user_id, request_dict, response)
        # 条件查询设备列表
        elif operation == 'query':
            return self.do_device_query(user_id, request_dict, response)
        # 获取家庭列表
        elif operation == 'family-list':
            return self.get_family_list(user_id, request_dict, response)
        # 查询所在家庭列表
        elif operation == "where-family-list":
            return self.who_family_list(user_id, response)
        # 家庭保存
        elif operation == 'family-save':
            return self.family_save(user_id, request_dict, response)
        # 家庭设置
        elif operation == 'family-setting':
            return self.get_family_setting(request_dict, response)
        # 家庭成员删除
        elif operation == 'member-del':
            return self.family_member_del(user_id, request_dict, response)
        # 获取房间列表
        elif operation == 'room-list':
            return self.get_family_room_list(request_dict, response)
        # 房间保存
        elif operation == 'room-save':
            return self.room_save(request_dict, response)
        # 权限列表
        elif operation == 'permission-list':
            return self.get_member_permission_list(user_id, request_dict, response)
        # 成员权限修改
        elif operation == 'permission-update':
            return self.changes_member_permission(user_id, request_dict, response)
        elif operation == 'family/del':
            return self.family_family_del(user_id, request_dict, response)
        # 首页设备列表
        elif operation == 'query-device':
            return self.get_device(user_id, request_dict, response)
        else:
            return response.json(414)

    @classmethod
    def family_family_del(cls, user_id, request_dict, response):
        """
        删除家庭
        @param user_id:
        @param request_dict:
        @param response:
        @return:
        """
        family_id = request_dict.get('familyId', None)
        if not family_id:
            return response.json(444)
        family_id = int(family_id)
        permission = cls.get_member_permission_details(user_id, family_id)
        if not permission or permission == '003':
            return response.json(404)
        user_family_qs = UserFamily.objects.filter(id=family_id, user_id=user_id)
        if not user_family_qs.exists():
            return response.json(173)
        count = UserFamily.objects.filter(user_id=user_id).count()
        if count <= 1:
            return response.json(10057)
        family_room_device_qs = FamilyRoomDevice.objects.filter(family_id=family_id)
        if family_room_device_qs.exists():
            family_room_device_qs.delete()
        family_join_qs = FamilyMemberJoin.objects.filter(family_id=family_id)
        if family_join_qs.exists():
            family_join_qs.delete()
        family_room_qs = FamilyRoom.objects.filter(family_id=family_id)
        if family_room_qs.exists():
            family_room_qs.delete()
        family_member_qs = FamilyMember.objects.filter(family_id=family_id)
        if family_member_qs.exists():
            family_member_qs.delete()
        family_qs = UserFamily.objects.filter(id=family_id)
        if family_qs.exists():
            family_qs.delete()
        return response.json(0)

    @classmethod
    def do_save(cls, user_id, request_dict, response, request):
        """
        添加网关设备
        @param request:
        @param user_id:
        @param request_dict:
        @param response:
        @return:
        """
        nick_name = request_dict.get('nickName', None)
        serial_number = request_dict.get('serialNumber', None)
        device_type = request_dict.get('deviceType', None)
        family_id = request_dict.get('familyId', None)
        room_id = request_dict.get('roomId', None)
        # type 可能为0
        if not all([nick_name, serial_number, device_type]):
            return response.json(444, {'param': 'nick_name, serial_number, device_type'})
        device_info_qs = Device_Info.objects.filter(serial_number=serial_number, isShare=False)
        device_info_qs = device_info_qs.values('NickName', 'userID_id', 'userID__userEmail', 'userID__phone',
                                               'userID__username', 'userID__NickName')
        if device_info_qs.exists():
            qs = device_info_qs
            nickname = qs[0]['NickName']
            device_user_id = qs[0]['userID_id']
            if device_user_id == user_id:
                return response.json(174)
            else:
                if qs[0]['userID__userEmail']:
                    bind_user = qs[0]['userID__userEmail']
                elif qs[0]['userID__phone']:
                    bind_user = qs[0]['userID__phone']
                elif qs[0]['userID__username']:
                    bind_user = qs[0]['userID__username']
                elif qs[0]['userID__NickName']:
                    bind_user = qs[0]['userID__NickName']
                else:
                    bind_user = qs[0]['userID_id']
                res = {
                    'bindUser': bind_user,
                    'bindDeviceName': nickname,
                    'isMainUserExists': 1
                }
                return response.json(0, res=res)
        try:
            with transaction.atomic():
                family_id = int(family_id)
                # 格式化后的日期时间
                now_time = CommonService.timestamp_to_str(int(time.time()))
                device_id = CommonService.getUserID(getUser=False)
                Device_Info.objects.create(id=device_id, userID_id=user_id, NickName=nick_name,
                                           Type=device_type,
                                           UID=serial_number,
                                           serial_number=serial_number, data_joined=now_time,
                                           update_time=now_time)
                boole = cls.family_room_device_save(family_id, room_id, device_id, device_type)
                if not boole:
                    return response.json(15)
                # 判断是否有用户绑定
                us_qs = UidSetModel.objects.filter(uid=serial_number)
                if not us_qs:
                    n_time = int(time.time())
                    ip = CommonService.get_ip_address(request)
                    ipInfo = CommonService.getIpIpInfo(ip, 'CN')
                    country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
                    if country_qs.exists():
                        country = country_qs[0]['id']
                    else:
                        country = '0'
                    region_id = Device_Region().get_device_region(ip)
                    region_alexa = 'CN' if region_id == 1 else 'ALL'
                    uid_set_create_dict = {
                        'uid': serial_number,
                        'addTime': n_time,
                        'updTime': n_time,
                        'ip': CommonService.get_ip_address(request_dict),
                        'nickname': nick_name,
                        'region_alexa': region_alexa,
                        'device_type': device_type,
                        'tb_country': country
                    }
                    UidSetModel.objects.create(**uid_set_create_dict)
                if int(device_type) == 201:  # 添加插座信息
                    SmartSocketView.save_socket_switch(device_id, serial_number, 0)
                res = {
                    'deviceId': device_id,
                    'nickName': nick_name,
                    'serialNumber': serial_number
                }
                return response.json(0, res)
        except Exception as e:
            print(e)
            return response.json(177, repr(e))

    @classmethod
    def get_device_not_in_room(cls, user_id, request_dict, response):
        """
        获取不在房间的设备
        @param user_id: 用户id
        @param request_dict:
        @param response:
        @return:
        """
        page_no = request_dict.get('pageNo', None)
        page_size = request_dict.get('pageSize', None)
        family_id = request_dict.get('familyId', None)
        if not all([page_no, page_size, family_id]):
            return response.json(444)
        page_no = int(page_no)
        page_size = int(page_size)
        device_list = cls.get_family_device_list(user_id, page_no, page_size, family_id, 0)
        return response.json(0, device_list)

    @classmethod
    def do_device_query(cls, user_id, request_dict, response):
        """
        查询用户设备信息
        @param user_id: 用户id
        @param request_dict: 请求参数
        @param response: 响应对象
        @return: response
        """
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        nick_name = request_dict.get('NickName', None)
        family_id = request_dict.get('familyId', None)
        room_id = request_dict.get('roomId', None)

        page = int(page)
        line = int(line)
        uid = request_dict.get('uid', None)
        if family_id:
            permission = cls.get_member_permission_details(user_id, int(family_id))
            if not permission or permission == '003':
                return response.json(404)
        if room_id:
            family_room = FamilyRoom.objects.filter(id=room_id)
            if not family_room.exists():
                return response.json(173)
            permission = cls.get_member_permission_details(user_id, family_room.first().family_id)
            if not permission or permission == '003':
                return response.json(404)
        # 获取设备信息列表
        device_info_list = cls.get_device_info_list(user_id, nick_name, uid,
                                                    page, line, family_id, room_id)
        uid_list = []
        # 判断是否是主用户 isPrimaryUser=0：否，1：是
        for dvl in device_info_list:
            if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
                dvl['isPrimaryUser'] = 1
            else:
                dvl['isPrimaryUser'] = 0
            uid_list.append(dvl['UID'])
        # 设备关联套餐，设备预览图
        uid_bucket_qs, uid_preview_qs = cls.get_bucket_and_preview_by_uid(uid_list)
        # 设备配置信息
        uid_set_dict = cls.get_uid_set_dict(uid_list)
        # 设备详情信息
        result = cls.get_device_details(device_info_list, uid_bucket_qs, uid_preview_qs, uid_set_dict)
        items = []
        for index, item in enumerate(result):
            # 加密
            if item['View_Password']:
                item['View_Password'] = CommonService.encode_data(item['View_Password'], 1, 4)
            items.append(item)
        return response.json(0, items)

    @classmethod
    def get_device_info_list(cls, user_id, nick_name, uid, page, line, family_id, room_id):
        """
        根据用户id获取设备信息
        @param room_id: 家庭id
        @param family_id: 房间id
        @param uid: uid
        @param nick_name: 设备名称
        @param line: 条数
        @param page: 页数
        @param user_id: 用户id
        @return: device_info_list 设备信息列表
        """
        # 获取用户设备信息
        device_info_qs = Device_Info.objects.filter(userID_id=user_id)
        # 过滤已重置的设备
        device_info_qs = device_info_qs.filter(~Q(isExist=2))
        if nick_name:
            device_info_qs = device_info_qs.filter(NickName__icontains=nick_name)
        if uid:
            device_info_qs.filter(UID=uid)
        if family_id or room_id:
            # 根据家庭id获取房间id关联查询设备
            return cls.get_family_device_list(user_id, page, line, family_id, room_id)
        device_info_values = device_info_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')

        device_info_values = device_info_values[(page - 1) * line:page * line]
        device_info_list = CommonService.qs_to_list(device_info_values)
        return device_info_list

    @classmethod
    def get_family_device_list(cls, user_id, page_no, page_size, family_id, room_id, is_room_other=False):
        """
        获取关联家庭设备列表
        @param is_room_other: 是否显示其他房间设备
        @param user_id: 用户id
        @param page_no: 页数
        @param page_size: 分页大小
        @param family_id: 家庭id
        @param room_id: 房间id
        @return: result_list
        """
        cursor = connection.cursor()
        sql = 'SELECT d.id,d.userID_id as userID,d.NickName,d.UID,d.View_Account,d.View_Password,d.ChannelIndex,' \
              'd.Type,d.isShare,d.primaryUserID,d.primaryMaster,d.data_joined,d.vodPrimaryUserID,d.vodPrimaryMaster, ' \
              'd.version,d.isVod,d.isExist,d.NotificationMode,d.isCameraOpenCloud,d.serial_number '
        sql += 'FROM device_info d INNER JOIN family_room_device l ON d.id = l.device_id '
        sql += 'WHERE d.userID_id = %s AND d.isExist != %s '
        if family_id:
            family_id = int(family_id)
            user_id = UserFamily.objects.filter(id=family_id).first().user_id
            sql += ' AND l.family_id = %s '
        if room_id and is_room_other:
            sql += ' AND l.room_id != %s '
        elif room_id:
            sql += ' AND l.room_id = %s '
        sql += ' GROUP BY d.id order by d.data_joined DESC,d.id DESC LIMIT %s,%s '
        if family_id and room_id:
            cursor.execute(sql, [user_id, 2, int(family_id), int(room_id), ((page_no - 1) * page_size),
                                 page_size, ])
            data_obj = cursor.fetchall()
        else:
            cursor.execute(sql, [user_id, 2, int(family_id) if family_id else int(room_id), ((page_no - 1) * page_size),
                                 page_size, ])
            data_obj = cursor.fetchall()
        cursor.close()  # 执行完，关闭
        connection.close()
        result_list = []
        col_names = [desc[0] for desc in cursor.description]
        for item in data_obj:
            val = dict(zip(col_names, item))
            user_id = val['userID']
            device_user_qs = Device_User.objects.filter(userID=user_id)
            val['userID__userEmail'] = device_user_qs.first().userEmail
            val['isShare'] = False if val['isShare'] == 0 else True
            if 'data_joined' in val:
                if val['data_joined']:
                    val['data_joined'] = val['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
                else:
                    val['data_joined'] = ''
            result_list.append(val)
        return result_list

    @classmethod
    def get_bucket_and_preview_by_uid(cls, uid_list):
        """
        根据uid列表查询套餐
        @param uid_list: uid列表
        @return: uid_bucket_qs
        """
        uid_bucket_qs = UID_Bucket.objects.filter(uid__in=uid_list).values('bucket__content', 'status', 'channel',
                                                                           'endTime', 'uid')
        uid_preview_qs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
        return uid_bucket_qs, uid_preview_qs

    @classmethod
    def get_uid_set_dict(cls, uid_list):
        """
        获取uid配置信息
        @param uid_list: uid列表
        @return: uid_set_dict uid配置信息
        """
        uid_set_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',
                    'is_ptz', 'double_wifi', 'is_ai')
        uid_set_dict = {}
        for us in uid_set_qs:
            uid_set_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'],
                'is_ptz': us['is_ptz'],
                'double_wifi': us['double_wifi'],
                'is_ai': us['is_ai']
            }
            # 从uid_channel里面取出通道配置信息
            uid_channel_set_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_list = []
            for ucs in uid_channel_set_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_list.append(channels_dict)
            uid_set_dict[us['uid']]['channels'] = channels_list
        return uid_set_dict

    @classmethod
    def get_device_details(cls, device_info_list, uid_bucket_qs, uid_preview_qs, uid_set_dict):
        """
        设备详情
        @param device_info_list: 设备信息列表
        @param uid_bucket_qs: 套餐对象
        @param uid_preview_qs:
        @param uid_set_dict:
        @return:
        """
        now_time = int(time.time())
        data = []
        for p in device_info_list:
            # 获取iotDeviceInfo表的endpoint和tokenIotNumber
            p['iot'] = []
            if p['serial_number']:  # 存在序列号根据序列号查询
                iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
            else:  # 根据uid查询
                iot_device_info_qs = iotdeviceInfoModel.objects.filter(uid=p['UID'])
            if iot_device_info_qs.exists():
                iot_device_Info = iot_device_info_qs.values('endpoint', 'token_iot_number')
                p['iot'].append({
                    'endpoint': iot_device_Info[0]['endpoint'],
                    'token_iot_number': iot_device_Info[0]['token_iot_number']
                })

            p['vod'] = []
            for dm in uid_bucket_qs:
                if p['UID'] == dm['uid']:
                    if dm['endTime'] > now_time:
                        p['vod'].append(dm)
            p['preview'] = []

            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')

            for up in uid_preview_qs:
                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']

            # 返回设备初始化字符
            uid_qs = UIDModel.objects.filter(uid=p_uid).values('platform', 'init_string', 'init_string_app')
            if uid_qs.exists():
                p['platform'] = uid_qs[0]['platform']
                p['initString'] = uid_qs[0]['init_string']
                p['initStringApp'] = uid_qs[0]['init_string_app']

            if p_uid in uid_set_dict:
                # 设备版本号
                uidversion = uid_set_dict[p_uid]['version']
                if len(uidversion) > 6:
                    uidversion = uidversion[0: uidversion.rfind('.')]
                p['uid_version'] = uidversion
                p['ucode'] = uid_set_dict[p_uid]['ucode']
                p['detect_interval'] = uid_set_dict[p_uid]['detect_interval']
                p['detect_status'] = uid_set_dict[p_uid]['detect_status']
                p['detect_group'] = uid_set_dict[p_uid]['detect_group']
                p['region_alexa'] = uid_set_dict[p_uid]['region_alexa']
                p['is_alexa'] = uid_set_dict[p_uid]['is_alexa']
                p['deviceModel'] = uid_set_dict[p_uid]['deviceModel']
                p['TimeZone'] = uid_set_dict[p_uid]['TimeZone']
                p['TimeStatus'] = uid_set_dict[p_uid]['TimeStatus']
                p['SpaceUsable'] = uid_set_dict[p_uid]['SpaceUsable']
                p['SpaceSum'] = uid_set_dict[p_uid]['SpaceSum']
                p['MirrorType'] = uid_set_dict[p_uid]['MirrorType']
                p['RecordType'] = uid_set_dict[p_uid]['RecordType']
                p['OutdoorModel'] = uid_set_dict[p_uid]['OutdoorModel']
                p['WIFIName'] = uid_set_dict[p_uid]['WIFIName']
                p['isDetector'] = uid_set_dict[p_uid]['isDetector']
                p['DetectorRank'] = uid_set_dict[p_uid]['DetectorRank']
                p['is_human'] = uid_set_dict[p_uid]['is_human']
                p['is_custom_voice'] = uid_set_dict[p_uid]['is_custom_voice']
                p['is_ptz'] = uid_set_dict[p_uid]['is_ptz']
                p['channels'] = uid_set_dict[p_uid]['channels']
                p['double_wifi'] = uid_set_dict[p_uid]['double_wifi']
                p['is_ai'] = uid_set_dict[p_uid]['is_ai']
                # 设备昵称 调用影子信息昵称，先阶段不可
                if uid_set_dict[p_uid]['nickname']:
                    p['NickName'] = uid_set_dict[p_uid]['nickname']
            else:
                # 设备版本号
                p['uid_version'] = ''
                p['ucode'] = ''
            data.append(p)
        return data

    @classmethod
    def get_family_list(cls, user_id, request_dict, response):
        """
        查询我的家庭列表
        @param user_id: 用户id
        @param request_dict: 请求
        @param response: 响应
        @return: 家庭列表items
        """
        lang = request_dict.get('lang', 'en')
        if user_id:
            with transaction.atomic():
                user_family_qs = UserFamily.objects.filter(user_id=user_id)
                if not user_family_qs.exists():
                    n_time = int(time.time())
                    device_user = Device_User.objects.filter(userID=user_id).values('username', 'userEmail')
                    if not device_user.exists():
                        return response.json(104)

                    # 创建默认家庭使用用户名或者邮箱作为名称
                    username = device_user[0]['username']
                    family_name = username if username else device_user[0]['userEmail']
                    family_name = family_name + "的家" if lang == 'cn' else family_name + " home"
                    user_family = UserFamily.objects.create(user_id=user_id, name=family_name,
                                                            updated_time=n_time,
                                                            created_time=n_time)
                    if user_family.id:
                        member_permission_qs = FamilyMemberPermission.objects.filter(no='001').values('id')
                        permission_id = member_permission_qs.first()['id']
                        FamilyMember.objects.create(family_id=user_family.id, user_id=user_id,
                                                    user_name=username, identity=1,
                                                    permission_id=int(permission_id), sort=1, updated_time=n_time,
                                                    created_time=n_time)
                        cls.family_device_binding(user_id, family_id=user_family.id)

                family_member_qs = FamilyMember.objects.filter(user_id=user_id) \
                    .order_by('sort').values('identity', 'family_id', 'family__name', 'permission_id', 'permission__no',
                                             'family__location', 'user__username', 'user__userIconUrl')
                items = EquipmentFamilyView.family_info_list(family_member_qs)
                return response.json(0, items)
        return response.json(309)

    @staticmethod
    def who_family_list(user_id, response):
        """
        查询我加入的家庭集合与我创建的家庭集合
        @param user_id:
        @param response:
        @return:
        """
        join_family_qs = FamilyMember.objects.filter(user_id=user_id, identity=0) \
            .order_by('sort').values('identity', 'family_id', 'family__name', 'permission_id', 'permission__no',
                                     'family__location', 'user__username', 'user__userIconUrl')
        join_family_list = EquipmentFamilyView.family_info_list(join_family_qs)

        my_family_qs = FamilyMember.objects.filter(user_id=user_id, identity=1) \
            .order_by('sort').values('identity', 'family_id', 'family__name', 'permission_id', 'permission__no',
                                     'family__location', 'user__username', 'user__userIconUrl')
        my_family_list = EquipmentFamilyView.family_info_list(my_family_qs)

        return response.json(0, {'myFamilyList': my_family_list, 'joinFamilyList': join_family_list})

    @staticmethod
    def family_info_list(family_member_qs):
        items = []
        data = {}
        for item in family_member_qs:
            data['familyId'] = item['family_id']
            data['identity'] = item['identity']
            data['familyName'] = item['family__name']
            data['permissionId'] = item['permission_id']
            data['permissionNo'] = item['permission__no']
            data['familyLocation'] = item['family__location']
            data['userName'] = item['user__username']
            data['userIconUrl'] = item['user__userIconUrl']
            room_qs = FamilyRoom.objects.filter(family_id=data['familyId']).order_by('sort') \
                .values('id', 'name')
            data['rooms'] = list(room_qs)
            items.append(data)
            data = {}
        return items

    @classmethod
    def get_family_setting(cls, request_dict, response):
        """
        家庭设置
        @param request_dict: 请求
        @param response: 响应
        @return: 家庭列表items
        """
        family_id = request_dict.get('familyId', None)
        if not family_id:
            return response.json(444)
        family_id = int(family_id)
        user_family_qs = UserFamily.objects.filter(id=family_id).values('id', 'name', 'location')
        if not user_family_qs.exists():
            return response.json(404)
        family_dict = user_family_qs.first()
        device_count = FamilyRoomDevice.objects.filter(family_id=family_id, sub_device=0).count()
        family_dict['deviceCount'] = device_count
        family_dict['roomCount'] = FamilyRoom.objects.filter(family_id=family_id).count()

        family_member_qs = FamilyMember.objects.filter(family_id=family_id)
        family_member_qs = family_member_qs.values('identity', 'family_id',
                                                   'permission_id',
                                                   'permission__no',
                                                   'user__username',
                                                   'user_id',
                                                   'user__userIconUrl',
                                                   'user__NickName',
                                                   'user__phone',
                                                   'user__userEmail',
                                                   'id')
        family_member_qs = family_member_qs.order_by('-identity').order_by('sort')
        items = []
        data = {}
        for item in family_member_qs:
            data['userName'] = item['user__username']
            data['userIconUrl'] = item['user__userIconUrl']
            data['userId'] = item['user_id']
            data['identity'] = item['identity']
            data['permissionId'] = item['permission_id']
            data['permissionNo'] = item['permission__no']
            data['nickName'] = item['user__NickName']
            data['phone'] = item['user__phone']
            data['userEmail'] = item['user__userEmail']
            data['memberId'] = item['id']
            items.append(data)
            data = {}
        family_dict['members'] = items
        return response.json(0, family_dict)

    @classmethod
    def family_save(cls, user_id, request_dict, response):
        """
        家庭保存
        @param user_id: 用户id
        @param request_dict: 参数
        @param response: 响应
        @return:
        """
        family_id = request_dict.get('familyId', None)
        family_name = request_dict.get('familyName', None)
        location = request_dict.get('location', None)
        with transaction.atomic():
            now_time = int(time.time())
            if family_id:
                is_owner = cls.get_family_owner(user_id, family_id)
                if not is_owner:
                    return response.json(404)
                family_member = FamilyMember.objects.filter(family_id=family_id, user_id=user_id)
                if family_member.exists():
                    family_member = family_member.first()
                    if family_member.identity == 0:
                        return response.json(404)
                    family_qs = UserFamily.objects.filter(id=family_id)
                    if family_qs.exists():
                        data = {
                            'updated_time': now_time
                        }
                        if family_name:
                            data['name'] = family_name
                        if location:
                            data['location'] = location
                        family_qs.update(**data)
                        return response.json(0)
            data = {'user_id': user_id, 'updated_time': now_time, 'created_time': now_time}
            if family_name:
                data['name'] = family_name
                if location:
                    data['location'] = location
                UserFamily.objects.create(**data)
                return response.json(0)
            return response.json(444)

    @classmethod
    def family_room_device_save(cls, family_id, room_id, device_id, device_type):
        """
        设备与家庭房间保存
        @param family_id: 家庭id
        @param room_id: 房间id
        @param device_id: 设备id
        @param device_type: 设备类型
        @return: Boole
        """
        now_time = int(time.time())
        device_type = int(device_type)
        family_room_device = FamilyRoomDevice.objects.filter(device_id=device_id)
        if family_room_device.exists():
            return False
        data = {
            'family_id': int(family_id),
            'device_id': device_id,
            'updated_time': now_time,
            'created_time': now_time
        }

        category = 0 if device_type == 200 or device_type == 201 else 1
        data['category'] = category
        # 查询类别排序
        family_room_device_qs = FamilyRoomDevice.objects.filter(family_id=int(family_id), category=category).values(
            'category_sort')
        if family_room_device_qs.exists():
            data['category_sort'] = family_room_device_qs[0]['category_sort']
        if room_id:
            room_id = int(room_id)
            if FamilyRoom.objects.filter(id=room_id).exists():
                data['room_id'] = room_id
        FamilyRoomDevice.objects.create(**data)
        return True

    @classmethod
    def family_device_binding(cls, user_id, family_id):
        """
        用户旧设备与默认家庭进行绑定
        @param user_id:
        @param family_id:
        @return: True
        """
        device_info_qs = Device_Info.objects.filter(userID=user_id)
        device_info_qs = device_info_qs.filter(~Q(isExist=0)).values('id', 'Type')
        if device_info_qs.exists():
            with transaction.atomic():
                not_time = time.time()
                device_list = []
                for item in device_info_qs:
                    device_id = item['id']
                    device_type = item['Type']
                    if device_type == 200 or 201:
                        category = 0
                    else:
                        category = 1
                    family_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
                    if not family_device_qs.exists():
                        # 设备绑定家庭
                        device_list.append(FamilyRoomDevice(family_id=family_id, device_id=device_id,
                                                            created_time=not_time, category=category,
                                                            updated_time=not_time))
                if device_list:
                    FamilyRoomDevice.objects.bulk_create(device_list)
        return True

    @classmethod
    def get_family_room_list(cls, request_dict, response):
        """
        获取房间列表并统计该房间下有几台设备
        @param request_dict: 请求参数
        @param response: 响应参数
        @return: total；data
        """
        family_id = request_dict.get('familyId', None)
        if not family_id:
            return response.json(444)
        count = FamilyRoomDevice.objects.filter(family_id=family_id).values('device_id').annotate(
            count=Count('device_id')).count()

        room_qs = FamilyRoom.objects.filter(family_id=family_id).order_by('sort')
        total = room_qs.count()
        room_qs = room_qs.values('id', 'name', 'sort')
        room_list = []
        if not room_qs.exists():
            return response.json(0, {'total': 0, 'data': room_list, 'deviceTotal': count})
        for item in room_qs:
            item['deviceCount'] = FamilyRoomDevice.objects.filter(family_id=family_id, room_id=item['id']).count()
            room_list.append(item)
        return response.json(0, {'total': total, 'data': room_list, 'deviceTotal': count})

    @classmethod
    def room_save(cls, request_dict, response):
        """
        房间保存
        @param request_dict: 请求参数
        @param response: 响应参数
        @return:
        """
        family_id = request_dict.get('familyId', None)
        room_name = request_dict.get('roomName', None)
        room_id = request_dict.get('roomId', None)
        if not all([family_id, room_name]):
            return response.json(444)
        with transaction.atomic():
            now_time = int(time.time())
            if room_id:
                room_qs = FamilyRoom.objects.filter(id=int(room_id))
                if room_qs.exists():
                    room_qs.update(name=room_name, updated_time=now_time)
                    return response.json(0)
            room_qs = FamilyRoom.objects.filter(family_id=family_id, name=room_name)

            if room_qs.exists():
                return response.json(174)
            FamilyRoom.objects.create(family_id=family_id, name=room_name, updated_time=now_time,
                                      created_time=now_time)
        return response.json(0)

    @classmethod
    def changes_member_permission(cls, app_user_id, request_dict, response):
        """
        更新家庭成员权限
        @param app_user_id: 当前app登录用户
        @param request_dict: 请求参数
        @param response: 响应实体
        @return:
        """
        family_id = request_dict.get('familyId', None)
        user_id = request_dict.get('userId', None)
        no = request_dict.get('no', None)
        if not all([family_id, user_id, no]):
            return response.json(444)
        owner = cls.get_family_owner(app_user_id, family_id)
        if not owner:
            return response.json(404)
        permission_qs = FamilyMemberPermission.objects.filter(no=no).values()
        if permission_qs.exists():
            permission_qs = permission_qs.first()
            p_id = permission_qs['id']
            FamilyMember.objects.filter(family_id=family_id, user_id=user_id).update(permission_id=p_id)
        return response.json(0)

    @classmethod
    def family_member_del(cls, app_user_id, request_dict, response):
        """
        家庭成员删除
        @param app_user_id: 当前app登录用户
        @param request_dict: 请求参数
        @param response: 响应实体
        @return:
        """
        family_id = request_dict.get('familyId', None)
        user_id = request_dict.get('userId', None)
        if not all([family_id, user_id]):
            return response.json(444)
        owner = cls.get_family_owner(app_user_id, family_id)
        if not owner:
            return response.json(404)
        family_member_qs = FamilyMember.objects.filter(family_id=family_id, user_id=user_id)
        if family_member_qs.exists():
            family_member_qs.delete()
        return response.json(0)

    @classmethod
    def get_member_permission_list(cls, app_user_id, request_dict, response):
        """
        获取用户权限列表
        @param app_user_id: 当前app登录用户
        @param request_dict:
        @param response:
        @return:
        """
        family_id = request_dict.get('familyId', None)
        user_id = request_dict.get('userId', app_user_id)
        if not family_id:
            return response.json(404)
        result = cls.get_member_permission_by_family_id(user_id, family_id)
        return response.json(0, result)

    @classmethod
    def get_member_permission_by_family_id(cls, user_id, family_id):
        """
        获取权限列表并返回当前user_id所在家庭中权限
        @param user_id:
        @param family_id:
        @return:
        """
        member_qs = FamilyMember.objects.filter(family_id=family_id)
        if user_id:
            member_qs = member_qs.filter(user_id=user_id).values()
            if member_qs.exists():
                member_qs = member_qs.first()
        permission = FamilyMemberPermission.objects.all().values('id', 'no')
        data_list = []
        this_permission = {}
        result = {}
        for item in permission:
            if item['id'] == member_qs['permission_id']:
                this_permission['id'] = item['id']
                this_permission['no'] = item['no']
            data_list.append(item)
        result['memberPermission'] = this_permission
        result['permissionList'] = data_list
        return result

    @classmethod
    def get_member_permission_details(cls, user_id, family_id):
        """
        根据用户id获取家庭设备权限
        @param user_id:
        @param family_id:
        @return: 权限编号 001：所有权限，002：查看设备，003：暂无权限
        """
        member_qs = FamilyMember.objects.filter(family_id=family_id, user_id=user_id).values()
        if member_qs.exists():
            member_qs = member_qs.first()
            permission_id = member_qs['permission_id']
            permission_qs = FamilyMemberPermission.objects.filter(id=permission_id).values('no')
            return permission_qs.first()['no']
        return ''

    @classmethod
    def get_family_owner(cls, user_id, family_id):
        """
        判断是否是家庭主用户
        @param user_id:
        @param family_id:
        @return:
        """
        user_family_qs = UserFamily.objects.filter(id=family_id, user_id=user_id)
        if user_family_qs.exists():
            return True
        return False

    @classmethod
    def get_device(cls, user_id, request_dict, response):
        """
        首页设备查询
        @param user_id: 用户id
        @param request_dict: 请求参数
        @request_dict page: 页数
        @request_dict line: 分页大小
        @request_dict familyId: 家庭id
        @request_dict roomId: 房间id
        @param response: 响应对象
        @return: response
        """
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        family_id = request_dict.get('familyId', None)
        room_id = request_dict.get('roomId', None)

        if not all([page, line, family_id]):
            return response.json(444, {'error param': 'page or line or family_id'})
        page = int(page)
        line = int(line)
        device_dict = {
            'gateways': [],
            'cameras': [],
            'sensors': [],
            'sort': []
        }
        permission = cls.get_member_permission_details(user_id, int(family_id))
        if not permission or permission == '003':
            return response.json(404)
        family_room_device_qs = FamilyRoomDevice.objects \
            .filter(Q(family_id=family_id), ~Q(device_id__isExist=2)) \
            .values().order_by('sort', '-device__data_joined')
        if not family_room_device_qs.exists():
            return response.json(0, device_dict)
        gateways = []
        cameras = []
        sensors = []

        try:
            category_sort = family_room_device_qs.values('category').annotate(
                count=Count('category')).values('category', 'category_sort').order_by('category_sort')
            for item in category_sort:
                if item['category'] == 0:
                    item['category_name'] = '网关子设备类'
                else:
                    item['category_name'] = '摄像头类'
            device_dict['sort'] = list(category_sort)
            if room_id:
                family_room = FamilyRoom.objects.filter(id=room_id)
                if not family_room.exists():
                    return response.json(0, device_dict)
                family_room_device_qs = family_room_device_qs.filter(room_id=room_id)
            # 处理网关摄像头
            gateways_or_cameras_qs = family_room_device_qs.filter(sub_device=0)[(page - 1) * line:page * line]
            for item in gateways_or_cameras_qs:
                room_qs = FamilyRoom.objects.filter(id=item['room_id']).values('name')
                room_name = room_qs[0]['name'] if room_qs.exists() else ''
                device_qs = Device_Info.objects.filter(id=item['device_id']).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'
                ).first()
                if device_qs:
                    if device_qs['View_Password']:
                        device_qs['View_Password'] = CommonService.encode_data(device_qs['View_Password'], 1, 4)
                    device_qs['sensorStatus'] = 0
                    device_qs['roomName'] = room_name
                    if device_qs['primaryUserID'] and device_qs['id'] == device_qs['primaryUserID']:
                        device_qs['isPrimaryUser'] = 1
                    else:
                        device_qs['isPrimaryUser'] = 0
                    if 'data_joined' in device_qs:
                        if device_qs['data_joined']:
                            device_qs['data_joined'] = device_qs['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
                        else:
                            device_qs['data_joined'] = ''
                    if device_qs['Type'] == 200 or device_qs['Type'] == 201:
                        if device_qs['Type'] == 201:
                            socket_info_qs = SocketInfo.objects.filter(device_id=device_qs['id']).values(
                                'status')
                            device_qs['socketStatus'] = socket_info_qs.first()[
                                'status'] if socket_info_qs.exists() else ''
                        gateways.append(device_qs)
                    else:
                        cameras.append(device_qs)
            # 处理传感器
            sensors_qs = family_room_device_qs.filter(~Q(sub_device=0))
            for item in sensors_qs:  # 查询传感器
                sub_device_qs = GatewaySubDevice.objects.filter(id=item['sub_device']).values()
                if sub_device_qs.exists():
                    sub_device_dict = {
                        "id": sub_device_qs[0]['id'],
                        "NickName": sub_device_qs[0]['nickname'],
                        "Type": sub_device_qs[0]['device_type'],
                        'sensorStatus': sub_device_qs[0]['status'],
                    }
                    sensors.append(sub_device_dict)
            device_dict['sensors'] = sensors

            device_list = [gateways, cameras]
            for index, item in enumerate(device_list):
                uid_list = []
                for dvl in item:
                    uid_list.append(dvl['UID'])
                # 设备关联套餐，设备预览图
                uid_bucket_qs, uid_preview_qs = cls.get_bucket_and_preview_by_uid(uid_list)
                # 设备配置信息
                uid_set_dict = cls.get_uid_set_dict(uid_list)
                # 设备详情信息
                result = cls.get_device_details(item, uid_bucket_qs, uid_preview_qs, uid_set_dict)
                if index == 0:
                    device_dict['gateways'] = result
                else:
                    device_dict['cameras'] = result

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