package com.sundot.airport.system.service.impl;

import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.sundot.airport.common.config.LevelConfig;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.system.utils.CodeGeneratorUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.system.mapper.BaseCheckCategoryMapper;
import com.sundot.airport.system.domain.BaseCheckCategory;
import com.sundot.airport.system.service.IBaseCheckCategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 检查项分类Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-11
 */
@Service
public class BaseCheckCategoryServiceImpl implements IBaseCheckCategoryService {
    @Autowired
    private LevelConfig levelConfig;
    @Autowired
    private CodeGeneratorUtil codeGeneratorUtil;
    @Autowired
    private BaseCheckCategoryMapper baseCheckCategoryMapper;

    /**
     * 查询检查项分类
     *
     * @param id 检查项分类主键
     * @return 检查项分类
     */
    @Override
    public BaseCheckCategory selectBaseCheckCategoryById(Long id) {
        return baseCheckCategoryMapper.selectBaseCheckCategoryById(id);
    }

    /**
     * 查询检查项分类列表
     *
     * @param baseCheckCategory 检查项分类
     * @return 检查项分类
     */
    @Override
    public List<BaseCheckCategory> selectBaseCheckCategoryList(BaseCheckCategory baseCheckCategory) {
        return baseCheckCategoryMapper.selectBaseCheckCategoryList(baseCheckCategory);
    }

    /**
     * 新增检查项分类
     *
     * @param baseCheckCategory 检查项分类
     * @return 结果
     */
    @Override
    public int insertBaseCheckCategory(BaseCheckCategory baseCheckCategory) {
        if (ObjectUtil.isEmpty(baseCheckCategory.getParentId()) || baseCheckCategory.getParentId().equals(0L)) {
            baseCheckCategory.setAncestors("0");
            baseCheckCategory.setLevel(1);
        } else {
            BaseCheckCategory info = baseCheckCategoryMapper.selectBaseCheckCategoryById(baseCheckCategory.getParentId());
            if (ObjectUtil.isEmpty(info)) {
                throw new ServiceException("父分类不存在，不允许新增");
            }
            baseCheckCategory.setAncestors(info.getAncestors() + "," + baseCheckCategory.getParentId());
            baseCheckCategory.setLevel(baseCheckCategory.getAncestors().split(",").length);
        }
        verifyData(baseCheckCategory);
        baseCheckCategory.setCode(codeGeneratorUtil.getNextCodeGenerator());
        baseCheckCategory.setCreateTime(DateUtils.getNowDate());
        return baseCheckCategoryMapper.insertBaseCheckCategory(baseCheckCategory);
    }

    /**
     * 修改检查项分类
     *
     * @param baseCheckCategory 检查项分类
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBaseCheckCategory(BaseCheckCategory baseCheckCategory) {
        baseCheckCategory.setUpdateTime(DateUtils.getNowDate());
        BaseCheckCategory newParent = baseCheckCategoryMapper.selectBaseCheckCategoryById(baseCheckCategory.getParentId());
        BaseCheckCategory old = baseCheckCategoryMapper.selectBaseCheckCategoryById(baseCheckCategory.getId());
        if (ObjectUtils.isNotEmpty(newParent) && ObjectUtils.isNotEmpty(old)) {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = old.getAncestors();
            baseCheckCategory.setAncestors(newAncestors);
            baseCheckCategory.setLevel(baseCheckCategory.getAncestors().split(",").length);
            updateChildren(baseCheckCategory.getId(), newAncestors, oldAncestors);
        }
        verifyData(baseCheckCategory);
        int result = baseCheckCategoryMapper.updateBaseCheckCategory(baseCheckCategory);
        return result;
    }

    /**
     * 修改子元素关系
     *
     * @param id           被修改的元素ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateChildren(Long id, String newAncestors, String oldAncestors) {
        List<BaseCheckCategory> children = baseCheckCategoryMapper.selectChildrenById(id);
        for (BaseCheckCategory child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            child.setLevel(child.getAncestors().split(",").length);
            verifyData(child);
        }
        if (!CollectionUtils.isEmpty(children)) {
            baseCheckCategoryMapper.updateChildren(children);
        }
    }

    /**
     * 批量删除检查项分类
     *
     * @param ids 需要删除的检查项分类主键
     * @return 结果
     */
    @Override
    public int deleteBaseCheckCategoryByIds(Long[] ids) {
        return baseCheckCategoryMapper.deleteBaseCheckCategoryByIds(ids);
    }

    /**
     * 删除检查项分类信息
     *
     * @param id 检查项分类主键
     * @return 结果
     */
    @Override
    public int deleteBaseCheckCategoryById(Long id) {
        return baseCheckCategoryMapper.deleteBaseCheckCategoryById(id);
    }

    /**
     * 查询检查项分类列表树形结构
     *
     * @param baseCheckCategory 检查项分类
     * @return 检查项分类集合
     */
    @Override
    public List<BaseCheckCategory> selectBaseCheckCategoryListTree(BaseCheckCategory baseCheckCategory) {
        List<BaseCheckCategory> list = selectBaseCheckCategoryList(baseCheckCategory);
        return buildTree(list);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param list 列表
     * @return 树结构列表
     */
    @Override
    public List<BaseCheckCategory> buildTree(List<BaseCheckCategory> list) {
        // 结果列表
        List<BaseCheckCategory> result = new ArrayList<>();

        // 临时Map，用于快速查找节点
        Map<Long, BaseCheckCategory> nodeMap = new HashMap<>();

        // 第一次遍历：将所有节点存入Map
        for (BaseCheckCategory node : list) {
            nodeMap.put(node.getId(), node);
        }

        // 第二次遍历：建立父子关系
        for (BaseCheckCategory node : list) {
            Long parentId = node.getParentId();
            if (parentId == null || parentId == 0L) {
                // 父ID为null或0，说明是根节点
                result.add(node);
            } else {
                // 查找父节点
                BaseCheckCategory parent = nodeMap.get(parentId);
                if (parent != null) {
                    // 初始化子节点列表
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    // 将当前节点添加到父节点的子列表中
                    List<BaseCheckCategory> children = (List<BaseCheckCategory>) parent.getChildren();
                    children.add(node);
                }
            }
        }

        return result;
    }

    /**
     * 验证数据
     */
    private void verifyData(BaseCheckCategory baseCheckCategory) {
        if (baseCheckCategory.getLevel() > levelConfig.getCheckCategoryLevel()) {
            throw new ServiceException("操作失败,层级超过限制" + levelConfig.getCheckCategoryLevel() + "级");
        }
    }

    /**
     * 根据二级分类名称查询对应的一级分类
     *
     * @param level2Name 二级分类名称（来自edu_cs_ques_cat.qc_name）
     * @return 一级分类，如果未找到则返回null
     */
    @Override
    public BaseCheckCategory selectLevel1ByLevel2Name(String level2Name) {
        if (level2Name == null || level2Name.trim().isEmpty()) {
            return null;
        }
        return baseCheckCategoryMapper.selectLevel1ByLevel2Name(level2Name);
    }

}
