#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : custome_login.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 自定义登录接口
import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

from django_base_ai import dispatch
from django_base_ai.system.models import Role
from django_base_ai.utils.json_response import DetailResponse
from django_base_ai.utils.request_util import save_login_log

User = get_user_model()

# 创建日志记录器
logger = logging.getLogger(__name__)


class CustomeLoginJWTAPIView(APIView):
    authentication_classes = ()
    permission_classes = ()

    # 用户自定义登录
    def post(self, request, *args, **kwargs):
        """
        执行自定义登录代码
        :param request: 用户请求体
        :param args:
        :param kwargs:
        :return:
        """
        logger.info("开始执行自定义登录")
        logger.debug(f"系统配置: {settings.SYSTEM_CONFIG}")

        # 默认
        func_str = ""
        namespace = {}

        try:
            fun = compile(func_str, "<string>", "exec")
            exec(fun, namespace)
            logger.info("自定义登录函数编译成功")

            ret = namespace["run_cmd"](kwargs=request.data)
            logger.info(f"自定义登录函数执行结果: {ret}")

            default_role_ids = dispatch.get_system_config_values("third.default_role")
            logger.debug(f"获取到的默认角色IDs: {default_role_ids}")

            user_id = ret.get("id")
            logger.debug(f"从返回结果中获取的用户ID: {user_id}")

            user = User.objects.get(id=user_id)
            logger.info(f"查询到用户: {user.username}, ID: {user.id}")

            # 新增到普通用户组
            roles = Role.objects.filter(id__in=default_role_ids)
            user.role.add(*roles)
            logger.info(f"已将用户添加到角色: {[r.name for r in roles]}")

            # 获得用户后，校验密码并签发token
            refresh = RefreshToken.for_user(user)
            cache.set(f"user_{user.id}", "online", 60 * 5)
            access_token = str(refresh.access_token)

            logger.info(f"生成Token成功, 用户ID: {user.id}")

            data = {
                "access": access_token,
                "refresh": str(refresh),
                "name": user.name,
                "skin": user.skin,
                "userId": user.id,
                "is_staff": user.is_staff,
                "avatar": user.avatar,
                "pwd_defaulted": user.pwd_defaulted,
                "user_type": user.user_type,
                "role_info": user.role.values("id", "name", "key"),
            }

            user.last_token = access_token
            user.save()
            logger.debug("用户Token已保存到数据库")

            # 记录登录日志
            save_login_log(request=request, login_type=900, current_user=user)
            logger.info(f"自定义登录成功, 用户: {user.username}, 登录类型: 900")

            return DetailResponse(data)
        except Exception as e:
            logger.error(f"自定义登录过程中发生错误: {str(e)}", exc_info=True)
            raise
