package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.StoreDictionary;
import shop.alien.entity.store.StoreMenu;
import shop.alien.entity.store.vo.StoreDictionaryVo;
import shop.alien.entity.store.vo.SystemConfigVo;
import shop.alien.mapper.StoreDictionaryMapper;
import shop.alien.store.service.StoreDictService;
import shop.alien.store.util.CommonConstant;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典ServiceImpl
 *
 * @author ssk
 * @version 1.0
 * @date 2025/2/8 10:24
 */
@Service
@RequiredArgsConstructor
public class StoreDictServiceImpl extends ServiceImpl<StoreDictionaryMapper, StoreDictionary> implements StoreDictService {

    private final StoreDictionaryMapper storeDictionaryMapper;

    /**
     * 查询字典值
     *
     * @param dictType 字典类型
     * @return list
     */
    @Override
    public List<StoreDictionary> getDict(String dictType) {
        LambdaQueryWrapper<StoreDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreDictionary::getTypeName, dictType);
        queryWrapper.eq(StoreDictionary::getDeleteFlag, 0);
        return this.list(queryWrapper);
    }

    /**
     * 新增字典
     *
     * @param storeDictionary 字典类
     * @return boolean
     */
    @Override
    public boolean addDict(StoreDictionary storeDictionary) {
        Integer num = storeDictionaryMapper.getMaxDictIdByTypeName(storeDictionary.getTypeName());
        storeDictionary.setDictId(null == num ? "1" :String.valueOf(num + 1));
        storeDictionary.setCreatedTime(new Date());
        return this.save(storeDictionary);
    }

    /**
     * 删除字典
     *
     * @param id 主键
     * @return boolean
     */
    @Override
    public boolean deleteDict(Integer id) {
        return this.removeById(id);
    }

    /**
     * 根据typeName查询字典
     *
     * @return Map
     */
    @Override
    public Map<String, List<StoreDictionary>> getDictList() {

        // typeNameList为空，则使用默认的typeName列表
        String typeName = CommonConstant.STORE_DICT_TYPENAME;
        List<String> typeNameList = Arrays.stream(typeName.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());

        // 查询字典列表
        List<StoreDictionary> storeDictionaryList =  storeDictionaryMapper.selectList(
                new LambdaQueryWrapper<StoreDictionary>().in(StoreDictionary::getTypeName, typeNameList).eq(StoreDictionary::getDeleteFlag,0));

        // 对字典列表构造父子结构
        List<StoreDictionary> storeDictionaries = buildTreeOptimized(storeDictionaryList);

        // 根据typeName进行分组
        return storeDictionaries.stream()
                .collect(Collectors.groupingBy(StoreDictionary::getTypeName));
    }

    @Override
    public SystemConfigVo getConfig(String dictType) {
        SystemConfigVo systemConfigVo = new SystemConfigVo();
        systemConfigVo.setDictType(dictType);
        LambdaQueryWrapper<StoreDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreDictionary::getTypeName, dictType);
        queryWrapper.eq(StoreDictionary::getDeleteFlag, 0);
        List<StoreDictionary> storeDictionaryList = this.list(queryWrapper);
        if(!CollectionUtils.isEmpty(storeDictionaryList)){
            StoreDictionary storeDictionary = storeDictionaryList.get(0);
            systemConfigVo.setConfigValue1(storeDictionary.getDictId());
            systemConfigVo.setConfigValue2(storeDictionary.getDictDetail());
        }
        return systemConfigVo;
    }

    @Override
    public void editConfig(SystemConfigVo systemConfigVo) {
        if(systemConfigVo != null && StringUtils.isNotBlank(systemConfigVo.getDictType())){
            LambdaQueryWrapper<StoreDictionary> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StoreDictionary::getTypeName, systemConfigVo.getDictType());
            queryWrapper.eq(StoreDictionary::getDeleteFlag, 0);
            List<StoreDictionary> storeDictionaryList = this.list(queryWrapper);
            if(!CollectionUtils.isEmpty(storeDictionaryList)){
                StoreDictionary storeDictionary = storeDictionaryList.get(0);
                storeDictionary.setDictId(systemConfigVo.getConfigValue1());
                storeDictionary.setDictDetail(systemConfigVo.getConfigValue2());
                storeDictionaryMapper.updateById(storeDictionary);
            }
        }
    }

    public List<StoreDictionary> buildTreeOptimized(List<StoreDictionary> flatList) {
        // 创建三个存储结构
        Map<Integer, StoreDictionary> nodeMap = new HashMap<>();  // ID到节点的映射
        Map<Integer, List<StoreDictionary>> parentChildMap = new HashMap<>();  // 父ID到子节点列表的映射
        List<StoreDictionary> result = new ArrayList<>();  // 结果列表

        // 填充nodeMap和parentChildMap
        for (StoreDictionary entity : flatList) {
            Integer id = entity.getId();
            Integer parentId = entity.getParentId();

            // 存入节点映射
            nodeMap.put(id, entity);

            // 初始化子节点列表
            entity.setStoreDictionaryList(new ArrayList<>());

            // 如果是根节点，直接添加到结果
            if (parentId == null || parentId==0 || !nodeMap.containsKey(parentId)) {
                result.add(entity);
            } else {
                // 否则，记录父子关系
                parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(entity);
            }
        }

        // 建立父子关系
        for (StoreDictionary entity : flatList) {
            Integer id = entity.getId();
            if (parentChildMap.containsKey(id)) {
                entity.getStoreDictionaryList().addAll(parentChildMap.get(id));
            }
        }
        return result;
    }
}
