import json

from django.core.paginator import Paginator
from django.db.models import Q

from backend.Form.AuthMenuForm import AuthMenuForm
from DCbackend.utils.common import success, fail, pageData
from backend.models import AuthMenu, Admin, AuthUserMenu
from django.core.cache import cache

class AuthMenuService:
    @staticmethod
    def verify_token(token):
        admin_id = cache.get(f"admin_token:{token}")
        if admin_id:
            return Admin.objects.filter(id=admin_id).first()
        return None
    # 根据token查询菜单
    @staticmethod
    def menuList(request):
        adminInfo = AuthMenuService.verify_token(request.POST.get("token"))
        if adminInfo is not None:
            rolaId = adminInfo.role_id
            return success(AuthMenuService.menuInfo(rolaId))
        else:
            return fail()

    @staticmethod
    def menuInfo(roleId):

        userMenus = AuthUserMenu.objects.filter(rola_id=roleId)
        results = []
        if userMenus.exists():

            for menu in userMenus:
                menuid = menu.menu_id
                menu = AuthMenu.objects.filter(id=menuid).first()

                if menu is not None:
                    results.append({
                        "id": menuid,
                        "name": menu.name,
                        "code": menu.code,
                        "parent_id": menu.parent_id,
                        "sort": menu.sort,
                        "status": menu.status,
                        "path": menu.path,
                        "type": menu.type
                    })
        return results;

    #角色权限返回菜单
    @staticmethod
    def search(request):
        parent_menus = AuthMenu.objects.filter(parent_id=0).order_by("-id")
        # 创建一个字典来存储一级菜单及其对应的二级菜单
        dataList = []

        for parent in parent_menus:
            # 查询每个一级菜单项的子菜单项
            child_menus = AuthMenu.objects.filter(parent_id=parent.id).order_by("-id")
            # 将一级菜单及其子菜单存储在字典中
            for child in child_menus:
                dataList.append({
                    "id": child.id,
                    "name": child.name,
                    "code": child.code,
                    "parent_id": child.parent_id,
                    "sort": child.sort,
                    "status": child.status,
                    "path": child.path,
                    "type": child.type
                })
        return success(dataList)

    #创建菜单
    @staticmethod
    def create(request):
        form = AuthMenuForm(request.POST)
        if form.is_valid():
            menu = form.save(commit=False)  # 创建模型实例但不保存到数据库
            if menu.parent_id is None:
                menu.parent_id = 0
            menu.save()  # 现在保存到数据库
            return success("成功")
        else:
            return fail(form.errors)

    @staticmethod
    def update(request):
        data = AuthMenu.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.name = request.POST.get("name")
            data.code = request.POST.get("code")
            data.parent_id = request.POST.get("parent_id")
            data.status = request.POST.get("status")
            data.sort = request.POST.get("sort")
            data.path = request.POST.get("path")
            data.type = request.POST.get("type")
            data.save()
            return success("成功")
        else:
            return fail("更新源数据失败")
    @staticmethod
    def delete(request):
        AuthMenu.objects.filter(id=request.POST.get("id")).update(status=4)
        return success("成功")

    @staticmethod
    def info(request):
        info = AuthMenu.objects.filter(id=request.POST.get("id")).first()
        return success(AuthMenuService.getDetail(info))


    #分页查询菜单
    @staticmethod
    def listpage(request):
        # 从POST请求中获取数据
        page = int(request.POST.get('page', 1))
        page_size = int(request.POST.get('page_size', 10))

        # 获取额外的筛选参数
        name = request.POST.get('name', '')
        code = request.POST.get('code', '')
        type = request.POST.get('type', '')
        status = request.POST.get('status', '')

        # 查询所有父级菜单
        parent_menus = AuthMenu.objects.filter(parent_id=0).order_by("-id")

        dataList = []

        for parent in parent_menus:
            # 构建子菜单的多条件查询
            child_query = Q(parent_id=parent.id)

            # 根据提供的参数添加筛选条件
            if name:
                child_query &= Q(name__icontains=name)
            if code:
                child_query &= Q(code__icontains=code)
            if type:
                child_query &= Q(type__icontains=type)
            if status:
                child_query &= Q(status__icontains=status)


            # 使用构建的条件查询子菜单
            child_menus = AuthMenu.objects.filter(child_query).order_by("-id")

            for child in child_menus:
                dataList.append({
                    "id": child.id,
                    "name": child.name,
                    "code": child.code,
                    "parent_id": child.parent_id,
                    "sort": child.sort,
                    "status": child.status,
                    "path": child.path,
                    "create_time": child.create_time,
                    "type": child.type
                })

        # 对结果进行分页
        paginator = Paginator(dataList, page_size)
        page_obj = paginator.get_page(page)

        # 构建响应数据
        response_data = {
            "total": paginator.count,
            "page": page,
            "page_size": page_size,
            "data": list(page_obj)
        }

        return success(response_data)

    @staticmethod
    def getDetail(item: AuthMenu):
        return {
            "id": item.id,
            'code': item.code,
            'name': item.name,
            'parent_id': item.parent_id,
            'status': item.status,
            'sort': item.sort,
            'path': item.path,
            'type': item.type
        }