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

/**
 * 检查部位Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-08
 */
@Service
public class BaseCheckPointServiceImpl implements IBaseCheckPointService {
    @Autowired
    private LevelConfig levelConfig;
    @Autowired
    private CodeGeneratorUtil codeGeneratorUtil;
    @Autowired
    private BaseCheckPointMapper baseCheckPointMapper;

    /**
     * 查询检查部位
     *
     * @param id 检查部位主键
     * @return 检查部位
     */
    @Override
    public BaseCheckPoint selectBaseCheckPointById(Long id) {
        return baseCheckPointMapper.selectBaseCheckPointById(id);
    }

    /**
     * 查询检查部位列表
     *
     * @param baseCheckPoint 检查部位
     * @return 检查部位
     */
    @Override
    public List<BaseCheckPoint> selectBaseCheckPointList(BaseCheckPoint baseCheckPoint) {
        return baseCheckPointMapper.selectBaseCheckPointList(baseCheckPoint);
    }

    /**
     * 新增检查部位
     *
     * @param baseCheckPoint 检查部位
     * @return 结果
     */
    @Override
    public int insertBaseCheckPoint(BaseCheckPoint baseCheckPoint) {
        if (ObjectUtil.isEmpty(baseCheckPoint.getParentId()) || baseCheckPoint.getParentId().equals(0L)) {
            baseCheckPoint.setAncestors("0");
            baseCheckPoint.setLevel(1);
        } else {
            BaseCheckPoint info = baseCheckPointMapper.selectBaseCheckPointById(baseCheckPoint.getParentId());
            if (ObjectUtil.isEmpty(info)) {
                throw new ServiceException("父部位不存在，不允许新增");
            }
            baseCheckPoint.setAncestors(info.getAncestors() + "," + baseCheckPoint.getParentId());
            baseCheckPoint.setLevel(baseCheckPoint.getAncestors().split(",").length);
        }
        verifyData(baseCheckPoint);
        baseCheckPoint.setCode(codeGeneratorUtil.getNextCodeGenerator());
        baseCheckPoint.setCreateTime(DateUtils.getNowDate());
        return baseCheckPointMapper.insertBaseCheckPoint(baseCheckPoint);
    }

    /**
     * 修改检查部位
     *
     * @param baseCheckPoint 检查部位
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBaseCheckPoint(BaseCheckPoint baseCheckPoint) {
        baseCheckPoint.setUpdateTime(DateUtils.getNowDate());
        BaseCheckPoint newParent = baseCheckPointMapper.selectBaseCheckPointById(baseCheckPoint.getParentId());
        BaseCheckPoint old = baseCheckPointMapper.selectBaseCheckPointById(baseCheckPoint.getId());
        if (ObjectUtils.isNotEmpty(newParent) && ObjectUtils.isNotEmpty(old)) {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = old.getAncestors();
            baseCheckPoint.setAncestors(newAncestors);
            baseCheckPoint.setLevel(baseCheckPoint.getAncestors().split(",").length);
            updateChildren(baseCheckPoint.getId(), newAncestors, oldAncestors);
        }
        verifyData(baseCheckPoint);
        int result = baseCheckPointMapper.updateBaseCheckPoint(baseCheckPoint);
        return result;
    }

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

    /**
     * 批量删除检查部位
     *
     * @param ids 需要删除的检查部位主键
     * @return 结果
     */
    @Override
    public int deleteBaseCheckPointByIds(Long[] ids) {
        return baseCheckPointMapper.deleteBaseCheckPointByIds(ids);
    }

    /**
     * 删除检查部位信息
     *
     * @param id 检查部位主键
     * @return 结果
     */
    @Override
    public int deleteBaseCheckPointById(Long id) {
        return baseCheckPointMapper.deleteBaseCheckPointById(id);
    }

    /**
     * 查询检查部位列表树形结构
     *
     * @param baseCheckPoint 检查部位
     * @return 树结构列表
     */
    @Override
    public List<BaseCheckPoint> selectBaseCheckPointListTree(BaseCheckPoint baseCheckPoint) {
        List<BaseCheckPoint> list = selectBaseCheckPointList(baseCheckPoint);
        return buildTree(list);
    }

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

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

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

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

        return result;
    }

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

}
