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.BaseSeizeCategoryMapper;
import com.sundot.airport.system.domain.BaseSeizeCategory;
import com.sundot.airport.system.service.IBaseSeizeCategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 查获物品分类Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-08
 */
@Service
public class BaseSeizeCategoryServiceImpl implements IBaseSeizeCategoryService {
    @Autowired
    private LevelConfig levelConfig;
    @Autowired
    private CodeGeneratorUtil codeGeneratorUtil;
    @Autowired
    private BaseSeizeCategoryMapper baseSeizeCategoryMapper;

    /**
     * 查询查获物品分类
     *
     * @param id 查获物品分类主键
     * @return 查获物品分类
     */
    @Override
    public BaseSeizeCategory selectBaseSeizeCategoryById(Long id) {
        return baseSeizeCategoryMapper.selectBaseSeizeCategoryById(id);
    }

    /**
     * 查询查获物品分类列表
     *
     * @param baseSeizeCategory 查获物品分类
     * @return 查获物品分类
     */
    @Override
    public List<BaseSeizeCategory> selectBaseSeizeCategoryList(BaseSeizeCategory baseSeizeCategory) {
        return baseSeizeCategoryMapper.selectBaseSeizeCategoryList(baseSeizeCategory);
    }

    /**
     * 新增查获物品分类
     *
     * @param baseSeizeCategory 查获物品分类
     * @return 结果
     */
    @Override
    public int insertBaseSeizeCategory(BaseSeizeCategory baseSeizeCategory) {
        if (ObjectUtil.isEmpty(baseSeizeCategory.getParentId()) || baseSeizeCategory.getParentId().equals(0L)) {
            baseSeizeCategory.setAncestors("0");
            baseSeizeCategory.setLevel(1);
        } else {
            BaseSeizeCategory info = baseSeizeCategoryMapper.selectBaseSeizeCategoryById(baseSeizeCategory.getParentId());
            if (ObjectUtil.isEmpty(info)) {
                throw new ServiceException("父分类不存在，不允许新增");
            }
            baseSeizeCategory.setAncestors(info.getAncestors() + "," + baseSeizeCategory.getParentId());
            baseSeizeCategory.setLevel(baseSeizeCategory.getAncestors().split(",").length);
        }
        verifyData(baseSeizeCategory);
        baseSeizeCategory.setCode(codeGeneratorUtil.getNextCodeGenerator());
        baseSeizeCategory.setCreateTime(DateUtils.getNowDate());
        return baseSeizeCategoryMapper.insertBaseSeizeCategory(baseSeizeCategory);
    }

    /**
     * 修改查获物品分类
     *
     * @param baseSeizeCategory 查获物品分类
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBaseSeizeCategory(BaseSeizeCategory baseSeizeCategory) {
        baseSeizeCategory.setUpdateTime(DateUtils.getNowDate());
        BaseSeizeCategory newParent = baseSeizeCategoryMapper.selectBaseSeizeCategoryById(baseSeizeCategory.getParentId());
        BaseSeizeCategory old = baseSeizeCategoryMapper.selectBaseSeizeCategoryById(baseSeizeCategory.getId());
        if (ObjectUtils.isNotEmpty(newParent) && ObjectUtils.isNotEmpty(old)) {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = old.getAncestors();
            baseSeizeCategory.setAncestors(newAncestors);
            baseSeizeCategory.setLevel(baseSeizeCategory.getAncestors().split(",").length);
            updateChildren(baseSeizeCategory.getId(), newAncestors, oldAncestors);
        }
        verifyData(baseSeizeCategory);
        int result = baseSeizeCategoryMapper.updateBaseSeizeCategory(baseSeizeCategory);
        return result;
    }

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

    /**
     * 批量删除查获物品分类
     *
     * @param ids 需要删除的查获物品分类主键
     * @return 结果
     */
    @Override
    public int deleteBaseSeizeCategoryByIds(Long[] ids) {
        return baseSeizeCategoryMapper.deleteBaseSeizeCategoryByIds(ids);
    }

    /**
     * 删除查获物品分类信息
     *
     * @param id 查获物品分类主键
     * @return 结果
     */
    @Override
    public int deleteBaseSeizeCategoryById(Long id) {
        return baseSeizeCategoryMapper.deleteBaseSeizeCategoryById(id);
    }

    /**
     * 查询查获物品分类树形结构
     *
     * @param baseSeizeCategory 查获物品分类
     * @return 树结构列表
     */
    @Override
    public List<BaseSeizeCategory> selectBaseSeizeCategoryListTree(BaseSeizeCategory baseSeizeCategory) {
        List<BaseSeizeCategory> list = selectBaseSeizeCategoryList(baseSeizeCategory);
        return buildTree(list);
    }

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

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

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

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

        return result;
    }

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

}
