package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.cultivate.mapper.CultivateCoverCategoryMapper;
import jnpf.cultivate.mapper.CultivateCoverInfoMapper;
import jnpf.cultivate.service.CultivateCoverCategoryService;
import jnpf.enums.cultivate.CultivateIsSystemEnum;
import jnpf.model.cultivate.po.common.FtbCultivateCoverCategoryEntity;
import jnpf.model.cultivate.po.common.FtbCultivateCoverInfoEntity;
import jnpf.model.cultivate.v2.common.vo.V2BaseIdNameVo;
import jnpf.model.cultivate.v2.exam.req.V2SaveCoverCategoryReq;
import jnpf.model.cultivate.v2.exam.vo.V2TreeCoverVo;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Desc 封面分类-实现类
 * @Author shangyi
 * @Date 2026/1/22
 */
@Slf4j
@Service
public class CultivateCoverCategoryServiceImpl extends ServiceImpl<CultivateCoverCategoryMapper, FtbCultivateCoverCategoryEntity> implements CultivateCoverCategoryService {

    @Autowired
    private CultivateCoverInfoMapper coverInfoMapper;

    @Override
    public String saveCategory(V2SaveCoverCategoryReq req) {
        // 检查名称是否重复（排除当前ID）
        LambdaQueryWrapper<FtbCultivateCoverCategoryEntity> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(FtbCultivateCoverCategoryEntity::getName, req.getName());
        checkWrapper.ne(StringUtil.isNotEmpty(req.getId()), FtbCultivateCoverCategoryEntity::getId, req.getId());
        if (this.count(checkWrapper) > 0) {
            throw new RuntimeException("封面分类名称已存在，请勿重复添加！");
        }
        FtbCultivateCoverCategoryEntity entity = new FtbCultivateCoverCategoryEntity();
        entity.setName(req.getName());
        entity.setIsSystem(CultivateIsSystemEnum.NO.getCode());
        if (StringUtil.isNotEmpty(req.getId())) {
            FtbCultivateCoverCategoryEntity byId = getById(req.getId());
            if (byId == null) {
                throw new RuntimeException("当前封面分类不存在！");
            }
            if (byId.getIsSystem() == 1) {
                throw new RuntimeException("系统封面分类不允许修改！");
            }
            entity.setId(req.getId());
            updateById(entity);
            return entity.getId();
        } else {
            //查询分类个数不能超过50个
            Long count = querySelfCount();
            if (count >= 50) {
                throw new RuntimeException("封面分类个数不能超过50个！");
            }
        }
        save(entity);
        return entity.getId();
    }

    private Long querySelfCount() {
        LambdaQueryWrapper<FtbCultivateCoverCategoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FtbCultivateCoverCategoryEntity::getIsSystem, CultivateIsSystemEnum.NO.getCode());
        return this.count(wrapper);
    }

    @Override
    public void delCategory(String id) {
        FtbCultivateCoverCategoryEntity byId = getById(id);
        if (byId == null) {
            throw new RuntimeException("当前封面分类不存在！");
        }
        if (Objects.equals(byId.getIsSystem(), CultivateIsSystemEnum.YES.getCode())) {
            throw new RuntimeException("系统封面分类不允许删除！");
        }
        //先删除此分类下面所有的分类
        coverInfoMapper.delete(new LambdaQueryWrapper<FtbCultivateCoverInfoEntity>().eq(FtbCultivateCoverInfoEntity::getCategoryId, id));
        this.baseMapper.deleteById(id);
    }

    @Override
    public List<V2BaseIdNameVo> getCategoryList(Integer isSystem) {
        List<FtbCultivateCoverCategoryEntity> list = this.list(new LambdaQueryWrapper<FtbCultivateCoverCategoryEntity>()
                .eq(isSystem != null, FtbCultivateCoverCategoryEntity::getIsSystem, isSystem)
                .orderByDesc(FtbCultivateCoverCategoryEntity::getIsSystem)
                .orderByAsc(FtbCultivateCoverCategoryEntity::getCreatorTime));
        return list.stream().map(e ->
                new V2BaseIdNameVo().setId(e.getId()).setName(e.getName()).setIsSystem(e.getIsSystem())).collect(Collectors.toList());
    }

    @Override
    public List<V2TreeCoverVo> treeCover() {
        //所有的封面分类
        List<FtbCultivateCoverCategoryEntity> categorylist = this.list(new LambdaQueryWrapper<FtbCultivateCoverCategoryEntity>()
                .orderByDesc(FtbCultivateCoverCategoryEntity::getIsSystem).orderByAsc(FtbCultivateCoverCategoryEntity::getCreatorTime));
        if (CollectionUtil.isEmpty(categorylist)) {
            return Collections.emptyList();
        }
        //所有的封面
        List<FtbCultivateCoverInfoEntity> coverList = coverInfoMapper.selectList(new LambdaQueryWrapper<>());
        //封装分类封面树
        List<V2TreeCoverVo> treeCoverList = categorylist.stream().map(e -> {
            V2TreeCoverVo parent = new V2TreeCoverVo();
            parent.setCategoryId(e.getId()).setCategoryName(e.getName()).setIsSystem(e.getIsSystem());
            List<FtbCultivateCoverInfoEntity> children = coverList.stream().filter(cover -> cover.getCategoryId().equals(e.getId())).collect(Collectors.toList());
            parent.setCoverList(children.stream().map(c -> {
                V2TreeCoverVo child = new V2TreeCoverVo();
                child.setCategoryId(e.getId()).setCategoryName(e.getName())
                        .setPath(c.getPath()).setIsSystem(c.getIsSystem());
                return child;
            }).collect(Collectors.toList()));
            return parent;
        }).collect(Collectors.toList());
        return treeCoverList;
    }


}
