import json

from django.core.paginator import Paginator

from DCbackend.utils.common import success, fail, pageData
from backend.Form.BrandForm import BrandForm
from backend.Form.ProductForm import ProductForm
from backend.Service.BrandService import BrandService
from backend.Service.ProductCategoryService import ProductCategoryService
from backend.Service.SupplierService import SupplierService
from backend.models import ProjectCategory, Brand, Product, ProductCategory, Supplier, ProductDocument


class ProductService:

    @staticmethod
    def Create(request):
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            links = json.loads(request.POST.get("links"))
            for link in links:
                pd = ProductDocument()
                pd.document_id = link
                pd.product_id = form.instance.id
                pd.status = 5
                pd.save()
            return success("成功")
        else:
            return fail(form.errors)

    @staticmethod
    def Update(request):
        data = Product.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.category_id = request.POST.get("category_id")
            data.brand_id = request.POST.get("brand_id")
            data.supplier_id = request.POST.get("supplier_id")
            data.name = request.POST.get("name")
            data.intro = request.POST.get("intro")
            data.price = request.POST.get("price")
            data.product_area = request.POST.get("product_area")
            data.is_safe = request.POST.get("is_safe")
            data.safe_time = request.POST.get("safe_time")
            data.is_package = request.POST.get("is_package")
            data.package_intro = request.POST.get("package_intro")
            data.qualifications = request.POST.get("qualifications")
            data.status = request.POST.get("status")
            data.attrs = request.POST.get("attrs")
            data.save()

            links = json.loads(request.POST.get("links"))

            ProductDocument.objects.filter(product_id=data.id).update(status=4)
            for link in links:
                pd = ProductDocument()
                pd.document_id = link
                pd.product_id = data.id
                pd.status = 5
                pd.save()

            return success("成功")
        else:
            return fail("更新产品信息")


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

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

    @staticmethod
    def getDetail(item: Product):

        category = ProductCategory.objects.filter(id=item.category_id).first()
        categoryData = ProductCategoryService.getDetail(category)

        brand = Brand.objects.filter(id=item.brand_id).first()
        brandData = BrandService.getDetail(brand)

        supplier = Supplier.objects.filter(id=item.supplier_id).first()
        supplierData = SupplierService.getDetail(supplier)
        where = {}
        where["product_id"] = item.id
        dpList = ProductDocument.objects.filter(**where).exclude(status=4).all()
        linkProduct = []
        for it in dpList:
            # temp = {
            #     'id': it.id,
            #     'product_id': it.product_id,
            #     'document_id': it.document_id,
            # }
            linkProduct.append( it.document_id)

        return {
            "id": item.id,
            'category_id': item.category_id,
            'brand_id': item.brand_id,
            'supplier_id': item.supplier_id,
            'linkDocument': linkProduct,
            'category': categoryData,
            'supplier': supplierData,
            'brand': brandData,
            'name': item.name,
            'intro': item.intro,
            'price': item.price,
            'product_area': item.product_area,
            'is_safe': item.is_safe,
            'safe_time': item.safe_time,
            'is_package': item.is_package,
            'package_intro': item.package_intro,
            'qualifications': item.qualifications,
            'createTime': item.create_time,
            'attrs': item.attrs,
            '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 = {}

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

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

        ids = request.POST.get("ids")
        if ids:
            idRange = json.loads(ids)
            where['id__in'] = idRange

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

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

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

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