from django.core.paginator import Paginator

from DCbackend.utils.common import success, fail, pageData
from backend.Form.BrandForm import BrandForm
from backend.Form.FormulaForm import FormulaForm
from backend.models import ProjectCategory, Brand, Formula


class FormulaService:

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

    @staticmethod
    def Update(request):
        data = Formula.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.name = request.POST.get("name")
            data.formula = request.POST.get("formula")
            data.use_status = request.POST.get("use_status")
            data.intro = request.POST.get("intro")
            data.params = request.POST.get("params")
            data.status = request.POST.get("status")
            data.point = request.POST.get("point")
            data.save()
            return success("成功")
        else:
            return fail("更新品牌信息失败")

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

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

    @staticmethod
    def getDetail(item: Formula):
        return {
            "id": item.id,
            'name': item.name,
            'formula': item.formula,
            'intro': item.intro,
            'use_status': item.use_status,
            'createTime': item.create_time,
            'params': item.params,
            'point': item.point,
            '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 = {}

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

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

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