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.common.utils.StringUtils;
import com.sundot.airport.system.domain.vo.PositionInfoVO;
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.BasePositionMapper;
import com.sundot.airport.system.domain.BasePosition;
import com.sundot.airport.system.service.IBasePositionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 位置Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-09
 */
@Service
public class BasePositionServiceImpl implements IBasePositionService {
    @Autowired
    private LevelConfig levelConfig;
    @Autowired
    private CodeGeneratorUtil codeGeneratorUtil;
    @Autowired
    private BasePositionMapper basePositionMapper;

    /**
     * 查询位置
     *
     * @param id 位置主键
     * @return 位置
     */
    @Override
    public BasePosition selectBasePositionById(Long id) {
        return basePositionMapper.selectBasePositionById(id);
    }

    /**
     * 查询位置列表
     *
     * @param basePosition 位置
     * @return 位置
     */
    @Override
    public List<BasePosition> selectBasePositionList(BasePosition basePosition) {
        return basePositionMapper.selectBasePositionList(basePosition);
    }

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

    /**
     * 修改位置
     *
     * @param basePosition 位置
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBasePosition(BasePosition basePosition) {
        basePosition.setUpdateTime(DateUtils.getNowDate());
        BasePosition newParent = basePositionMapper.selectBasePositionById(basePosition.getParentId());
        BasePosition old = basePositionMapper.selectBasePositionById(basePosition.getId());
        if (ObjectUtils.isNotEmpty(newParent) && ObjectUtils.isNotEmpty(old)) {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = old.getAncestors();
            basePosition.setAncestors(newAncestors);
            basePosition.setLevel(basePosition.getAncestors().split(",").length);
            updateChildren(basePosition.getId(), newAncestors, oldAncestors);
        }
        verifyData(basePosition);
        int result = basePositionMapper.updateBasePosition(basePosition);
        return result;
    }

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

    /**
     * 批量删除位置
     *
     * @param ids 需要删除的位置主键
     * @return 结果
     */
    @Override
    public int deleteBasePositionByIds(Long[] ids) {
        return basePositionMapper.deleteBasePositionByIds(ids);
    }

    /**
     * 删除位置信息
     *
     * @param id 位置主键
     * @return 结果
     */
    @Override
    public int deleteBasePositionById(Long id) {
        return basePositionMapper.deleteBasePositionById(id);
    }

    /**
     * 查询位置列表树形结构
     *
     * @param basePosition 位置
     * @return 树结构列表
     */
    @Override
    public List<BasePosition> selectBasePositionListTree(BasePosition basePosition) {
        List<BasePosition> basePositionList = selectBasePositionList(basePosition);
        return buildTree(basePositionList);
    }

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

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

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

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

        return result;
    }

    @Override
    public List<PositionInfoVO> selectChannelsUnderArea(List<String> regionalCodes) {
        return basePositionMapper.selectChannelsUnderArea(regionalCodes);
    }

    /**
     * 验证数据
     */
    private void verifyData(BasePosition basePosition) {
        if (basePosition.getLevel() > levelConfig.getPositionLevel()) {
            throw new ServiceException("操作失败,层级超过限制" + levelConfig.getPositionLevel() + "级");
        }
        if (!StringUtils.equals(basePosition.getPositionType(), levelConfig.getPositionLevelMap().get(basePosition.getLevel()))) {
            throw new ServiceException("操作失败,层级与位置类型不匹配");
        }
    }

}
