from django.core.paginator import Paginator

from DCbackend.utils.common import success, fail, pageData
from backend.Form.ImageForm import ImageForm
from backend.Form.ParamsForm import ParamsForm
from backend.models import Params, Image


class ImageService:

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

    @staticmethod
    def Update(request):
        data = Image.objects.filter(id=request.POST.get("id")).first();
        if data is not None:
            data.category_id = request.POST.get("category_id")
            data.name = request.POST.get("name")
            data.width = request.POST.get("width")
            data.height = request.POST.get("height")
            data.path = request.POST.get("path")
            data.status = request.POST.get("status")
            data.save()
            return success("成功")
        else:
            return fail("更新图片信息失败")

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

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

    @staticmethod
    def getDetail(item: Image):
        return {
            "id": item.id,
            'categoryId': item.category_id,
            'name': item.name,
            'width': item.width,
            'height': item.height,
            'path': item.path,
            '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 = {}

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


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

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

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