package com.zt.plat.module.base.service.doctemplate;

import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.module.base.controller.admin.doctemplate.vo.DocTemplateCategoryPageReqVO;
import com.zt.plat.module.base.controller.admin.doctemplate.vo.DocTemplateCategoryRespVO;
import com.zt.plat.module.base.controller.admin.doctemplate.vo.DocTemplateCategorySaveReqVO;
import com.zt.plat.module.base.convert.doctemplate.DocTemplateCategoryConvert;
import com.zt.plat.module.base.dal.dataobject.doctemplate.DocTemplateCategoryDO;
import com.zt.plat.module.base.dal.dao.doctemplate.DocTemplateCategoryMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.base.enums.ErrorCodeConstants.TEMPLATE_CATEGORY_NOT_EXISTS;

/**
 * 模板分类 Service 实现类
 *
 * @author 系统生成
 */
@Service
@Validated
public class DocTemplateCategoryServiceImpl implements DocTemplateCategoryService {

    @Resource
    private DocTemplateCategoryMapper templateCategoryMapper;

    @Override
    public Long createTemplateCategory(DocTemplateCategorySaveReqVO createReqVO) {
        // 插入
        DocTemplateCategoryDO templateCategory = DocTemplateCategoryConvert.INSTANCE.convert(createReqVO);
        // 设置默认值
        if (templateCategory.getSort() == null) {
            templateCategory.setSort(0);
        }
        templateCategoryMapper.insert(templateCategory);
        // 返回
        return templateCategory.getId();
    }

    @Override
    public void updateTemplateCategory(DocTemplateCategorySaveReqVO updateReqVO) {
        // 校验存在
        validateTemplateCategoryExists(updateReqVO.getId());
        // 更新
        DocTemplateCategoryDO updateObj = DocTemplateCategoryConvert.INSTANCE.convert(updateReqVO);
        templateCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteTemplateCategory(Long id) {
        // 校验存在
        validateTemplateCategoryExists(id);
        // 删除
        templateCategoryMapper.deleteById(id);
    }

    private void validateTemplateCategoryExists(Long id) {
        if (templateCategoryMapper.selectById(id) == null) {
            throw exception(TEMPLATE_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public DocTemplateCategoryRespVO getTemplateCategory(Long id) {
        DocTemplateCategoryDO templateCategory = templateCategoryMapper.selectById(id);
        return DocTemplateCategoryConvert.INSTANCE.convert(templateCategory);
    }

    @Override
    public PageResult<DocTemplateCategoryRespVO> getTemplateCategoryPage(DocTemplateCategoryPageReqVO pageReqVO) {
        PageResult<DocTemplateCategoryDO> pageResult = templateCategoryMapper.selectPage(pageReqVO);
        return DocTemplateCategoryConvert.INSTANCE.convertPage(pageResult);
    }

    @Override
    public List<DocTemplateCategoryRespVO> getTemplateCategoryList() {
        List<DocTemplateCategoryDO> list = templateCategoryMapper.selectList();
        return DocTemplateCategoryConvert.INSTANCE.convertList(list);
    }

    @Override
    public List<DocTemplateCategoryRespVO> buildTree() {
        // 1. 查询所有分类数据
        List<DocTemplateCategoryDO> allCategories = templateCategoryMapper.selectList();

        // 2. 转换为 VO
        List<DocTemplateCategoryRespVO> categoryVOs = DocTemplateCategoryConvert.INSTANCE.convertList(allCategories);

        // 3. 构建树形结构
        return buildTreeStructure(categoryVOs);
    }

    /**
     * 构建树形结构
     */
    private List<DocTemplateCategoryRespVO> buildTreeStructure(List<DocTemplateCategoryRespVO> categories) {
        // 1. 按 parentId 分组
        Map<String, List<DocTemplateCategoryRespVO>> groupByParentId = categories.stream()
                .collect(Collectors.groupingBy(node ->
                        node.getParentId() != null ? node.getParentId().toString() : "null"));

        // 2. 设置子节点并排序
        categories.forEach(node -> {
            List<DocTemplateCategoryRespVO> children = groupByParentId.get(node.getId().toString());
            if (children != null && !children.isEmpty()) {
                // 按排序号升序排列
                children.sort(Comparator.comparing(DocTemplateCategoryRespVO::getSort,
                        Comparator.nullsLast(Comparator.naturalOrder())));
                node.setChildren(children);
            }
        });

        // 3. 返回根节点（parentId 为 null 的节点）
        List<DocTemplateCategoryRespVO> rootNodes = groupByParentId.get("null");
        if (rootNodes != null) {
            // 根节点也要排序
            rootNodes.sort(Comparator.comparing(DocTemplateCategoryRespVO::getSort,
                    Comparator.nullsLast(Comparator.naturalOrder())));
            return rootNodes;
        }
        return List.of();
    }

    @Override
    public String getCategoryFullPath(Long categoryId) {
        if (categoryId == null) {
            return "";
        }

        // 构建分类路径
        List<String> pathNames = new ArrayList<>();
        Long currentId = categoryId;

        // 递归查找父级分类
        while (currentId != null) {
            DocTemplateCategoryDO category = templateCategoryMapper.selectById(currentId);
            if (category == null) {
                break;
            }
            // 将当前分类名称添加到列表开头
            pathNames.add(0, category.getCategoryName());
            // 继续查找父级
            currentId = category.getParentId();
        }

        // 用"/"拼接分类路径
        return String.join("/", pathNames);
    }

}
