package com.kmall.api.service;

import com.google.common.collect.Maps;
import com.kmall.api.dao.ApiCategoryMapper;
import com.kmall.api.entity.CategoryVo;
import com.kmall.api.entity.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service
public class ApiCategoryService {
    @Autowired
    private ApiCategoryMapper categoryDao;


    public CategoryVo queryObject(Integer id) {
        return categoryDao.queryObject(id);
    }


    public List<CategoryVo> queryList(Map<String, Object> map) {
        return categoryDao.queryList(map);
    }

    public List<CategoryVo> queryListByParentId(Map<String, Object> map) {
        return categoryDao.queryListByParentId(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return categoryDao.queryTotal(map);
    }


    public void save(CategoryVo category) {
        categoryDao.save(category);
    }


    public void update(CategoryVo category) {
        categoryDao.update(category);
    }


    public void delete(Integer id) {
        categoryDao.delete(id);
    }


    public void deleteBatch(Integer[] ids) {
        categoryDao.deleteBatch(ids);
    }


    public List<CategoryVo> getFilterCategory(List<GoodsVo> goodsEntityList, List<CategoryVo> filterCategory){

        if (null != goodsEntityList && goodsEntityList.size() > 0) {
            List<Integer> categoryIds = new ArrayList();
            for (GoodsVo goodsVo : goodsEntityList) {
                if (null == goodsVo || null == goodsVo.getCategory_id()) {
                    continue;
                }
                categoryIds.add(goodsVo.getCategory_id());
            }
            //查找二级分类的parent_id
            Map categoryParam = Maps.newHashMap();
            categoryParam.put("ids", categoryIds);
            categoryParam.put("fields", "parent_id");
            List<CategoryVo> parentCategoryList = categoryDao.queryList(categoryParam);
            //
            List<Integer> parentIds = new ArrayList();
            for (CategoryVo categoryEntity : parentCategoryList) {
                parentIds.add(categoryEntity.getParent_id());
            }
            //一级分类
            categoryParam = Maps.newHashMap();
            categoryParam.put("fields", "id,name");
            categoryParam.put("order", "asc");
            categoryParam.put("sidx", "sort_order");
            categoryParam.put("ids", parentIds);
            List<CategoryVo> parentCategory = categoryDao.queryList(categoryParam);
            if (null != parentCategory) {
                filterCategory.addAll(parentCategory);
            }
        }
        return filterCategory;
    }

}
