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

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 com.cy.guoyan.admin.module.guoyan.dal.dataobject.researchtopiccategory.ResearchTopicCategoryDO;
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.stateownedreformbestpracticecategory.vo.*;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.stateownedreformbestpracticecategory.StateOwnedReformBestPracticeCategoryDO;
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.stateownedreformbestpracticecategory.StateOwnedReformBestPracticeCategoryMapper;
import static com.cy.guoyan.admin.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cy.guoyan.admin.module.system.enums.ErrorCodeConstants.*;

/**
 * 国资改革最佳实践主题分类 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class StateOwnedReformBestPracticeCategoryServiceImpl implements StateOwnedReformBestPracticeCategoryService {

    @Resource
    private StateOwnedReformBestPracticeCategoryMapper stateOwnedReformBestPracticeCategoryMapper;

    @Override
    public Long createStateOwnedReformBestPracticeCategory(StateOwnedReformBestPracticeCategorySaveReqVO createReqVO) {
        createReqVO.setStatus("正常");
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        StateOwnedReformBestPracticeCategoryDO data = BeanUtils.toBean(createReqVO, StateOwnedReformBestPracticeCategoryDO.class);
        data.setCreatorName(nickname);
        if (Objects.equals("0", createReqVO.getParentId())) {
            data.setParentId(null);
        }
        DefaultIdentifierGenerator generator = new DefaultIdentifierGenerator();
        data.setId(generator.nextId(null));
        data.setOid(UUID.randomUUID().toString().replace("-", ""));
        stateOwnedReformBestPracticeCategoryMapper.insert(data);
        return data.getId();
    }

    @Override
    public void updateStateOwnedReformBestPracticeCategory(StateOwnedReformBestPracticeCategorySaveReqVO updateReqVO) {
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        StateOwnedReformBestPracticeCategoryDO old = stateOwnedReformBestPracticeCategoryMapper.selectById(updateReqVO.getId());
        if (old == null) {
            throw exception(STATE_OWNED_REFORM_BEST_PRACTICE_CATEGORY_NOT_EXISTS);
        }

        // 更新
        StateOwnedReformBestPracticeCategoryDO updateObj = BeanUtils.toBean(updateReqVO, StateOwnedReformBestPracticeCategoryDO.class);
        updateObj.setUpdaterName(nickname);
        stateOwnedReformBestPracticeCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteStateOwnedReformBestPracticeCategory(Long id) {

        StateOwnedReformBestPracticeCategoryDO old = stateOwnedReformBestPracticeCategoryMapper.selectById(id);
        if (old == null) {
            throw exception(STATE_OWNED_REFORM_BEST_PRACTICE_CATEGORY_NOT_EXISTS);
        }

        if (old.getParentId() == null) {
            List<StateOwnedReformBestPracticeCategoryDO> sub = stateOwnedReformBestPracticeCategoryMapper.selectList(
                    new LambdaQueryWrapperX<StateOwnedReformBestPracticeCategoryDO>()
                            .eq(StateOwnedReformBestPracticeCategoryDO::getParentId, old.getOid()));

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

    @Override
        public void deleteStateOwnedReformBestPracticeCategoryListByIds(List<Long> ids) {
        // 校验存在
        validateStateOwnedReformBestPracticeCategoryExists(ids);
        // 删除
        stateOwnedReformBestPracticeCategoryMapper.deleteByIds(ids);
        }

    private void validateStateOwnedReformBestPracticeCategoryExists(List<Long> ids) {
        List<StateOwnedReformBestPracticeCategoryDO> list = stateOwnedReformBestPracticeCategoryMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(STATE_OWNED_REFORM_BEST_PRACTICE_CATEGORY_NOT_EXISTS);
        }
    }

    private void validateStateOwnedReformBestPracticeCategoryExists(Long id) {
        if (stateOwnedReformBestPracticeCategoryMapper.selectById(id) == null) {
            throw exception(STATE_OWNED_REFORM_BEST_PRACTICE_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public StateOwnedReformBestPracticeCategoryDO getStateOwnedReformBestPracticeCategory(Long id) {
        return stateOwnedReformBestPracticeCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<StateOwnedReformBestPracticeCategoryDO> getStateOwnedReformBestPracticeCategoryPage(StateOwnedReformBestPracticeCategoryPageReqVO pageReqVO) {
        return stateOwnedReformBestPracticeCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<StateOwnedReformBestPracticeCategoryDO> getStateOwnedReformBestPracticeCategoryTree(StateOwnedReformBestPracticeCategoryPageReqVO pageReqVO) {
        List<StateOwnedReformBestPracticeCategoryDO> categoryDOS = stateOwnedReformBestPracticeCategoryMapper.selectList(new LambdaQueryWrapperX<StateOwnedReformBestPracticeCategoryDO>()
//                .eq(ResearchTopicCategoryDO::getStatus, "正常")
                        .likeIfPresent(StateOwnedReformBestPracticeCategoryDO::getCategoryName, pageReqVO.getCategoryName())
                        .orderByAsc(StateOwnedReformBestPracticeCategoryDO::getOrderNum)
        );
        return buildTree(categoryDOS);
    }

    public List<StateOwnedReformBestPracticeCategoryDO> buildTree(List<StateOwnedReformBestPracticeCategoryDO> list) {

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

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

        // 3. 递归排序：先对子树排序，再对子节点排序
        Comparator<StateOwnedReformBestPracticeCategoryDO> comparator = Comparator
                .comparing(StateOwnedReformBestPracticeCategoryDO::getOrderNum, Comparator.nullsLast(Integer::compareTo));
        sortRecursively(rootList, comparator);

        return rootList;
    }

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


}