package com.mcwl.system.init;

import com.mcwl.common.core.domain.entity.SysDictData;
import com.mcwl.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DaiZibo
 * @date 2025/1/14
 * @apiNote
 */


@Slf4j
@Component
public class DictInit implements ApplicationRunner {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    private static final Map<String, Map<String, SysDictData>> dictCache = new HashMap<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.dict();
    }

    //初始化防擦
    public void dict(){

        long startTime = System.currentTimeMillis(); // 记录开始时间
        log.info("初始化字典数据...");

        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");

        // 查询所有字典数据    查询所有状态为启用的正常的，sql太简单就不写了
        List<SysDictData> allDicts = sysDictDataMapper.selectDictDataList(dictData);

        // 根据 dictType 分组
        Map<String, List<SysDictData>> groupedByType = allDicts.stream()
                .collect(Collectors.groupingBy(SysDictData::getDictType));

        // 组织最终的 Map 结构
        groupedByType.forEach((type, items) -> {
            Map<String, SysDictData> subMap = items.stream()
                    .collect(Collectors.toMap(
                            SysDictData::getDictValue,
                            item -> item// 这里使用整个 SysDictData 对象作为值
                    ));
            dictCache.put(type, subMap);
        });
        long cost = System.currentTimeMillis() - startTime; // 计算耗时
        log.info("字典数据初始化完成，耗时 {} 毫秒", cost); // 打印耗时
    }

    /**
     * 获取字典值
     *
     * @param type
     * @param value
     * @return
     */
    public static String getDictValue(String type, String value) {
        Map<String, SysDictData> stringSysDictDataMap = dictCache.get(type);
        if (stringSysDictDataMap != null) {

            SysDictData sysDictData = stringSysDictDataMap.get(value);

            if (sysDictData != null) {
                return sysDictData.getDictLabel();
            }
        }

        return "";
    }
}
