package com.ssyf.module.robot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyf.module.robot.domain.entity.RRunningConfigGlobal;
import com.ssyf.module.robot.domain.query.RRunningConfigGlobalQuery;
import com.ssyf.module.robot.service.RRunningConfigGlobalService;
import com.ssyf.module.robot.mapper.RRunningConfigGlobalMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author ELSA
 * @description 针对表【r_running_config_global(运行全局配置表)】的数据库操作Service实现
 * @createDate 2026-01-08 16:49:25
 */
@Service
public class RRunningConfigGlobalServiceImpl extends ServiceImpl<RRunningConfigGlobalMapper, RRunningConfigGlobal>
        implements RRunningConfigGlobalService{

    private static final String GLOBAL_CONFIG_CACHE_KEY = "robot:global:config";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void updateBy(RRunningConfigGlobalQuery query) {
        RRunningConfigGlobal entity = BeanUtil.toBean(query , RRunningConfigGlobal.class);
        entity.setUuid(null).setId(null).setCreateTime(null).setUpdateTime(LocalDateTime.now());

        this.update( entity ,new LambdaQueryWrapper<>());

        // 更新后清除缓存
        redisTemplate.delete(GLOBAL_CONFIG_CACHE_KEY);
    }

    @Override
    public RRunningConfigGlobal getOneBy() {
        // 尝试从缓存获取
        RRunningConfigGlobal cachedConfig = (RRunningConfigGlobal) redisTemplate.opsForValue().get(GLOBAL_CONFIG_CACHE_KEY);
        if (cachedConfig != null) {
            return cachedConfig;
        }

        // 缓存未命中，从数据库获取
        RRunningConfigGlobal config = this.getOne(new LambdaQueryWrapper<RRunningConfigGlobal>().last("LIMIT 1"));

        // 将结果放入缓存
        if (config != null) {
            redisTemplate.opsForValue().set(GLOBAL_CONFIG_CACHE_KEY, config);
        }

        return config;
    }
}
