package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.StoreDictionary;
import shop.alien.entity.store.vo.StoreDictionaryVo;
import shop.alien.mapper.StoreDictionaryMapper;
import shop.alien.storeplatform.service.BusinessSectionService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 经营板块服务实现类
 * 提供经营板块的三级分类查询服务实现
 *
 * @author alien-cloud
 * @date 2025-12-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessSectionServiceImpl implements BusinessSectionService {

    private final StoreDictionaryMapper storeDictionaryMapper;

    /**
     * 类型名称常量：经营板块
     */
    private static final String TYPE_NAME = "business_section";
    /**
     * 类型名称常量：二级
     */
    private static final String BUSINESS_TYPE = "business_type";
    /**
     * 类型名称常量：三级 分类
     */
    private static final String BUSINESS_CLASSIFY = "business_classify";

    /**
     * 一级分类的根节点 dict_id（经营板块根节点）
     */
    private static final String ROOT_DICT_ID = "0";

    /**
     * 查询经营板块一级分类列表
     *
     * @return 一级分类列表
     */
    @Override
    public List<StoreDictionaryVo> getFirstLevelList() {
        log.info("BusinessSectionServiceImpl.getFirstLevelList - 开始查询一级分类");

//        // 1. 查询根节点（dict_id = 0）
//        StoreDictionary root = storeDictionaryMapper.selectOne(
//                new LambdaQueryWrapper<StoreDictionary>()
//                        .eq(StoreDictionary::getTypeName, TYPE_NAME)
//                        .isNull(StoreDictionary::getParentId)
//                        .eq(StoreDictionary::getDeleteFlag, 0)
//        );
//
//        if (root == null) {
//            log.warn("BusinessSectionServiceImpl.getFirstLevelList - 未找到经营板块根节点");
//            return new ArrayList<>();
//        }

        // 2. 查询一级分类（parent_id = 根节点的id，且 dict_id != 0）
        List<StoreDictionary> firstLevelList = storeDictionaryMapper.selectList(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, TYPE_NAME)
                        .isNull(StoreDictionary::getParentId)
                        .eq(StoreDictionary::getDeleteFlag, 0)
                        .orderByAsc(StoreDictionary::getDictId)
        );

        // 3. 转换为 VO
        List<StoreDictionaryVo> voList = convertToVoList(firstLevelList);

        log.info("BusinessSectionServiceImpl.getFirstLevelList - 查询成功，共 {} 条数据", voList.size());
        return voList;
    }

    /**
     * 查询经营板块二级分类列表
     *
     * @param parentDictId 一级分类的字典ID（dict_id）
     * @return 二级分类列表
     */
    @Override
    public List<StoreDictionaryVo> getSecondLevelList(String parentDictId) {
        log.info("BusinessSectionServiceImpl.getSecondLevelList - 开始查询二级分类，parentDictId={}", parentDictId);

        // 1. 根据 dict_id 查询父节点
//        StoreDictionary parent = storeDictionaryMapper.selectOne(
//                new LambdaQueryWrapper<StoreDictionary>()
//                        .eq(StoreDictionary::getTypeName, BUSINESS_TYPE)
//                        .eq(StoreDictionary::getId, parentDictId)
//                        .eq(StoreDictionary::getDeleteFlag, 0)
//        );
//
//        if (parent == null) {
//            log.warn("BusinessSectionServiceImpl.getSecondLevelList - 未找到父节点，parentDictId={}", parentDictId);
//            return new ArrayList<>();
//        }

        // 获取一级分类id
        Integer id = storeDictionaryMapper.selectOne(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, TYPE_NAME)
                        .eq(StoreDictionary::getDictId, parentDictId)
                        .eq(StoreDictionary::getDeleteFlag, 0)
        ).getId();

        // 2. 查询二级分类（parent_id = 父节点的id）
        List<StoreDictionary> secondLevelList = storeDictionaryMapper.selectList(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, BUSINESS_TYPE)
                        .eq(StoreDictionary::getParentId, id)
                        .eq(StoreDictionary::getDeleteFlag, 0)
                        .orderByAsc(StoreDictionary::getDictId)
        );

        // 3. 转换为 VO
        List<StoreDictionaryVo> voList = convertToVoList(secondLevelList);

        log.info("BusinessSectionServiceImpl.getSecondLevelList - 查询成功，共 {} 条数据", voList.size());
        return voList;
    }

    /**
     * 查询经营板块三级分类列表
     *
     * @param parentDictId 二级分类的字典ID（dict_id）
     * @return 三级分类列表
     */
    @Override
    public List<StoreDictionaryVo> getThirdLevelList(String parentDictId) {
        log.info("BusinessSectionServiceImpl.getThirdLevelList - 开始查询三级分类，parentDictId={}", parentDictId);

//        // 1. 根据 dict_id 查询父节点
//        StoreDictionary parent = storeDictionaryMapper.selectOne(
//                new LambdaQueryWrapper<StoreDictionary>()
//                        .eq(StoreDictionary::getTypeName, BUSINESS_CLASSIFY)
//                        .eq(StoreDictionary::getId, parentDictId)
//                        .eq(StoreDictionary::getDeleteFlag, 0)
//        );
//
//        if (parent == null) {
//            log.warn("BusinessSectionServiceImpl.getThirdLevelList - 未找到父节点，parentDictId={}", parentDictId);
//            return new ArrayList<>();
//        }

        // 获取二级分类id
        Integer businessTypeId = storeDictionaryMapper.selectOne(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, BUSINESS_TYPE)
                        .eq(StoreDictionary::getDictId, parentDictId)
                        .eq(StoreDictionary::getDeleteFlag, 0)
        ).getId();

        // 2. 查询三级分类（parent_id = 父节点的id）
        List<StoreDictionary> thirdLevelList = storeDictionaryMapper.selectList(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, BUSINESS_CLASSIFY)
                        .eq(StoreDictionary::getParentId, businessTypeId)
                        .eq(StoreDictionary::getDeleteFlag, 0)
                        .orderByAsc(StoreDictionary::getDictId)
        );

        // 3. 转换为 VO
        List<StoreDictionaryVo> voList = convertToVoList(thirdLevelList);

        log.info("BusinessSectionServiceImpl.getThirdLevelList - 查询成功，共 {} 条数据", voList.size());
        return voList;
    }

    /**
     * 查询经营板块树形结构（三级联动）
     *
     * @return 树形结构数据（包含一级、二级、三级）
     */
    @Override
    public List<StoreDictionaryVo> getTreeStructure() {
        log.info("BusinessSectionServiceImpl.getTreeStructure - 开始查询三级树形结构");

        // 1. 查询所有经营板块数据（排除根节点）
        List<StoreDictionary> allList = storeDictionaryMapper.selectList(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, TYPE_NAME)
                        .eq(StoreDictionary::getDeleteFlag, 0)
                        .orderByAsc(StoreDictionary::getParentId)
                        .orderByAsc(StoreDictionary::getDictId)
        );

        if (allList == null || allList.isEmpty()) {
            log.warn("BusinessSectionServiceImpl.getTreeStructure - 未查询到任何数据");
            return new ArrayList<>();
        }

        // 2. 转换为 VO 列表
        List<StoreDictionaryVo> allVoList = convertToVoList(allList);

        // 3. 构建树形结构
        List<StoreDictionaryVo> treeList = buildTree(allVoList, allList);

        log.info("BusinessSectionServiceImpl.getTreeStructure - 查询成功，共 {} 个一级分类", treeList.size());
        return treeList;
    }

    /**
     * 根据字典ID查询完整路径
     *
     * @param dictId 字典ID
     * @return 分类路径（从一级到当前级）
     */
    @Override
    public List<StoreDictionaryVo> getFullPath(String dictId) {
        log.info("BusinessSectionServiceImpl.getFullPath - 开始查询完整路径，dictId={}", dictId);

        List<StoreDictionaryVo> pathList = new ArrayList<>();

        // 1. 查询当前节点
        StoreDictionary current = storeDictionaryMapper.selectOne(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, TYPE_NAME)
                        .eq(StoreDictionary::getId, dictId)
                        .eq(StoreDictionary::getDeleteFlag, 0)
        );

        if (current == null) {
            log.warn("BusinessSectionServiceImpl.getFullPath - 未找到节点，dictId={}", dictId);
            return pathList;
        }

        // 2. 递归查询父节点，构建路径
        buildPath(current, pathList);

        // 3. 反转列表（从一级到当前级）
        List<StoreDictionaryVo> result = new ArrayList<>();
        for (int i = pathList.size() - 1; i >= 0; i--) {
            result.add(pathList.get(i));
        }

        log.info("BusinessSectionServiceImpl.getFullPath - 查询成功，路径长度={}", result.size());
        return result;
    }

    /**
     * 构建树形结构
     *
     * @param allVoList 所有VO列表
     * @param allList   所有实体列表
     * @return 树形结构
     */
    private List<StoreDictionaryVo> buildTree(List<StoreDictionaryVo> allVoList, 
                                               List<StoreDictionary> allList) {
        // 1. 找出一级分类（查询根节点的id）
        StoreDictionary root = storeDictionaryMapper.selectOne(
                new LambdaQueryWrapper<StoreDictionary>()
                        .eq(StoreDictionary::getTypeName, TYPE_NAME)
                        .eq(StoreDictionary::getDictId, ROOT_DICT_ID)
                        .eq(StoreDictionary::getDeleteFlag, 0)
        );

        if (root == null) {
            return new ArrayList<>();
        }

        Integer rootId = root.getId();

        // 2. 找出一级分类
        List<StoreDictionaryVo> firstLevelList = allVoList.stream()
                .filter(vo -> {
                    StoreDictionary entity = allList.stream()
                            .filter(e -> e.getId().equals(vo.getId()))
                            .findFirst()
                            .orElse(null);
                    return entity != null && rootId.equals(entity.getParentId());
                })
                .collect(Collectors.toList());

        // 3. 为每个一级分类填充子节点
        for (StoreDictionaryVo firstLevel : firstLevelList) {
            // 查询二级分类
            List<StoreDictionaryVo> secondLevelList = allVoList.stream()
                    .filter(vo -> {
                        StoreDictionary entity = allList.stream()
                                .filter(e -> e.getId().equals(vo.getId()))
                                .findFirst()
                                .orElse(null);
                        return entity != null && firstLevel.getId().equals(entity.getParentId());
                    })
                    .collect(Collectors.toList());

            // 为每个二级分类填充三级分类
            for (StoreDictionaryVo secondLevel : secondLevelList) {
                List<StoreDictionaryVo> thirdLevelList = allVoList.stream()
                        .filter(vo -> {
                            StoreDictionary entity = allList.stream()
                                    .filter(e -> e.getId().equals(vo.getId()))
                                    .findFirst()
                                    .orElse(null);
                            return entity != null && secondLevel.getId().equals(entity.getParentId());
                        })
                        .collect(Collectors.toList());

                secondLevel.setSubDataList(thirdLevelList.isEmpty() ? null : thirdLevelList);
            }

            firstLevel.setSubDataList(secondLevelList.isEmpty() ? null : secondLevelList);
        }

        return firstLevelList;
    }

    /**
     * 递归构建路径
     *
     * @param current  当前节点
     * @param pathList 路径列表
     */
    private void buildPath(StoreDictionary current, List<StoreDictionaryVo> pathList) {
        if (current == null) {
            return;
        }

        // 跳过根节点
        if (ROOT_DICT_ID.equals(current.getDictId())) {
            return;
        }

        // 添加当前节点
        StoreDictionaryVo vo = new StoreDictionaryVo();
        BeanUtils.copyProperties(current, vo);
        pathList.add(vo);

        // 递归查询父节点
        if (current.getParentId() != null) {
            StoreDictionary parent = storeDictionaryMapper.selectById(current.getParentId());
            buildPath(parent, pathList);
        }
    }

    /**
     * 实体列表转 VO 列表
     *
     * @param entityList 实体列表
     * @return VO列表
     */
    private List<StoreDictionaryVo> convertToVoList(List<StoreDictionary> entityList) {
        if (entityList == null || entityList.isEmpty()) {
            return new ArrayList<>();
        }

        return entityList.stream().map(entity -> {
            StoreDictionaryVo vo = new StoreDictionaryVo();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList());
    }
}

