/*
 * 文 件 名:  EmsCommonCacheImpl
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/2/13
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.ruoyi.ems.service;

import com.ruoyi.ems.core.BaseCache;
import com.ruoyi.ems.domain.FacsCategory;
import com.ruoyi.ems.domain.FacsSubCategory;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 公共缓存实现类
 * <功能详细描述>
 *
 * @author lvwenbin
 * @version [版本号, 2025/2/13]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service("emsCommonCache")
public class EmsCommonCache implements BaseCache, ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(EmsCommonCache.class);

    @Autowired
    private IFacsCategoryService facsCategoryService;

    @Autowired
    private IFacsSubCategoryService facsSubCategoryService;

    /**
     * 分类缓存
     */
    private Map<String, FacsCategory> facsCategoryCache = new ConcurrentHashMap<>();

    /**
     * 子分类缓存
     */
    private Map<String, FacsSubCategory> facsSubCategoryCache = new ConcurrentHashMap<>();

    @Override
    public FacsCategory getCategory(String code) {
        return facsCategoryCache.get(code);
    }

    /**
     * 根据编码获取子分类信息
     *
     * @param code 编码
     * @return 子分类信息
     */
    @Override
    public FacsSubCategory getSubCategory(String code) {
        return facsSubCategoryCache.get(code);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        loadFacsCategory();
        loadFacsSubCategory();
    }

    private void loadFacsCategory() {
        List<FacsCategory> dbList = facsCategoryService.selectCategoryList();

        if (CollectionUtils.isNotEmpty(dbList)) {
            Map<String, FacsCategory> dbMap = dbList.stream()
                .collect(Collectors.toMap(FacsCategory::getCode, Function.identity()));
            facsCategoryCache.putAll(dbMap);
        }

        log.info("加载设施分类缓存完成，共{}条数据", dbList.size());
    }

    private void loadFacsSubCategory() {
        List<FacsSubCategory> dbList = facsSubCategoryService.selectSubCategoryList();

        if (CollectionUtils.isNotEmpty(dbList)) {
            Map<String, FacsSubCategory> dbMap = dbList.stream()
                .collect(Collectors.toMap(FacsSubCategory::getCode, Function.identity()));
            facsSubCategoryCache.putAll(dbMap);
        }

        log.info("加载设施子分类缓存完成，共{}条数据", dbList.size());
    }
}