from django.core.paginator import Paginator

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


class ParamsService:

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

    @staticmethod
    def Update(request):
        data = Params.objects.filter(id=request.POST.get("id")).first();
        if data is not None:
            data.code = request.POST.get("code")
            data.type = request.POST.get("type")
            data.intro = request.POST.get("intro")
            data.name = request.POST.get("name")
            data.value_type = request.POST.get("value_type")
            data.value_item = request.POST.get("value_item")
            data.value = request.POST.get("value")
            data.status = request.POST.get("status")
            data.save()
            return success("成功")
        else:
            return fail("更新参数信息失败")

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

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

    @staticmethod
    def getDetail(item: Params):
        return {
            "id": item.id,
            "type": item.type,
            'code': item.code,
            'name': item.name,
            'intro': item.intro,
            'value_type': item.value_type,
            'value_item': item.value_item,
            'value': item.value,
            '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 = {}
        code = request.POST.get("code", '')
        if code:
            where["code__icontains"] = code

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

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

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

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