package jnpf.cultivate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.cultivate.mapper.FtbCultivateLearnCategoriesMapper;
import jnpf.cultivate.service.FtbCultivateLearnCategoriesService;
import jnpf.cultivate.service.FtbCultivateLearnTaskListService;
import jnpf.model.cultivate.dto.learn.FtbCultivateLearnCategoriesDto;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnCategories;
import jnpf.model.cultivate.req.learn.AddLearnCategoryReq;
import jnpf.model.cultivate.req.learn.QueryLearnCategoryListReq;
import jnpf.model.cultivate.req.learn.UpdateLearnCategoryReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author 许贵林
 * @description 数据库操作Service实现
 * @createDate 2024-05-08 09:42:09
 */
@Service
public class FtbCultivateLearnCategoriesServiceImpl extends ServiceImpl<FtbCultivateLearnCategoriesMapper, FtbCultivateLearnCategories>
        implements FtbCultivateLearnCategoriesService {


    @Autowired
    private FtbCultivateLearnTaskListService taskListService;

    /**
     * 查询所有 返回tree
     *
     * @param req
     * @return
     */
    @Override
    public List<FtbCultivateLearnCategoriesDto> listCategory(QueryLearnCategoryListReq req) {
        //type 0 查询所有分类（默认）  1 查询一级分类
        if (req.getType() == null) {//默认查询所有
            req.setType(0);
        }
        if (!req.getType().equals(0) && !req.getType().equals(1)) {
            throw new RuntimeException("type参数错误");
        }
        QueryWrapper<FtbCultivateLearnCategories> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(req.getType().equals(1), FtbCultivateLearnCategories::getParentId, "")
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0)
                .orderByAsc(FtbCultivateLearnCategories::getCreatorTime);
        List<FtbCultivateLearnCategories> categoriesList = baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(categoriesList)) {
            return new ArrayList<>();
        }
        List<FtbCultivateLearnCategoriesDto> retList = new ArrayList<>();
        if (req.getType().equals(1)) {
            //一级分类不需要够级分类树
            retList = BeanUtil.copyToList(categoriesList, FtbCultivateLearnCategoriesDto.class);
        } else {
            retList = buildCateTree(categoriesList);
        }
        if (req.getIsQueryNum().equals(1)) {
            Map<String, Integer> countMap = taskListService.groupCountCateNum();
            fillCateNum(retList, countMap);
        }
        return retList;
    }

    /**
     * 填充分类的任务数量
     *
     * @param retList
     * @param countMap
     */
    private void fillCateNum(List<FtbCultivateLearnCategoriesDto> retList, Map<String, Integer> countMap) {
        if (CollectionUtil.isEmpty(retList) || CollectionUtil.isEmpty(countMap)) {
            return;
        }
        for (FtbCultivateLearnCategoriesDto dto : retList) {
            Integer count = countMap.get(dto.getId());
            if (count != null) {
                dto.setTotleNum(count);
            }
            List<FtbCultivateLearnCategoriesDto> children = dto.getChildren();
            if (CollectionUtil.isNotEmpty(children)) {
                fillCateNum(children, countMap);
            }
        }
    }


    /**
     * 添加分类
     *
     * @param req
     * @return
     */
    @Override
    public FtbCultivateLearnCategories insertData(AddLearnCategoryReq req) {
        //检测名称是否重复
        QueryWrapper<FtbCultivateLearnCategories> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbCultivateLearnCategories::getName, req.getName())
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0);
        Long count = baseMapper.selectCount(wrapper);
        if (null != count && count > 0) {
            throw new RuntimeException("分类名称已经存在");
        }
        //查询检测父级分类是否存在
        FtbCultivateLearnCategories parent = null;
        if (StringUtils.isNotEmpty(req.getParentId())) {
            parent = queryAndCheckParent(req.getParentId());
        }

        //添加分类
        FtbCultivateLearnCategories categories = new FtbCultivateLearnCategories();
        categories.setName(req.getName());
        categories.setParentId(req.getParentId());
        String path = "";
        if (null != parent) {
            //检查是否超过2级
            if (StringUtils.isNotEmpty(parent.getPath())) {
                if (parent.getPath().split("-").length > 2) {
                    throw new RuntimeException("分类最多支持2级");
                }
            }

            if (StringUtils.isNotEmpty(parent.getPath())) {
                path = parent.getPath() + "-" + parent.getId();
            } else {
                path = parent.getId();
            }
        }
        categories.setPath(path);
        categories.setEnabledMark(0);
        baseMapper.insert(categories);
        return categories;
    }

    /**
     * 修改分类
     *
     * @param id  修改的分类ID
     * @param req
     * @return
     */
    @Override
    public FtbCultivateLearnCategories updateData(String id, UpdateLearnCategoryReq req) {
        //检测分类是否删除
        queryAndCheckById(id);
        //检测名称是否重复
        QueryWrapper<FtbCultivateLearnCategories> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbCultivateLearnCategories::getName, req.getName())
                .ne(FtbCultivateLearnCategories::getId, id)
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0);
        Long count = baseMapper.selectCount(wrapper);
        if (null != count && count > 0) {
            throw new RuntimeException("分类名称已经存在");
        }

        FtbCultivateLearnCategories parent = null;
        if (StringUtils.isNotEmpty(req.getParentId())) {
            parent = queryAndCheckParent(req.getParentId());
        }

        //修改分类
        FtbCultivateLearnCategories categories = new FtbCultivateLearnCategories();
        categories.setName(req.getName());
        categories.setId(id);
        categories.setEnabledMark(0);
        baseMapper.updateById(categories);
        return categories;

    }

    /**
     * 查询分类信息
     *
     * @param parentId 分类ID
     * @return
     */
    private FtbCultivateLearnCategories queryAndCheckParent(String parentId) {
        FtbCultivateLearnCategories parent = baseMapper.selectById(parentId);
        if (null == parent) {
            throw new RuntimeException("父级分类不存在");
        }
        if (parent.getEnabledMark().equals(1)) {
            throw new RuntimeException("父级分类已被删除");
        }
        return parent;
    }

    /**
     * 根据分类ID查询分类信息
     *
     * @param id 分类ID
     * @return
     */
    @Override
    public FtbCultivateLearnCategories queryAndCheckById(String id) {
        FtbCultivateLearnCategories entity = baseMapper.selectById(id);
        if (null == entity) {
            throw new RuntimeException("分类不存在");
        }
        if (entity.getEnabledMark().equals(1)) {
            throw new RuntimeException("分类已经删除");
        }
        return entity;
    }

    /**
     * 删除分类
     *
     * @param id 分类ID
     */
    @Override
    public void deleteData(String id) {
        List<String> deleteIds = new ArrayList<>();
        deleteIds.add(id);
        //检测分类是否删除
        FtbCultivateLearnCategories currCategory = queryAndCheckById(id);

        //检测分类下是否有下级分类
        List<String> childCategoryIds = queryChildCategoryIds(currCategory);
        if (CollectionUtil.isNotEmpty(childCategoryIds)) {
            deleteIds.addAll(childCategoryIds);
        }

        //检测分类是是否有任务
        if (taskListService.checkHasTask(deleteIds)) {
            throw new RuntimeException("分类下存在任务，请先删除任务");
        }
        //删除分类
        List<FtbCultivateLearnCategories> updateList = new ArrayList<>();
        for (String deleteId : deleteIds) {
            FtbCultivateLearnCategories categories = new FtbCultivateLearnCategories();
            categories.setId(deleteId);
            categories.setEnabledMark(1);
            updateList.add(categories);
        }
        updateBatchById(updateList);
    }

    /**
     * 查询分类下所有子分类ID
     *
     * @param currCategory 父分类ID
     * @return
     */
    public List<String> queryChildCategoryIds(FtbCultivateLearnCategories currCategory) {
        String path = "";
        if (StringUtils.isNotEmpty(currCategory.getPath())) {
            path = currCategory.getPath() + "-" + currCategory.getId();
        } else {
            path = currCategory.getId();
        }
        QueryWrapper<FtbCultivateLearnCategories> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .likeRight(FtbCultivateLearnCategories::getPath, path)
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0);
        List<FtbCultivateLearnCategories> categoriesList = baseMapper.selectList(wrapper);
        List<String> childIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(categoriesList)) {
            for (FtbCultivateLearnCategories ftbNoticeCategories : categoriesList) {
                childIds.add(ftbNoticeCategories.getId());
            }
        }
        return childIds;
    }

    /**
     * 查询分类下所有子分类
     *
     * @param parentId 父分类ID
     * @return
     */
    @Override
    public List<FtbCultivateLearnCategories> queryChildCategory(String parentId) {
        QueryWrapper<FtbCultivateLearnCategories> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbCultivateLearnCategories::getParentId, parentId)
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 查询分类下子分类数量
     *
     * @param parentId 父分类ID
     * @return
     */
    @Override
    public Long queryChildCategoryNum(String parentId) {
        QueryWrapper<FtbCultivateLearnCategories> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbCultivateLearnCategories::getParentId, parentId)
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0);
        return baseMapper.selectCount(wrapper);
    }


    /**
     * 构建分类树
     *
     * @param categoriesList
     * @return
     */
    private List<FtbCultivateLearnCategoriesDto> buildCateTree(List<FtbCultivateLearnCategories> categoriesList) {
        List<FtbCultivateLearnCategoriesDto> categoriesDtoList = BeanUtil.copyToList(categoriesList, FtbCultivateLearnCategoriesDto.class);
        List<FtbCultivateLearnCategoriesDto> retList = new ArrayList<>();
        Map<String, List<FtbCultivateLearnCategoriesDto>> map = new HashMap<>();
        for (FtbCultivateLearnCategoriesDto dto : categoriesDtoList) {
            fillCategoryLevel(dto);
            if (StringUtils.isEmpty(dto.getParentId())) {
                retList.add(dto);
            } else {
                List<FtbCultivateLearnCategoriesDto> tempList = map.get(dto.getParentId());
                if (CollectionUtil.isEmpty(tempList)) {
                    tempList = new ArrayList<>();
                }
                tempList.add(dto);
                map.put(dto.getParentId(), tempList);
            }
        }

        for (FtbCultivateLearnCategoriesDto dto : categoriesDtoList) {
            List<FtbCultivateLearnCategoriesDto> child = map.get(dto.getId());
            if (CollectionUtil.isNotEmpty(child)) {
                dto.setChildren(child);
            }
        }
        return retList;
    }

    /**
     * 填充分类级别
     *
     * @param dto
     */
    private void fillCategoryLevel(FtbCultivateLearnCategoriesDto dto) {
        if (StringUtils.isEmpty(dto.getPath())) {
            dto.setLevel(0);
            return;
        }
        String[] split = dto.getPath().split("-");
        dto.setLevel(split.length);
    }

    /**
     * 批量查询分类信息
     *
     * @param ids 分类ID 集合
     * @return
     */
    public Map<String, FtbCultivateLearnCategories> queryCateByIds(List<String> ids) {
        Map<String, FtbCultivateLearnCategories> ret = new HashMap<>();
        if (CollectionUtil.isEmpty(ids)) {
            return ret;
        }
        LambdaQueryWrapper<FtbCultivateLearnCategories> wrapper = new LambdaQueryWrapper<FtbCultivateLearnCategories>()
                .in(FtbCultivateLearnCategories::getId, ids)
                .eq(FtbCultivateLearnCategories::getEnabledMark, 0);
        List<FtbCultivateLearnCategories> list = baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(list)) {
            return ret;
        }
        for (FtbCultivateLearnCategories cat : list) {
            ret.put(cat.getId(), cat);
        }
        return ret;
    }

    /**
     * 查询分类和父分类
     *
     * @param cateId 分类id
     * @return
     */
    @Override
    public List<FtbCultivateLearnCategories> queryCategoryAndParentCategory(String cateId) {
        List<FtbCultivateLearnCategories> list = new ArrayList<>();
        if (StringUtils.isEmpty(cateId)) {
            return list;
        }
        FtbCultivateLearnCategories currCate = baseMapper.selectById(cateId);
        if (currCate == null) {
            return list;
        }
        if (StringUtils.isNotEmpty(currCate.getPath())) {
            String[] split = currCate.getPath().split("-");
            for (int i = 0; i < split.length; i++) {
                if (StringUtils.isNotEmpty(split[i])) {
                    FtbCultivateLearnCategories last = baseMapper.selectById(split[i]);
                    if (last == null) {
                        break;
                    }
                    list.add(last);
                }
            }
        }
        list.add(currCate);
        return list;
    }


}




