from django.core.paginator import Paginator

from DCbackend.utils.common import success, fail, pageData
from backend.Form.TemplateForm import TemplateForm
from backend.Service.TemplateCategoryService import TemplateCategoryService
from backend.models import Template, TemplateCategory


class TemplateService:

    @staticmethod
    def Create(request):
        try:
            form = TemplateForm(request.POST)
            if form.is_valid():
                template = form.save()
                # 将 code 更新为 id
                template.code = str(template.id)
                template.save()

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

        except Exception as e:
            return fail(str(e))
    @staticmethod
    def Update(request):
        data = Template.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.content = request.POST.get("content")
            data.attrs = request.POST.get("attrs")
            data.category_id = request.POST.get("category_id")
            data.status = request.POST.get("status")
            data.lay_id = request.POST.get("lay_id")
            data.intro = request.POST.get("intro")
            data.type = request.POST.get("type")
            data.save()
            return success("更新成功")
        else:
            return fail("更新模板信息")

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

    @staticmethod
    def Delete(request):
        Template.objects.filter(id=request.POST.get("id")).update(status=4)
        return success("删除成功")

    @staticmethod
    def getDetail(item: Template):
        category = TemplateCategory.objects.filter(id=item.category_id).first()
        categoryData = TemplateCategoryService.getDetail(category)
        return {
            "id": item.id,
            "code":item.code,
            'name': item.name,
            'lay_id': item.lay_id,
            'intro': item.intro,
            'type': item.type,
            'category_id': item.category_id,
            'category': categoryData,
            'content': item.content,
            'attrs':item.attrs,
            'createTime': item.create_time,
            'status': item.status
        }

    @staticmethod
    def Search(request):
        page = request.POST.get("page")
        pageSize = request.POST.get("pageSize")
        if page is None:
            page = 1
        if pageSize is None:
            pageSize = 1

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

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

        status = request.POST.get("status")
        if status:
            where['status'] = status

        paginator = Paginator(Template.objects.filter(**where).exclude(status=4).order_by("-id"), pageSize)  # 每页显示10条数据
        page_obj = paginator.get_page(page)
        dataList = []
        for item in page_obj:
            info = TemplateService.getDetail(item)
            dataList.append(info)
        return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))

    @staticmethod
    def pageTemplate(request):
        page = request.POST.get("page")
        pageSize = request.POST.get("pageSize")
        if page is None:
            page = 1
        if pageSize is None:
            pageSize = 1

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

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

        status = request.POST.get("status")
        if status:
            where['status'] = status

        paginator = Paginator(Template.objects.filter(**where).exclude(status=4).order_by("-id").values('id','name','category_id','create_time','status'), pageSize)  # 每页显示10条数据
        page_obj = paginator.get_page(page)
        # 获取所有需要的 category_id
        category_ids = set(info['category_id'] for info in page_obj if info['category_id'] is not None)

        # 一次性查询所有需要的 DocumentCategory
        categories = {
            cat['id']: cat['name']
            for cat in TemplateCategory.objects.filter(id__in=category_ids).exclude(status=4).values('id', 'name')
        }
        dataList = []
        for info in page_obj:
            info_dict = dict(info)  # 转换为可变的字典
            category_id = info_dict['category_id']
            info_dict['type_name'] = categories.get(category_id, '')
            dataList.append(info_dict)
        return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))