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

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.controller.admin.researchtopiccategory.vo.ResearchTopicCategoryPageReqVO;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.researchtopiccategory.ResearchTopicCategoryDO;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.researchtopicinfo.ResearchTopicInfoDO;
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.stateownedreformlawcategory.vo.*;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.stateownedreformlawcategory.StateOwnedReformLawCategoryDO;
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.stateownedreformlawcategory.StateOwnedReformLawCategoryMapper;

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 StateOwnedReformLawCategoryServiceImpl implements StateOwnedReformLawCategoryService {

    @Resource
    private StateOwnedReformLawCategoryMapper stateOwnedReformLawCategoryMapper;

    @Override
    public Long createStateOwnedReformLawCategory(StateOwnedReformLawCategorySaveReqVO createReqVO) {
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));

        StateOwnedReformLawCategoryDO categoryDO = stateOwnedReformLawCategoryMapper.selectOne(
                new LambdaQueryWrapperX<StateOwnedReformLawCategoryDO>()
                        .orderByDesc(StateOwnedReformLawCategoryDO::getCategoryCode)
                        .last("LIMIT 1")
        );

        Long categoryCode = categoryDO.getCategoryCode();
        categoryCode++;
        createReqVO.setStatus("正常");
        StateOwnedReformLawCategoryDO data = BeanUtils.toBean(createReqVO, StateOwnedReformLawCategoryDO.class);
        data.setCreatorName(nickname);
        data.setInfoCount(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) {
            StateOwnedReformLawCategoryDO parent = stateOwnedReformLawCategoryMapper.selectOne(
                    new LambdaQueryWrapperX<StateOwnedReformLawCategoryDO>()
                            .eq(StateOwnedReformLawCategoryDO::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));
        stateOwnedReformLawCategoryMapper.insert(data);

        return data.getId();
    }

    @Override
    public void updateStateOwnedReformLawCategory(StateOwnedReformLawCategorySaveReqVO updateReqVO) {
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));

        StateOwnedReformLawCategoryDO old = stateOwnedReformLawCategoryMapper.selectById(updateReqVO.getId());
        if (old== null) {
            throw exception(STATE_OWNED_REFORM_LAW_CATEGORY_NOT_EXISTS);
        }

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

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

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


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

    @Override
    public void deleteStateOwnedReformLawCategory(Long id) {

        StateOwnedReformLawCategoryDO old = stateOwnedReformLawCategoryMapper.selectById(id);
        if (old == null) {
            throw exception(STATE_OWNED_REFORM_LAW_CATEGORY_NOT_EXISTS);
        }

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

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

        stateOwnedReformLawCategoryMapper.deleteById(id);
    }

    @Override
        public void deleteStateOwnedReformLawCategoryListByIds(List<Long> ids) {
        // 校验存在
        validateStateOwnedReformLawCategoryExists(ids);
        // 删除
        stateOwnedReformLawCategoryMapper.deleteByIds(ids);
        }

    private void validateStateOwnedReformLawCategoryExists(List<Long> ids) {
        List<StateOwnedReformLawCategoryDO> list = stateOwnedReformLawCategoryMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(STATE_OWNED_REFORM_LAW_CATEGORY_NOT_EXISTS);
        }
    }

    private void validateStateOwnedReformLawCategoryExists(Long id) {
        if (stateOwnedReformLawCategoryMapper.selectById(id) == null) {
            throw exception(STATE_OWNED_REFORM_LAW_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public StateOwnedReformLawCategoryDO getStateOwnedReformLawCategory(Long id) {
        return stateOwnedReformLawCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<StateOwnedReformLawCategoryDO> getStateOwnedReformLawCategoryPage(StateOwnedReformLawCategoryPageReqVO pageReqVO) {
        return stateOwnedReformLawCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<StateOwnedReformLawCategoryDO> getStateOwnedReformLawCategoryTree(ResearchTopicCategoryPageReqVO pageReqVO) {

        List<StateOwnedReformLawCategoryDO> categoryDOS = stateOwnedReformLawCategoryMapper.selectList(new LambdaQueryWrapperX<StateOwnedReformLawCategoryDO>()
//                .eq(ResearchTopicCategoryDO::getStatus, "正常")
                        .likeIfPresent(StateOwnedReformLawCategoryDO::getCategoryName, pageReqVO.getCategoryName())
                        .orderByAsc(StateOwnedReformLawCategoryDO::getOrder1)
                        .orderByAsc(StateOwnedReformLawCategoryDO::getOrder2)
        );
        return buildTree(categoryDOS);
    }

    @Override
    public void voidStateOwnedReformLawCategory(Long id, String status) {
        StateOwnedReformLawCategoryDO infoDO = stateOwnedReformLawCategoryMapper.selectById(id);
        if (infoDO == null) {
            throw exception(STATE_OWNED_REFORM_LAW_CATEGORY_NOT_EXISTS);
        }
        infoDO.setStatus(status);
        stateOwnedReformLawCategoryMapper.updateById(infoDO);
    }

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

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

        // 2. 组装父子关系
        List<StateOwnedReformLawCategoryDO> rootList = new ArrayList<>();
        for (StateOwnedReformLawCategoryDO 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<StateOwnedReformLawCategoryDO> comparator = Comparator
                .comparing(StateOwnedReformLawCategoryDO::getOrder1, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(StateOwnedReformLawCategoryDO::getOrder2, Comparator.nullsLast(Integer::compareTo));

        sortRecursively(rootList, comparator);

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