from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.group.models import Group
from apps.log.models import get_log, gen_log
from apps.user.middleware.rolecontrol import RoleControl
from apps.user.models import User

import logging
logger = logging.getLogger('django')


class GroupView(APIView):
    authentication_classes = []

    # 删除分组
    @staticmethod
    @RoleControl
    def delete(request, group_id, *args, **kwargs):
        group = Group.objects.filter(id=group_id, delete=False)
        if not group:
            logger.error("分组已删除或不存在")
        group = group[0]
        users = group.users.all()
        for user in users:
            group.users.remove(user)
        group.delete = True
        group.save()
        executor, action, method = get_log(request)
        gen_log(action, "分组", group.name, method, executor)
        return HttpResponse("删除完成")


class GroupEdit(APIView):
    authentication_classes = []

    # 编辑分组
    @staticmethod
    @RoleControl
    def post(request, group_id, *args, **kwargs):
        name = request.POST.get('group_name')

        if not name:
            logger.error("组名不能位空")
            return HttpResponse(status=500, content='组名不能位空')

        group = Group.objects.filter(id=group_id, delete=False)
        if not group:
            logger.error("id为" + group_id + "的分组不存在")
            return HttpResponse(status=404, content="id为" + group_id + "的分组不存在")
        group = group[0]
        group.name = name
        group.save()
        executor, action, method = get_log(request)
        gen_log(action, "分组", group.name, method, executor)
        return HttpResponse(status=200, content='修改已保存')