package com.CUST.brain.service.impl;

import com.CUST.brain.common.cache.ParamCacheManager;
import com.CUST.brain.dao.domain.system.SysParam;
import com.CUST.brain.dao.mapper.SysParamMapper;
import com.CUST.brain.service.SysParamService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysParamServiceImpl extends ServiceImpl<SysParamMapper, SysParam> implements SysParamService {

    @Resource
    private ParamCacheManager paramCacheManager;

    @Override
    public Map<String, String> getParamsByType(String typeId) {
        // 先从缓存获取
        Map<String, String> paramMap = paramCacheManager.getParamMap(typeId);
        if (paramMap == null) {
            // 缓存未命中，从数据库查询
            List<SysParam> params = listByType(typeId);
            paramMap = params.stream()
                    .collect(Collectors.toMap(
                            SysParam::getParamName,
                            SysParam::getParamValue,
                            (v1, v2) -> v1
                    ));
            // 更新缓存
            paramCacheManager.cacheParamList(typeId, params);
        }
        return paramMap;
    }

    @Override
    public String getParamValue(String typeId, String paramName) {
        Map<String, String> paramMap = getParamsByType(typeId);
        return paramMap.get(paramName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateParam(SysParam param) {
        boolean result = updateById(param);
        if (result) {
            // 删除缓存
            paramCacheManager.removeParamCache(param.getParamType());
        }
        return result;
    }

    @Override
    public List<SysParam> listByType(String typeCode) {
        // 先从缓存获取
        List<SysParam> params = paramCacheManager.getParamList(typeCode);
        if (params == null) {
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<SysParam> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysParam::getParamType, typeCode);
            params = list(wrapper);
            // 更新缓存
            paramCacheManager.cacheParamList(typeCode, params);
        }
        return params;
    }

    @Override
    public Map<String, List<SysParam>> getParamsByTypes(List<String> typeCodes) {
        if (typeCodes == null || typeCodes.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, List<SysParam>> result = new HashMap<>();
        for (String typeCode : typeCodes) {
            result.put(typeCode, listByType(typeCode));
        }
        return result;
    }
} 