package com.younike.system.service.impl;

import java.util.*;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.exception.GlobalException;
import com.younike.system.domain.CateDimension;
import com.younike.system.domain.Dimension;
import com.younike.system.domain.vo.CategoryVo;
import com.younike.system.mapper.CateDimensionMapper;
import com.younike.system.mapper.DimensionMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.younike.system.mapper.CategoryMapper;
import com.younike.system.domain.Category;
import com.younike.system.service.ICategoryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 分类Service业务层处理
 *
 * @author elev
 * @date 2022-01-04
 */
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DimensionMapper dimensionMapper;

    @Autowired
    private CateDimensionMapper cateDimensionMapper;

    @Override
    @Transactional
    public AjaxResult submit(CategoryVo categoryVo) {
        if (categoryVo == null
                || StringUtils.isEmpty(categoryVo.getCategoryName())
                || categoryVo.getDimensionList() == null
                || categoryVo.getDimensionList().size() == 0) {
            return AjaxResult.error("参数错误");
        }
        if (categoryVo.getCategoryId() == null) {
            categoryVo.setType(0);
            if (categoryVo.getSorting() == null) {
                // 查询 系统中最大的分类排序
                List<Category> categoryList = categoryMapper.getByParentId(null);
                if (CollectionUtils.isNotEmpty(categoryList)) {
                    Optional<Category> maxSorting = categoryList.stream().max(Comparator.comparing(Category::getSorting));
                    maxSorting.ifPresent(vo -> categoryVo.setSorting(vo.getSorting()+1));
                } else {
                    categoryVo.setSorting(1);
                }
            }
            int insertCategory = categoryMapper.insertCategory(categoryVo);
            if (insertCategory < 1) {
                throw new GlobalException("添加失败");
            }
        } else {
            int updateCategory = categoryMapper.updateCategory(categoryVo);
            if (updateCategory < 1) {
                throw new GlobalException("修改失败");
            }
        }
        List<Dimension> updateList = new ArrayList<>();
        List<Dimension> insertList = new ArrayList<>();
        List<CateDimension> cateDimensionList = new ArrayList<>();
        categoryVo.getDimensionList().forEach(dimension -> {
            if (dimension.getDimensionId() != null) {
                updateList.add(dimension);
            }
            if (dimension.getDimensionId() == null && (dimension.getDelFlag() == null || dimension.getDelFlag() == 0)) {
                insertList.add(dimension);
            }
        });
        if (updateList.size() > 0) {
            int updateBatch = dimensionMapper.updateBatch(updateList);
            if (updateBatch < 1) {
                throw new GlobalException("添加失败");
            }
        }
        if (insertList.size() > 0) {
            int insertBatch = dimensionMapper.insertBatch(insertList);
            if (insertBatch < 1) {
                throw new GlobalException("添加失败");
            }
            insertList.forEach(dimension -> {
                CateDimension cateDimension = new CateDimension();
                cateDimension.setCategoryId(categoryVo.getCategoryId());
                cateDimension.setDimensionId(dimension.getDimensionId());
                cateDimensionList.add(cateDimension);
            });
        }
        if (cateDimensionList.size() > 0) {
            int insertBatch = cateDimensionMapper.insertBatch(cateDimensionList);
            if (insertBatch < 1) {
                throw new GlobalException("添加失败");
            }
        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult submitChild(Category category) {
        if (category == null || StringUtils.isEmpty(category.getParentId()) || StringUtils.isEmpty(category.getCategoryName())) {
            return AjaxResult.error("参数错误");
        }
        if (category.getCategoryId() == null) {
            category.setType(1);
            if (category.getSorting() == null) {
                // 查询 系统中最大的分类排序
                List<Category> categoryList = categoryMapper.getByParentId(category.getParentId());
                if (CollectionUtils.isNotEmpty(categoryList)) {
                    Optional<Category> maxSorting = categoryList.stream().max(Comparator.comparing(Category::getSorting));
                    maxSorting.ifPresent(vo -> category.setSorting(vo.getSorting()+1));
                } else {
                    category.setSorting(1);
                }
            }
            int insertCategory = categoryMapper.insertCategory(category);
            if (insertCategory < 1) {
                throw new GlobalException("添加失败");
            }
        } else {
            int updateCategory = categoryMapper.updateCategory(category);
            if (updateCategory < 1) {
                throw new GlobalException("修改失败");
            }
        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public List<CategoryVo> categoryList(Integer bizType) {
        List<CategoryVo> categoryList = categoryMapper.getCategoryList(bizType);
        if (categoryList == null || categoryList.size() == 0) {
            return categoryList;
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return categoryVoList;
    }

    @Override
    public List<CategoryVo> categoryTree() {
        List<CategoryVo> categoryList = categoryMapper.selectCategoriesList(null);
        if (categoryList == null || categoryList.size() == 0) {
            return categoryList;
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return categoryVoList;
    }

    @Override
    public int updateSortingBatch(List<Category> categoryList) {
        return categoryMapper.updateSortingBatch(categoryList);
    }

    /**
     * 查询分类
     *
     * @param categoryId 分类主键
     * @return 分类
     */
    @Override
    public Category selectCategoryByCategoryId(Long categoryId) {
        return categoryMapper.selectCategoryByCategoryId(categoryId);
    }

    /**
     * 查询分类列表
     *
     * @param category 分类
     * @return 分类
     */
    @Override
    public List<Category> selectCategoryList(Category category)
    {
        return categoryMapper.selectCategoryList(category);
    }

    /**
     * 新增分类
     *
     * @param category 分类
     * @return 结果
     */
    @Override
    public int insertCategory(Category category) {
        category.setCreateTime(LocalDateTime.now());
        return categoryMapper.insertCategory(category);
    }

    /**
     * 修改分类
     *
     * @param category 分类
     * @return 结果
     */
    @Override
    public int updateCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.updateCategory(category);
    }

    /**
     * 批量删除分类
     *
     * @param categoryIds 需要删除的分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryByCategoryIds(Long[] categoryIds) {
        return categoryMapper.deleteCategoryByCategoryIds(categoryIds);
    }

    /**
     * 删除分类信息
     *
     * @param categoryId 分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryByCategoryId(Long categoryId) {
        return categoryMapper.deleteCategoryByCategoryId(categoryId);
    }

    /**
     * 获取全部服务数据
     * @return
     */
    @Override
    public AjaxResult selectCategoriesList(Integer bizType) {
        //获取全部服务分类数据
        List<CategoryVo> categoryList = categoryMapper.selectCategoriesList(bizType);
        if (categoryList == null || categoryList.size() == 0) {
            return AjaxResult.success(null);
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return AjaxResult.success(categoryVoList);
    }

    /**
     * 首页服务数据
     * @return
     */
    @Override
    public AjaxResult getHomeCategoriesList(Integer bizType) {
        List<Category> categoryList = categoryMapper.getHomeCategoriesList(bizType);
        return AjaxResult.success(categoryList);
    }

    @Override
    public AjaxResult selectCategoriesListServer(Integer bizType) {
        //获取全部服务分类数据
        List<CategoryVo> categoryList = new ArrayList<>();
        CategoryVo allInfo = new CategoryVo();
        allInfo.setParentId(null);
        allInfo.setType(0);
        allInfo.setCategoryId(0l);
        allInfo.setCategoryName("全部服务");
        categoryList.add(allInfo);
        categoryList.addAll(categoryMapper.selectCategoriesList(bizType));
        if (categoryList == null || categoryList.size() == 0) {
            return AjaxResult.success(null);
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                List<CategoryVo> childList = new ArrayList<>();
                CategoryVo info = new CategoryVo();
                BeanUtils.copyProperties(categoryVo, info);  ;
                info.setChildrenCategory(null);
                childList.add(info);
                if(!ObjectUtils.isEmpty(categoryMap.get(categoryVo.getCategoryId().toString()))){
                    childList.addAll(categoryMap.get(categoryVo.getCategoryId().toString()));
                }
                categoryVo.setChildrenCategory(childList);
            });
        }
        return AjaxResult.success(categoryVoList);
    }
}
