from django.core.paginator import Paginator

from DCbackend.utils.common import success, pageData
from backend.models import Customer


class CustomerService:

    @staticmethod
    def getDetail(item: Customer):
        return {
            "id": item.id,
            'code': item.code,
            'name': item.name,
            'enName': item.en_name,
            'mobile': item.mobile,
            'contact': item.contact,
            'address': item.address,
            'other': item.other,
            '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

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

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

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