import uuid
from django.forms import model_to_dict
from DCbackend.utils.common import success, fail, pageData, handle_uploaded_file, oss_upload_file
from DCbackend.utils.token import decrypt, encrypt
from backend.Form.SuperAdminForm import SuperAdminForm
from backend.Form.SuperSettingsForm import SuperSettingsForm
from backend.Form.UserForm import UserForm
from backend.models import ProjectCategory, DefaultStatus, Project, Admin, SuperAdmin, SuperSettings, AuthMenu
from django.core.cache import cache

class SuperAdminService:
    @staticmethod
    def createPassword(request):
        password = request.POST.get("password")
        password = encrypt(password)
        return success(password)


    @staticmethod
    def createAccount(request):
        form = SuperAdminForm(request.POST)
        if form.is_valid():
            form.instance.password = encrypt(form.instance.password)
            form.save()
            return success("新建账号成功")
        else:
            return fail(form.errors)

    @staticmethod
    def superLogin(request):
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        adminInfo = SuperAdmin.objects.filter(username=username).first()

        if adminInfo is not None:
            if password == decrypt(adminInfo.password):
                # 检查是否存在有效的 token
                existing_token = SuperAdminService.get_existing_supertoken(adminInfo.id)

                if existing_token:
                    # 如果存在有效的 token，直接返回
                    return success({"token": existing_token})
                else:
                    # 如果不存在有效的 token，生成新的
                    new_token = uuid.uuid4().hex
                    cache.set(f"superadmin_token:{new_token}", adminInfo.id, timeout=60 * 60 * 24)
                    cache.set(f"superadmin_id_to_token:{adminInfo.id}", new_token, timeout=60 * 60 * 24)
                    return success({"token": new_token})
            else:
                return fail("登录密码不正确")
        else:
            return fail("登录失败，管理员用户名不存在")


    @staticmethod
    def get_existing_supertoken(admin_id):
        # 尝试从缓存中获取该管理员的 token
        token = cache.get(f"superadmin_id_to_token:{admin_id}")
        if token:
            # 如果找到 token，检查它是否仍然有效
            if cache.get(f"superadmin_token:{token}"):
                return token
        return None
    @staticmethod
    def verify_token(token):
        admin_id = cache.get(f"superadmin_token:{token}")
        if admin_id:
            return SuperAdmin.objects.filter(id=admin_id).first()
        return None

    #获取配置信息
    @staticmethod
    def selcetSetting(request):
        token = request.POST.get("token")
        if not token:
            return fail("token为空")
        superInfo = SuperAdminService.verify_token(token)
        if not superInfo:
            return fail("用户不存在")
        setting = SuperSettings.objects.filter(id=superInfo).first()
        superInfo_dict = model_to_dict(setting)
        return success(superInfo_dict)


    @staticmethod
    def insertSetting(request):
        count = SuperSettings.objects.filter().count()
        if count > 0:
            return fail("已存在配置参数,请勿重复添加")
        form = SuperSettingsForm(request.POST)
        if form.is_valid():
            form.save()
            return success("新增成功")
        else:
            return fail(form.errors)

    @staticmethod
    def updateSettings(request):
        data = SuperSettings.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.logo = request.POST.get("logo")
            data.name = request.POST.get("name")
            data.sidebar_color = request.POST.get("sidebar_color")
            data.internal_color = request.POST.get("internal_color")
            data.button_color = request.POST.get("button_color")
            data.log_color = request.POST.get("log_color")
            data.log_color_url = request.POST.get("log_color_url")
            data.head_color = request.POST.get("head_color")
            data.save()
            return success("更新成功")
        else:
            return fail("更新源数据失败")

    @staticmethod
    def deleteSettings(request):
        id = request.POST.get("id")
        SuperSettings.objects.filter(id=id).delete()
        return success("物理删除成功")

    @staticmethod
    def getSuperMenu(request):
        token = request.POST.get("token")
        if not token:
            return fail("token为空")
        superInfo = SuperAdminService.verify_token(token)
        if not superInfo:
            return fail("用户不存在")

        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")
            # 将一级菜单及其子菜单存储在字典中
            children = []
            for child in child_menus:
                children.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
                })
            dataList.append({
                "id": parent.id,
                "name": parent.name,
                "code": parent.code,
                "parent_id": parent.parent_id,
                "sort": parent.sort,
                "status": parent.status,
                "path": parent.path,
                "type": parent.type,
                "children": children
            })
        return success(dataList)


    @staticmethod
    def creatAdmin(request):
        form = UserForm(request.POST)
        if form.is_valid():
            form.instance.password = encrypt(form.instance.password)
            new_admin = form.save()


            return success("创建admin成功")
        else:
            return fail(form.errors)
















