package com.fjhx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjhx.entity.Product;
import com.fjhx.service.ClassifyService;
import com.fjhx.service.ProductExService;
import com.fjhx.service.ProductService;
import com.fjhx.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ProductExServiceImpl implements ProductExService {

    @Autowired
    private ProductService productService;

    @Autowired
    private ClassifyService classifyService;

    @Override
    public Page<Product> getPage(Map<String, String> condition) {

        LambdaQueryWrapper<Product> wrapper = Wrappers.lambdaQuery();

        wrapper.orderByAsc(Product::getCode);

        String keyword = condition.get("keyword");
        if (ObjectUtil.isNotEmpty(keyword)) {
            wrapper.and(q -> q.like(Product::getCode, keyword).or().like(Product::getName, keyword));
        }

        // 如果传入分类id，查询分类已经分类下级
        String classifyId = condition.get("classifyId");
        if (ObjectUtil.isNotEmpty(classifyId)) {
            List<Long> childrenIdList = classifyService.getChildrenIdList(Long.valueOf(classifyId));
            wrapper.in(Product::getClassifyId, childrenIdList);
        }

        return productService.page(PageUtil.createPage(condition), wrapper);
    }

}
