from django.core.paginator import Paginator

from DCbackend.utils.common import success, fail, pageData
from backend.Form.ProjectCategoryForm import ProjectCategoryForm
from backend.models import ProjectCategory, DefaultStatus


class ProjectCategoryService:

    @staticmethod
    def Create(request):
        form = ProjectCategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return success("成功")
        else:
            return fail(form.errors)

    @staticmethod
    def Update(request):
        data = ProjectCategory.objects.filter(id=request.POST.get("id")).first();
        if data is not None:
            data.code = request.POST.get("code")
            data.name = request.POST.get("name")
            data.status = request.POST.get("status")
            data.save()
            return success("成功")
        else:
            return fail("保存分类失败")

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

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

    @staticmethod
    def getDetail(category: ProjectCategory):

        return {
            "id": category.id,
            'code': category.code,
            'name': category.name,
            'createTime': category.create_time,
            'status': category.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 = 10

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

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

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

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