from django.core.paginator import Paginator
from django.db import transaction
from oss2.exceptions import status

from DCbackend.utils.common import success, fail, pageData
from backend.Form.TemplateCategoryForm import TemplateCategoryForm
from backend.Form.TemplateForm import TemplateForm
from backend.models import  TemplateCategory
import json

class TemplateCategoryService:
    @staticmethod
    @transaction.atomic
    def Create(request):
        try:
            form = TemplateCategoryForm(request.POST)
            if form.is_valid():
                parent_id = request.POST.get("parent_id")
                if int(parent_id) !=0:
                    parent = TemplateCategory.objects.get(id=parent_id)
                    level = 1
                    while parent.parent_id and parent.parent_id != 0:
                        try:
                            parent = TemplateCategory.objects.get(id=parent.parent_id)
                            level += 1
                            if level >= 5:
                                return fail("新增失败,最多五级分类")
                        except TemplateCategory.DoesNotExist:
                            break  # 父级分类不存在，跳出循环

                form.save()
                return success("新增成功")
            else:
                return fail("表单无效")
        except Exception as e:
            return fail(str(e))


    @staticmethod
    @transaction.atomic
    def Creates(request):
        try:
            child_data = request.POST.get("child")


            parent_id = request.POST.get("id")

            if child_data:
                #保存子类
                data = json.loads(child_data)
                TemplateCategoryService.save_or_update_category(data,parent_id)

            else:
                # 保存父类
                form = TemplateCategoryForm(request.POST)
                print(form.data)
                if form.is_valid():
                    form.save()
                    return success("父级信息保存成功")
                else:
                    return fail(f"父级信息保存失败: {form.errors}")

            return success("保存成功")
        except Exception as e:
            return fail(str(e))

    @staticmethod
    @transaction.atomic
    def save_or_update_category(data, parent_id):
        if isinstance(data, list):
            for item in data:
                TemplateCategoryService.save_or_update_category(item, parent_id)
            return

        category_id = data.get('id')
        if category_id and category_id != "":
            # 更新现有分类
            category = TemplateCategory.objects.filter(id=category_id).first()
            if not category:
                raise ValueError(f"未找到ID为{category_id}的分类")
        else:
            # 创建新分类
            category = TemplateCategory()

        # 更新分类数据
        category.name = data.get('name')
        category.status = data.get('status')

        # 设置 parent_id
        category.parent_id = str(parent_id)

        category.save()
        print(f"保存分类: {category}")

        # 处理子分类
        children = data.get('child', [])
        if children:
            for child in children:
                print(f"处理子分类: {child.get('name')}")
                # 使用当前分类的ID作为子分类的parent_id
                TemplateCategoryService.save_or_update_category(child, category.id)


    @staticmethod
    @transaction.atomic
    def Update(request):
        try:
            data = TemplateCategory.objects.filter(id=request.POST.get("id")).first();
            if data is not None:
                parent_id = int(request.POST.get("parent_id"))
                if int(data.parent_id) == 0 and parent_id != 0:
                    return fail("无法将父类变更为子类")

                if int(data.parent_id) != 0 and  parent_id == 0:
                    return fail("无法将子类直接变更为父类，请删除后新建")

                count = TemplateCategory.objects.filter(parent_id = data.id).exclude(status = 4).count()
                if count != 0 and int(data.parent_id) != 0 and parent_id != 0:
                    return fail("当前子类下有参数，无法变更")


                data.intro = request.POST.get("intro")
                data.name = request.POST.get("name")
                data.status = request.POST.get("status")
                data.parent_id = parent_id

                data.save()
                return success("编辑成功")
            else:
                return fail("数据错误无当前数据")

        except Exception as e:
            return fail(str(e))


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

    @staticmethod
    @transaction.atomic
    def Delete(request):
        count = TemplateCategory.objects.filter(parent_id=request.POST.get("id")).exclude(status=4).count()
        if count > 0:
            return fail("其下存在数据无法删除")

        TemplateCategory.objects.filter(id=request.POST.get("id")).update(status=4)
        return success("成功")

    @staticmethod
    def getDetail(item: TemplateCategory):


        return {
            "id": item.id,
            'intro': item.intro,
            'name': item.name,
            'createTime': item.create_time,
            'status': item.status,
            'parent_id': item.parent_id
        }

    @staticmethod
    def Search(request):
        status = request.POST.get("status")
        prantId = request.POST.get("parent_id")
        dataList = []


        if prantId == "0":
            page = request.POST.get("page")
            pageSize = request.POST.get("pageSize")
            if page is None:
                page = 1
            if pageSize is None:
                pageSize = 10

            where = {}
            name = request.POST.get("name", '')
            if name:
                where["name__icontains"] = name


            if status:
                where['status'] = status

            paginator = Paginator(TemplateCategory.objects.filter(**where,parent_id=0).exclude(status=4).order_by("-id"),pageSize)  # 每页显示10条数据
            page_obj = paginator.get_page(page)

            for item in page_obj:
                child_count = TemplateCategory.objects.filter(parent_id=item.id).exclude(status=4).count()
                info = TemplateCategoryService.getDetail(item)
                info['child_count'] = child_count
                dataList.append(info)
            return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))
        else:
            subcategories = TemplateCategory.objects.filter(parent_id=prantId).exclude(status=4).order_by("-id")

            dataList = []
            for item in subcategories:
                child_count = TemplateCategory.objects.filter(parent_id=item.id).exclude(status=4).count()
                info = TemplateCategoryService.getDetail(item)
                info['child_count'] = child_count
                dataList.append(info)
            return success(dataList)

    @staticmethod
    def allInfo(request):
        # 查询所有一级菜单项
        parent_menus = TemplateCategory.objects.filter(parent_id=0).exclude(status=4).order_by("-id")

        # 创建一个字典来存储一级菜单及其对应的二级菜单
        dataList = []

        for parent in parent_menus:
            # 查询每个一级菜单项的子菜单项
            child_menus = TemplateCategory.objects.filter(parent_id=parent.id).exclude(status=4).order_by("-id")
            # 将一级菜单及其子菜单存储在字典中
            dataList.append({
                "parent": {
                "id": parent.id,
                "name": parent.name,
                "parent_id": parent.parent_id,
                # 添加其他需要的字段
            },
            "children": list(child_menus.values("id", "name", "parent_id"))
            })

        return success(dataList)

    @staticmethod
    def allList(request):
        # 查询所有非状态4的类别
        all_categories = TemplateCategory.objects.exclude(status=4).order_by("-id")

        # 查询所有顶级类别（parent_id 为 0）
        top_level_categories = all_categories.filter(parent_id=0).exclude(status=4)

        # 获取所有子类别，同时确保其父类也不是状态4
        child_categories = all_categories.exclude(parent_id=0).exclude(status=4).filter(
            parent_id__in=all_categories.values('id')
        )

        # 获取所有有子类的顶级类别的ID
        categories_with_children = set(child_categories.values_list('parent_id', flat=True))

        # 组织结果
        result = list(child_categories) + [
            category for category in top_level_categories
            if category.id not in categories_with_children
        ]

        # 将查询集转换为列表，以便序列化
        result_list = [
            {
                'id': item.id,
                'name': item.name,
                'intro': item.intro,
                'create_time': item.create_time,
                'status': item.status,
                'parent_id': item.parent_id
            }
            for item in result
        ]

        return success(result_list)

    @staticmethod
    def treeCategory(request):
        return success(TemplateCategoryService.get_category_hierarchy())

    @staticmethod
    def get_category_hierarchy(parent_id=0, level=1, max_level=5):
        if level > max_level:
            return []

        categories = TemplateCategory.objects.exclude(status=4).filter(parent_id=parent_id).order_by("-id")
        result = []

        for category in categories:
            children = TemplateCategoryService.get_category_hierarchy(parent_id=category.id, level=level + 1,
                                                                      max_level=max_level)
            result.append({
                "id": category.id,
                "name": category.name,
                "children": children
            })

        return result

