package org.dromara.system.service.impl.xiake;

import cn.hutool.core.convert.Convert;
import jakarta.annotation.PostConstruct;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.sms4j.api.universal.RedisUtil;
import org.dromara.system.domain.xiake.XiakeConfig;
import org.dromara.system.domain.xiake.bo.XiakeConfigBo;
import org.dromara.system.domain.xiake.vo.XiakeConfigVo;
import org.dromara.system.mapper.xiake.XiakeConfigMapper;
import org.dromara.system.service.xiake.IXiakeConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 下课时间配置Service业务层处理
 *
 * @author boman
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class XiakeConfigServiceImpl implements IXiakeConfigService {

    private final XiakeConfigMapper baseMapper;

/*
    */
/**
     * 项目启动时，初始化参数到缓存
     *//*

    @PostConstruct
    public void init()
    {
        loadingConfigCache();
    }
*/

    /**
     * 查询下课时间配置
     */
    @Override
    public XiakeConfigVo queryById(Long configId){
        return baseMapper.selectVoById(configId);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param bo 参数键名
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(XiakeConfigBo bo) {
        String configType = bo.getConfigType();
        String cacheKey = getCacheKey(bo.getConfigKey());
        cacheKey = cacheKey + ":"+configType;
        String configValue = Convert.toStr(RedisUtils.getCacheObject(cacheKey));
        if (StringUtils.isNotBlank(configValue))
        {
            return configValue;
        }
        bo.setConfigKey(bo.getConfigKey()+ ":"+configType);
        XiakeConfigVo retConfig = baseMapper.selectConfig(bo);
        if (retConfig != null)
        {
            RedisUtils.setCacheObject(getCacheKey(cacheKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     *
     * @param bo
     * @return
     */
    @Override
    public int updateConfigValue(XiakeConfigBo bo) {
        String key = bo.getConfigKey() + ":" + bo.getConfigType();

        XiakeConfigVo temp = baseMapper.checkConfigKeyUnique(key);
        if (!StringUtils.equals(temp.getConfigKey(), bo.getConfigKey()))
        {
            RedisUtils.deleteObject(getCacheKey(temp.getConfigKey()));
        }
        bo.setConfigKey(key);
        int row = baseMapper.updateConfigByKey(bo);
        if (row > 0)
        {
            RedisUtils.setCacheObject(getCacheKey(key), bo.getConfigValue());
        }
        return row;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return CacheConstants.XIA_CONFIG_KEY + configKey;
    }
    /**
     * 查询下课时间配置列表
     */
    @Override
    public TableDataInfo<XiakeConfigVo> queryPageList(XiakeConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<XiakeConfig> lqw = buildQueryWrapper(bo);
        Page<XiakeConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询下课时间配置列表
     */
    @Override
    public List<XiakeConfigVo> queryList(XiakeConfigBo bo) {
        LambdaQueryWrapper<XiakeConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<XiakeConfig> buildQueryWrapper(XiakeConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<XiakeConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getConfigName()), XiakeConfig::getConfigName, bo.getConfigName());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), XiakeConfig::getConfigKey, bo.getConfigKey());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigValue()), XiakeConfig::getConfigValue, bo.getConfigValue());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigType()), XiakeConfig::getConfigType, bo.getConfigType());
        return lqw;
    }

    /**
     * 新增下课时间配置
     */
    @Override
    public Boolean insertByBo(XiakeConfigBo bo) {
        XiakeConfig add = MapstructUtils.convert(bo, XiakeConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setConfigId(add.getConfigId());
        }
        return flag;
    }

    /**
     * 修改下课时间配置
     */
    @Override
    public Boolean updateByBo(XiakeConfigBo bo) {
        XiakeConfig update = MapstructUtils.convert(bo, XiakeConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(XiakeConfig entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除下课时间配置
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache()
    {
        List<XiakeConfig> configsList = baseMapper.selectList(buildQueryWrapper(new XiakeConfigBo()));
        for (XiakeConfig config : configsList)
        {
            RedisUtils.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache()
    {
        Collection<String> keys = RedisUtils.keys(CacheConstants.XIA_CONFIG_KEY + "*");
        RedisUtils.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache()
    {
        clearConfigCache();
        loadingConfigCache();
    }
}
