# -*- encoding: utf-8 -*-
"""
@File    : UserDeviceShareController.py
@Time    : 2023/1/7 15:05
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""
import logging
import time

from django.db import transaction
from django.db.models import Q
from django.views import View

from Model.models import DeviceSharePermission, DeviceChannelUserSet, DeviceChannelUserPermission, UidChannelSetModel, \
    Device_Info
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.UserDeviceService import UserDeviceService

LOGGER = logging.getLogger('info')


class UserDeviceShareView(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', token.lang)
        response = ResponseObject(lang)
        if token.code != 0:
            return response.json(token.code)
        if operation == 'user-permissions':
            return self.get_user_share_permission(request_dict, response)
        elif operation == 'permissions-save':
            return self.user_channel_permission_save(request_dict, response)
        elif operation == 'permissions-test':
            return self.synch_share_device_permission(response)
        else:
            return response.json(404)

    @classmethod
    def get_user_share_permission(cls, request_dict, response):
        """
        获取用户分享权限
        @param request_dict: 设备uid
        @param response: 响应对象
        @return: permission List
        """
        try:
            uid = request_dict.get('uid', None)
            user_id = request_dict.get('userId', None)
            channel_count = request_dict.get('channelCount', None)
            if not all([user_id, uid, channel_count]):
                return response(444, 'uid, userId and channelCount is required')
            user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
                .values('id', 'channels')
            if not user_permission_qs.exists():
                return response.json(0, {})
            up_id = user_permission_qs[0]['id']
            channel_permission_qs = DeviceChannelUserPermission.objects.filter(channel_user_id=up_id) \
                .values('permission_id', 'channel_user_id')
            if not channel_permission_qs.exists():
                return response.json(0, {})
            channel_list = list(range(1, int(channel_count) + 1))
            share_channel_list = user_permission_qs[0]['channels'].split(',')
            c_list = []
            for channel in channel_list:
                is_select = 1 if str(channel) in share_channel_list else 0
                c_list.append({'channelIndex': channel, 'isSelect': is_select})
            p_list = []
            permission_qs = DeviceSharePermission.objects.all()
            share_permission_list = [item['permission_id'] for item in channel_permission_qs]
            for item in permission_qs:
                is_select = 1 if item.id in share_permission_list else 0
                p_list.append({'permissionId': item.id, 'code': item.code, 'isSelect': is_select})
            data = {'channels': c_list, 'permissions': p_list}
            return response.json(0, data)
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def user_channel_permission_save(cls, request_dict, response):
        """
        主用户分享设备时设置通道权限保存
        """
        try:
            uid = request_dict.get('uid', None)
            channels = request_dict.get('channels', None)  # 通道集合，多个','隔开
            user_id = request_dict.get('userId', None)
            permission_ids = request_dict.get('permissionIds', None)  # 权限集合，多个','隔开
            if not all([user_id, uid, channels, permission_ids]):
                return response.json(444)
            p_ids = []
            device_user_set = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid)
            now_time = int(time.time())
            with transaction.atomic():
                is_delete = False
                if not device_user_set.exists():
                    device_set = {'uid': uid, 'user_id': user_id, 'channels': channels,
                                  'created_time': now_time, 'updated_time': now_time}
                    device_user_set = DeviceChannelUserSet.objects.create(**device_set)
                    channel_user_id = device_user_set.id
                else:
                    DeviceChannelUserSet.objects.update(channels=channels, updated_time=now_time)
                    channel_user_id = device_user_set.first().id
                    is_delete = True
                if ',' in permission_ids:
                    p_ids = [int(val) for val in permission_ids.split(',')]
                if is_delete:
                    DeviceChannelUserPermission.objects.filter(
                        channel_user_id=channel_user_id).delete()
                if not p_ids:
                    channel_permission = {'permission_id': int(permission_ids),
                                          'channel_user_id': channel_user_id,
                                          'created_time': now_time}
                    DeviceChannelUserPermission.objects.create(**channel_permission)
                else:
                    channel_permission_list = []
                    for item in p_ids:
                        channel_permission_list.append(DeviceChannelUserPermission(
                            permission_id=int(item),
                            channel_user_id=channel_user_id,
                            created_time=now_time))
                    DeviceChannelUserPermission.objects.bulk_create(channel_permission_list)
                return response.json(0)
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def qrcode_share_channel_permission_save(user_id, uid):
        """
        二维码分享保存通道权限
        @param user_id: 用户id
        @param uid: 用户设备ID
        @return: True | False
        """
        try:
            if not all([user_id, uid]):
                return False
            with transaction.atomic():
                ds_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid)
                if ds_qs.exists():
                    return True
                UserDeviceService.update_device_channel(uid)
                channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid).values('channel')
                if not channel_qs.exists():
                    return False
                channel_list = [str(val['channel']) for val in channel_qs]
                channel_str = ','.join(channel_list)
                now_time = int(time.time())
                device_set = {'uid': uid, 'user_id': user_id, 'channels': channel_str,
                              'created_time': now_time, 'updated_time': now_time}
                device_user_set = DeviceChannelUserSet.objects.create(**device_set)
                channel_permission_qs = DeviceSharePermission.objects \
                    .all().values('id', 'code').order_by('sort')
                user_set_id = device_user_set.id
                channel_permission_list = []
                for item in channel_permission_qs:
                    channel_permission_list.append(DeviceChannelUserPermission(
                        permission_id=item['id'],
                        channel_user_id=user_set_id,
                        created_time=now_time))
                DeviceChannelUserPermission.objects.bulk_create(channel_permission_list)
            return True
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return False

    @staticmethod
    def synch_share_device_permission(response):
        """
        同步分析设备权限
        @param response: 响应结果
        """
        device_info_qs = Device_Info.objects \
            .filter(~Q(Type__in=[1, 2, 3, 4, 10001]), ~Q(primaryUserID=''), isShare=1) \
            .values('userID_id', 'UID').order_by('-data_joined')
        if not device_info_qs.exists():
            return response.json(0)
        for item in device_info_qs:
            UserDeviceShareView.qrcode_share_channel_permission_save(item['userID_id'], item['UID'])
        return response.json(0)
