package com.cy.guoyan.admin.module.guoyan.service.researchtopiccategory;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.cy.guoyan.admin.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cy.guoyan.admin.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.cy.guoyan.admin.module.guoyan.controller.admin.researchtopiccategory.vo.*;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.researchtopiccategory.ResearchTopicCategoryDO;
import com.cy.guoyan.admin.framework.common.pojo.PageResult;
import com.cy.guoyan.admin.framework.common.util.object.BeanUtils;

import com.cy.guoyan.admin.module.guoyan.dal.mysql.researchtopiccategory.ResearchTopicCategoryMapper;

import static com.cy.guoyan.admin.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cy.guoyan.admin.framework.common.util.collection.CollectionUtils.convertList;
import static com.cy.guoyan.admin.module.system.enums.ErrorCodeConstants.*;

/**
 * 国资研究专题分类 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ResearchTopicCategoryServiceImpl implements ResearchTopicCategoryService {

    @Resource
    private ResearchTopicCategoryMapper researchTopicCategoryMapper;

    @Override
    public Long createResearchTopicCategory(ResearchTopicCategorySaveReqVO createReqVO) {
        ResearchTopicCategoryDO categoryDO = researchTopicCategoryMapper.selectOne(
                new LambdaQueryWrapperX<ResearchTopicCategoryDO>()
                        .orderByDesc(ResearchTopicCategoryDO::getCategoryCode)
                        .last("LIMIT 1")
        );
        Long categoryCode = categoryDO.getCategoryCode();
        categoryCode++;
        createReqVO.setStatus("正常");
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        ResearchTopicCategoryDO data = BeanUtils.toBean(createReqVO, ResearchTopicCategoryDO.class);
        data.setCreatorName(nickname);
        data.setArticleCount(0);
        DefaultIdentifierGenerator generator = new DefaultIdentifierGenerator();
        if (data.getLevel() == 1) {
            data.setCategoryCode(categoryCode);
            data.setLevel1Code(categoryCode);
            data.setLevel1Name(data.getCategoryName());
            data.setOrder1(createReqVO.getOrder());
            data.setOrder2(0);
        }else if (data.getLevel() == 2) {
            ResearchTopicCategoryDO parent = researchTopicCategoryMapper.selectOne(
                    new LambdaQueryWrapperX<ResearchTopicCategoryDO>()
                            .eq(ResearchTopicCategoryDO::getCategoryCode, data.getParentCode()));

            data.setCategoryCode(categoryCode);
            data.setParentName(parent.getCategoryName());
            data.setLevel1Code(parent.getLevel1Code());
            data.setLevel1Name(parent.getLevel1Name());
            data.setLevel2Code(data.getCategoryCode());
            data.setLevel2Name(data.getCategoryName());
            data.setOrder1(parent.getOrder1());
            data.setOrder2(createReqVO.getOrder());
        }
        data.setId(generator.nextId(null));
        researchTopicCategoryMapper.insert(data);
        // 返回
        return data.getId();
    }

    @Override
    public void updateResearchTopicCategory(ResearchTopicCategorySaveReqVO updateReqVO) {
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        ResearchTopicCategoryDO old = researchTopicCategoryMapper.selectById(updateReqVO.getId());
        if (old== null) {
            throw exception(RESEARCH_TOPIC_CATEGORY_NOT_EXISTS);
        }

        if (old.getLevel() == 1) {
            updateReqVO.setOrder1(updateReqVO.getOrder());
            if (!Objects.equals(old.getOrder1(),updateReqVO.getOrder1())) {
                List<ResearchTopicCategoryDO> sub = researchTopicCategoryMapper.selectList(
                        new LambdaQueryWrapperX<ResearchTopicCategoryDO>()
                                .eq(ResearchTopicCategoryDO::getParentCode, updateReqVO.getCategoryCode()));

                sub.forEach(item -> {
                    item.setOrder1(updateReqVO.getOrder1());
                });
                researchTopicCategoryMapper.updateBatch(sub);
            }
            if (!Objects.equals(old.getCategoryName(), updateReqVO.getCategoryName())) {
                updateReqVO.setLevel1Name(updateReqVO.getCategoryName());
                List<ResearchTopicCategoryDO> sub = researchTopicCategoryMapper.selectList(
                        new LambdaQueryWrapperX<ResearchTopicCategoryDO>()
                                .eq(ResearchTopicCategoryDO::getParentCode, updateReqVO.getCategoryCode()));

                sub.forEach(item -> {
                    item.setParentName(updateReqVO.getCategoryName());
                    item.setLevel1Name(updateReqVO.getCategoryName());
                });
                researchTopicCategoryMapper.updateBatch(sub);
            }


        } else if (old.getLevel() == 2) {
            updateReqVO.setOrder2(updateReqVO.getOrder());
            updateReqVO.setLevel2Name(updateReqVO.getCategoryName());
        }
        // 更新
        ResearchTopicCategoryDO updateObj = BeanUtils.toBean(updateReqVO, ResearchTopicCategoryDO.class);
        updateObj.setUpdaterName(nickname);
        researchTopicCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteResearchTopicCategory(Long id) {
        // 校验存在
        ResearchTopicCategoryDO old = researchTopicCategoryMapper.selectById(id);
        if (old == null) {
            throw exception(RESEARCH_TOPIC_CATEGORY_NOT_EXISTS);
        }

        if (old.getLevel() == 1) {
            List<ResearchTopicCategoryDO> sub = researchTopicCategoryMapper.selectList(
                    new LambdaQueryWrapperX<ResearchTopicCategoryDO>()
                            .eq(ResearchTopicCategoryDO::getParentCode, old.getCategoryCode()));

            if (!CollUtil.isEmpty(sub)) {
                throw exception(CATEGORY_DELETE_HAS_CHILDREN);
            }
        }

        // 删除
        researchTopicCategoryMapper.deleteById(id);
    }

    @Override
        public void deleteResearchTopicCategoryListByIds(List<Long> ids) {
        // 校验存在
        validateResearchTopicCategoryExists(ids);
        // 删除
        researchTopicCategoryMapper.deleteByIds(ids);
        }

    private void validateResearchTopicCategoryExists(List<Long> ids) {
        List<ResearchTopicCategoryDO> list = researchTopicCategoryMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(RESEARCH_TOPIC_CATEGORY_NOT_EXISTS);
        }
    }

    private void validateResearchTopicCategoryExists(Long id) {
        if (researchTopicCategoryMapper.selectById(id) == null) {
            throw exception(RESEARCH_TOPIC_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public ResearchTopicCategoryDO getResearchTopicCategory(Long id) {
        return researchTopicCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<ResearchTopicCategoryDO> getResearchTopicCategoryPage(ResearchTopicCategoryPageReqVO pageReqVO) {
        return researchTopicCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ResearchTopicCategoryDO> getResearchTopicCategoryTree(ResearchTopicCategoryPageReqVO pageReqVO) {
        List<ResearchTopicCategoryDO> categoryDOS = researchTopicCategoryMapper.selectList(new LambdaQueryWrapperX<ResearchTopicCategoryDO>()
//                .eq(ResearchTopicCategoryDO::getStatus, "正常")
                .likeIfPresent(ResearchTopicCategoryDO::getCategoryName, pageReqVO.getCategoryName())
                .orderByAsc(ResearchTopicCategoryDO::getOrder1)
                .orderByAsc(ResearchTopicCategoryDO::getOrder2)
        );
        return buildTree(categoryDOS);
    }

//    public List<ResearchTopicCategoryDO> buildTree(List<ResearchTopicCategoryDO> list) {
//        // code -> item 的映射
//        Map<String, ResearchTopicCategoryDO> map = new HashMap<>();
//        for (ResearchTopicCategoryDO node : list) {
//            map.put(String.valueOf(node.getCategoryCode()), node);
//            node.setChildren(new ArrayList<>()); // 确保children初始化
//        }
//        List<ResearchTopicCategoryDO> rootList = new ArrayList<>();
//
//        for (ResearchTopicCategoryDO node : list) {
//            String parentCode = String.valueOf(node.getParentCode());
//            if (parentCode == null || !map.containsKey(parentCode)) {
//                // 顶级节点
//                rootList.add(node);
//            } else {
//                ResearchTopicCategoryDO parent = map.get(parentCode);
//                parent.getChildren().add(node);
//            }
//        }
//
//        return rootList;
//    }

    /**
     * 根据 categoryCode / parentCode 构建树，并按 order1 → order2 排序
     */
    public List<ResearchTopicCategoryDO> buildTree(List<ResearchTopicCategoryDO> list) {

        // 1. 预处理：建立 code→节点 映射，并初始化 children
        Map<String, ResearchTopicCategoryDO> map = new HashMap<>();
        for (ResearchTopicCategoryDO node : list) {
            map.put(String.valueOf(node.getCategoryCode()), node);
            node.setChildren(new ArrayList<>());     // 确保 children 不为 null
        }

        // 2. 组装父子关系
        List<ResearchTopicCategoryDO> rootList = new ArrayList<>();
        for (ResearchTopicCategoryDO node : list) {
            String parentCode = String.valueOf(node.getParentCode());
            if (parentCode == null || !map.containsKey(parentCode)) {
                // 顶级节点
                rootList.add(node);
            } else {
                map.get(parentCode).getChildren().add(node);
            }
        }

        // 3. 递归排序：先对子树排序，再对子节点排序
        Comparator<ResearchTopicCategoryDO> comparator = Comparator
                .comparing(ResearchTopicCategoryDO::getOrder1, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(ResearchTopicCategoryDO::getOrder2, Comparator.nullsLast(Integer::compareTo));

        sortRecursively(rootList, comparator);

        return rootList;
    }

    /**
     * 递归对子树进行排序
     */
    private void sortRecursively(List<ResearchTopicCategoryDO> nodes,
                                 Comparator<ResearchTopicCategoryDO> comparator) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        // 先对子节点列表排序
        nodes.sort(comparator);
        // 再递归对子节点的子节点排序
        for (ResearchTopicCategoryDO node : nodes) {
            sortRecursively(node.getChildren(), comparator);
        }
    }




}