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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssyf.common.security.domain.ClientInfo;
import com.ssyf.common.security.helper.ClientContextHelper;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.module.robot.domain.entity.RRunningConfig;
import com.ssyf.module.robot.domain.query.RRunningConfigQuery;
import com.ssyf.module.robot.service.RRunningConfigService;
import com.ssyf.module.robot.mapper.RRunningConfigMapper;
import com.ssyf.plugs.cache.service.impl.RedisCacheService;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
import com.ssyf.plugs.cache.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author ELSA
* @description 针对表【r_running_config(运行配置表)】的数据库操作Service实现
* @createDate 2025-12-18 10:53:31
*/
@Service
public class RRunningConfigServiceImpl extends ServiceImpl<RRunningConfigMapper, RRunningConfig>
    implements RRunningConfigService{

    @Autowired
    private RedisCacheService cacheService;

    /**
     * Redis缓存键前缀
     */
    private static final String CACHE_KEY_PREFIX = "running:config:";

    /**
     * 缓存过期时间（秒）
     */
    private static final long CACHE_EXPIRE_SECONDS = 3600;

    @Override
    public RRunningConfig addOne(RRunningConfigQuery query) {
        if(StrUtil.isBlank(query.getConfigName())){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "配置名称不能为空");
        }
        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        RRunningConfig entity = BeanUtil.toBean(query ,RRunningConfig.class);
        entity.setUuid(IdUtil.simpleUUID());
        entity.setCreatorUuid(clientInfo.getId().toString()).setCreator(clientInfo.getNickname())
                .setCreateTime(LocalDateTime.now());
        this.save(entity);
        
        // 清除缓存，确保下次查询时获取最新数据
        String cacheKey = CACHE_KEY_PREFIX + entity.getUuid();
        cacheService.remove(cacheKey);
        
        return entity;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByUid(String uuid) {
        checkedExistAndGet(uuid);
        this.remove(createBaseWrapper(null).eq(RRunningConfig::getUuid, uuid));
        
        // 清除缓存
        String cacheKey = CACHE_KEY_PREFIX + uuid;
        cacheService.remove(cacheKey);
    }

    @Override
    public void removeBatchByUids(List<String> uuids) {
        this.remove(createBaseWrapper(null).in(RRunningConfig::getUuid, uuids));
        
        // 清除缓存
        for (String uuid : uuids) {
            String cacheKey = CACHE_KEY_PREFIX + uuid;
            cacheService.remove(cacheKey);
        }
    }

    @Override
    public void updateByUid(String uuid, RRunningConfigQuery query) {
        this.checkedExistAndGet(uuid);
        query.setUuid(null);
        RRunningConfig update = BeanUtil.toBean(query ,RRunningConfig.class);
        LambdaQueryWrapper<RRunningConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RRunningConfig::getUuid, uuid);
        this.update(update , wrapper);
        
        // 清除缓存，确保下次查询时获取最新数据
        String cacheKey = CACHE_KEY_PREFIX + uuid;
        cacheService.remove(cacheKey);
    }

    @Override
    public RRunningConfig getOneByUid(String uuid) {
        String cacheKey = CACHE_KEY_PREFIX + uuid;
        
        // 先从缓存中获取
        RRunningConfig cachedConfig = (RRunningConfig) cacheService.get(cacheKey);
        if (cachedConfig != null) {
            return cachedConfig;
        }
        
        // 缓存中没有，从数据库查询
        RRunningConfig config = this.getOne(createBaseWrapper(null).eq(RRunningConfig::getUuid, uuid));
        
        // 如果查询到数据，放入缓存
        if (config != null) {
            cacheService.put(CACHE_EXPIRE_SECONDS, cacheKey, config);
        }
        
        return config;
    }

    @Override
    public PageInfo<RRunningConfig> getPage(RRunningConfigQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return PageInfo.of(this.list(createBaseWrapper(query)));
    }

    @Override
    public List<RRunningConfig> getList(RRunningConfigQuery query) {
        return this.list(createBaseWrapper(query));
    }

    @Override
    public RRunningConfig checkedExistAndGet(String uuid) {
        RRunningConfig old = this.getOne(createBaseWrapper(null).eq(RRunningConfig::getUuid, uuid));
        if (old == null) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "数据不存在");
        }
        return old;
    }

    @Override
    public Integer countBy(RRunningConfigQuery query) {
        return this.count(createBaseWrapper(query));
    }

    private LambdaQueryWrapper<RRunningConfig> createBaseWrapper(RRunningConfigQuery query) {
        LambdaQueryWrapper<RRunningConfig> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.eq(query.getStatus() != null, RRunningConfig::getStatus, query.getStatus());
        //uuids
        wrapper.in(query.getUuids() != null && !query.getUuids().isEmpty(), RRunningConfig::getUuid, query.getUuids());
        wrapper.like(StrUtil.isNotBlank(query.getUuid()), RRunningConfig::getUuid, query.getUuid());
        wrapper.like(StrUtil.isNotBlank(query.getConfigName()), RRunningConfig::getConfigName, query.getConfigName());
         wrapper.ge(query.getCreateTimeStart() != null, RRunningConfig::getCreateTime, query.getCreateTimeStart());
        wrapper.le(query.getCreateTimeEnd() != null, RRunningConfig::getCreateTime, query.getCreateTimeEnd());
        wrapper.like(StrUtil.isNotBlank(query.getCreator()), RRunningConfig::getCreator, query.getCreator());
        wrapper.eq(StrUtil.isNotBlank(query.getCreatorUuid()), RRunningConfig::getCreatorUuid, query.getCreatorUuid());
        
        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(RRunningConfig.class, wrapper, query.getSorts());
        } else {
            wrapper.orderByDesc(RRunningConfig::getCreateTime);
        }
        return wrapper;
    }
}




