# @Author    : Rocky
# @File      : DeviceGroupController.py
# @Time      : 2025/1/22 9:51
from django.db import transaction
from django.db.models import Q
from django.views import View

from Model.models import DeviceGroup, Device_Info
from Service.CommonService import CommonService


class DeviceGroupView(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_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
        if token_code != 0:
            return response.json(token_code)
        if operation == 'queryGroupQuantity':  # 查询分组数量
            return self.query_group_quantity(request_dict, user_id, response)
        elif operation == 'queryGroupDevice':  # 查询分组设备
            return self.query_group_device(request_dict, user_id, response)
        elif operation == 'queryOtherGroupDevice':  # 查询其他分组设备
            return self.query_other_group_device(request_dict, user_id, response)
        elif operation == 'creat':  # 创建分组
            return self.creat(request_dict, user_id, response)
        elif operation == 'update':  # 重命名分组
            return self.update(request_dict, user_id, response)
        elif operation == 'delete':  # 删除分组
            return self.delete(request_dict, user_id, response)
        elif operation == 'transferGroup':   # 转移分组
            return self.transfer_group(request_dict, user_id, response)
        else:
            return response.json(414)

    @staticmethod
    def query_group_quantity(request_dict, user_id, response):
        """
        查询分组数量
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        # 该用户已存在该组名的分组
        device_group_qs = DeviceGroup.objects.filter(user_id=user_id).values('id', 'group_name')
        if not device_group_qs.exists():
            return response.json(173)
        res = []
        for device_group in device_group_qs:
            device_quantity = Device_Info.objects.filter(device_group_id=device_group['id']).count()
            device_group['device_quantity'] = device_quantity
            res.append(device_group)
        return response.json(0, res)

    @staticmethod
    def query_group_device(request_dict, user_id, response):
        """
        查询分组设备
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        device_group_id = request_dict.get('device_group_id', None)
        if not device_group_id:
            return response.json(444)
        device_info_qs = Device_Info.objects.filter(device_group_id=device_group_id).values('NickName')
        if not device_info_qs.exists():
            return response.json(0)
        res = list(device_info_qs)
        return response.json(0, res)

    @staticmethod
    def query_other_group_device(request_dict, user_id, response):
        """
        查询其他分组设备
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        device_group_id = request_dict.get('device_group_id', None)
        if not device_group_id:
            return response.json(444)
        try:
            # 查询设备数量不为0的其他分组
            device_group_qs = DeviceGroup.objects.filter(~Q(id=device_group_id), user_id=user_id).\
                values('id', 'group_name')
            if not device_group_qs.exists():
                return response.json(0)
            res = []
            # 查询各组的设备id和昵称
            for device_group in device_group_qs:
                device_info_list = []
                device_info_qs = Device_Info.objects.filter(device_group_id=device_group['id']).\
                    values('id', 'NickName')
                for device_info in device_info_qs:
                    device_info_list.append(device_info)
                    device_group['device_info_list'] = device_info_list
                    res.append(device_group)
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def creat(request_dict, user_id, response):
        """
        创建分组
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        group_name = request_dict.get('group_name', None)
        if not group_name:
            return response.json(444)
        # 该用户已存在该组名的分组
        device_group_qs = DeviceGroup.objects.filter(user_id=user_id, group_name=group_name)
        if device_group_qs.exists():
            return response.json(174)
        DeviceGroup.objects.create(user_id=user_id, group_name=group_name)
        return response.json(0)

    @staticmethod
    def update(request_dict, user_id, response):
        """
        重命名分组
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        device_group_id = request_dict.get('device_group_id', None)
        group_name = request_dict.get('group_name', None)
        if not all([device_group_id, group_name]):
            return response.json(444)
        # 该用户已存在该组名的分组
        device_group_qs = DeviceGroup.objects.filter(user_id=user_id, group_name=group_name)
        if device_group_qs.exists():
            return response.json(174)
        DeviceGroup.objects.filter(id=device_group_id).update(group_name=group_name)
        return response.json(0)

    @staticmethod
    def delete(request_dict, user_id, response):
        """
        删除分组
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        device_group_id = request_dict.get('device_group_id', None)
        if not device_group_id:
            return response.json(444)
        try:
            device_group_id = int(device_group_id)
            with transaction.atomic():
                # 删除设备分组数据,重置设备信息表的分组id
                DeviceGroup.objects.filter(id=device_group_id).delete()
                Device_Info.objects.filter(device_group_id=device_group_id).update(device_group_id=0)
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def transfer_group(request_dict, user_id, response):
        """
        转移分组
        @param request_dict:
        @param user_id:
        @param response:
        @return: res
        """
        device_group_id = request_dict.get('device_group_id', None)
        device_id_list = request_dict.get('device_id_list', None)
        if not all([device_group_id, device_id_list]):
            return response.json(444)
        try:
            device_group_id = int(device_group_id)
            device_id_list = device_id_list.split(',')
            # 更新设备信息表的分组id
            Device_Info.objects.filter(id__in=device_id_list).update(device_group_id=device_group_id)
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
