#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：format_core_base_auth.py
@Author  ：congxing.wang
@Date    ：2026/02/25
@Desc    ：权限数据格式化与展示
"""


def get_auth_json(target_data, mid):
    from django_base_ai.system.models import Dept, Role, Tags, Users

    # 最终显示的名称
    target_data_result = []
    for item in target_data:
        nid = item.get("id", 0)
        node_type = item.get("node_type", 0)
        obj = None
        if node_type == 1:
            obj = Dept.objects.filter(id=nid).first()
        elif node_type == 2:
            obj = Role.objects.filter(id=nid).first()
        elif node_type == 3:
            obj = Tags.objects.filter(id=nid).first()
        elif node_type == 4:
            obj = Users.objects.filter(id=nid).first()
        if obj:
            target_data_result.append(
                {
                    "id": nid,
                    "name": f"{obj.name}({obj.username})" if node_type == 4 else obj.name,
                    "node_type": node_type,
                }
            )
    return {"nid": mid, "target_data": target_data_result}


def create_update_auth_json(value):
    from django_base_ai.system.models import CoreBaseAuth

    if isinstance(value, dict):
        if "nid" in value:
            CoreBaseAuth.objects.filter(id=value.get("nid", 0)).delete()
        target_data = value.get("target_data", [])
    else:
        target_data = value
    django_base_ai_auth = CoreBaseAuth.objects.create(target_data=target_data)
    # 过滤不同类型参数
    dept_ids, role_ids, tags_ids, user_ids = [], [], [], []
    for item in target_data:
        node_type = item.get("node_type", 0)
        if node_type == 1:
            dept_ids.append(item.get("id"))
        elif node_type == 2:
            role_ids.append(item.get("id"))
        elif node_type == 3:
            tags_ids.append(item.get("id"))
        elif node_type == 4:
            user_ids.append(item.get("id"))
    django_base_ai_auth.target_dept.set(dept_ids)
    django_base_ai_auth.target_role.set(role_ids)
    django_base_ai_auth.target_tags.set(tags_ids)
    django_base_ai_auth.target_users.set(user_ids)
    django_base_ai_auth.save()
    return {"nid": django_base_ai_auth.id}


# 部门递归方法
def get_dept_user_ids(dept_id, list_ids):
    from django_base_ai.system.models import Dept, Users

    depts = Dept.objects.filter(parent__id=dept_id)
    for item in depts:
        ids = list(Users.objects.filter(dept_id=item.id).values_list("id", flat=True))
        list_ids += ids
        get_dept_user_ids(item.id, list_ids)


def get_auth_user_info(django_base_ai_auth_id=0):
    from django_base_ai.system.models import CoreBaseAuth, Users

    # 根据id查询授权限
    django_base_ai_auth = CoreBaseAuth.objects.filter(id=django_base_ai_auth_id).first()
    if not django_base_ai_auth:
        return []
    if django_base_ai_auth.target_dept.filter(dept__id=1).exists():
        return list(set(list(Users.objects.filter(is_active=1).all().values_list("id", flat=True))))
    list_ids = []
    for item in django_base_ai_auth.target_dept.all():
        ids = list(Users.objects.filter(dept_id=item.id).values_list("id", flat=True))
        list_ids += ids
        # 递归子级
        get_dept_user_ids(item.id, list_ids)
    # 角色
    for item in django_base_ai_auth.target_role.all():
        ids = list(Users.objects.filter(role=item).distinct().values_list("id", flat=True))
        list_ids += ids
    # 标签（可以有多个)
    for item in django_base_ai_auth.target_tags.all():
        ids = list(item.user_info.all().values_list("id", flat=True))
        list_ids += ids
    # 用户
    ids = list(django_base_ai_auth.target_users.all().values_list("id", flat=True))
    list_ids += ids
    # 需要递归获取
    return list(set(list_ids))


def check_user_info(user_id, django_base_ai_auth_id=0):
    """
    检查用户是否有权限
    :param user_id:
    :param django_base_ai_auth_id:
    :return:
    """
    from django_base_ai.system.models import CoreBaseAuth, Tags, Users

    django_base_ai_auth = CoreBaseAuth.objects.filter(id=django_base_ai_auth_id).first()
    current_user = Users.objects.filter(id=user_id, is_active=True).first()
    current_user_role = list(current_user.role.all().values_list("id", flat=True))
    current_user_tags = list(Tags.objects.filter(user_info__id=current_user.id).values_list("id", flat=True))
    check_dept = (
        django_base_ai_auth.target_dept.all().filter(id=current_user.dept.id if current_user.dept else 0).exists()
    )
    check_role = django_base_ai_auth.target_role.all().filter(id__in=current_user_role).exists()
    check_tags = django_base_ai_auth.target_tags.all().filter(id__in=current_user_tags).exists()
    check_users = django_base_ai_auth.target_users.all().filter(id=current_user.id).exists()
    if not check_dept and not check_role and not check_tags and not check_users:
        return False
    return True
