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.RGiftConfig;
import com.ssyf.module.robot.domain.query.RGiftConfigQuery;
import com.ssyf.module.robot.service.RGiftConfigService;
import com.ssyf.module.robot.mapper.RGiftConfigMapper;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
* @author ELSA
* @description 针对表【r_gift_config(礼物配置表)】的数据库操作Service实现
* @createDate 2025-12-18 10:53:31
*/
@Service
public class RGiftConfigServiceImpl extends ServiceImpl<RGiftConfigMapper, RGiftConfig>
    implements RGiftConfigService{

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String CACHE_KEY_PREFIX = "gift_config:";
    private static final long CACHE_EXPIRE_HOURS = 24;

    @Override
    public RGiftConfig addOne(RGiftConfigQuery query) {
        if(StrUtil.isBlank(query.getConfigName())){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "礼物名称不能为空");
        }
        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        RGiftConfig entity = BeanUtil.toBean(query ,RGiftConfig.class);
        entity.setUuid(IdUtil.simpleUUID());
        entity.setCreatorUuid(clientInfo.getId().toString()).setCreator(clientInfo.getNickname())
                .setCreateTime(LocalDateTime.now());
        this.save(entity);
        return entity;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByUid(String uuid) {
        checkedExistAndGet(uuid);
        this.remove(createBaseWrapper(null).eq(RGiftConfig::getUuid, uuid));
        
        // 删除成功后清除缓存
        String cacheKey = CACHE_KEY_PREFIX + uuid;
        redisTemplate.delete(cacheKey);
    }

    @Override
    public void removeBatchByUids(List<String> uuids) {
        this.remove(createBaseWrapper(null).in(RGiftConfig::getUuid, uuids));
        
        // 批量删除成功后清除缓存
        for (String uuid : uuids) {
            String cacheKey = CACHE_KEY_PREFIX + uuid;
            redisTemplate.delete(cacheKey);
        }
    }

    @Override
    public void updateByUid(String uuid, RGiftConfigQuery query) {
        this.checkedExistAndGet(uuid);
        query.setUuid(null);
        RGiftConfig update = BeanUtil.toBean(query ,RGiftConfig.class);
        LambdaQueryWrapper<RGiftConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RGiftConfig::getUuid, uuid);
        this.update(update , wrapper);
        
        // 更新成功后清除缓存，下次查询时会重新加载
        String cacheKey = CACHE_KEY_PREFIX + uuid;
        redisTemplate.delete(cacheKey);
    }

    @Override
    public RGiftConfig getOneByUid(String uuid) {
        String cacheKey = CACHE_KEY_PREFIX + uuid;
        
        // 先尝试从缓存获取
        RGiftConfig cachedConfig = (RGiftConfig) redisTemplate.opsForValue().get(cacheKey);
        if (cachedConfig != null) {
            return cachedConfig;
        }
        
        // 缓存未命中，查询数据库
        RGiftConfig config = this.getOne(createBaseWrapper(null).eq(RGiftConfig::getUuid, uuid));
        
        // 如果查询到结果，存入缓存
        if (config != null) {
            redisTemplate.opsForValue().set(cacheKey, config, CACHE_EXPIRE_HOURS, TimeUnit.HOURS);
        }
        
        return config;
    }

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

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

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

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

    private LambdaQueryWrapper<RGiftConfig> createBaseWrapper(RGiftConfigQuery query) {
        LambdaQueryWrapper<RGiftConfig> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.like(StrUtil.isNotBlank(query.getUuid()), RGiftConfig::getUuid, query.getUuid());
        wrapper.ge(query.getCreateTimeStart() != null, RGiftConfig::getCreateTime, query.getCreateTimeStart());
        wrapper.le(query.getCreateTimeEnd() != null, RGiftConfig::getCreateTime, query.getCreateTimeEnd());
        wrapper.like(StrUtil.isNotBlank(query.getCreator()), RGiftConfig::getCreator, query.getCreator());
        wrapper.eq(StrUtil.isNotBlank(query.getCreatorUuid()), RGiftConfig::getCreatorUuid, query.getCreatorUuid());
        wrapper.like(StrUtil.isNotBlank(query.getConfigName()), RGiftConfig::getConfigName, query.getConfigName());
        wrapper.ge(query.getMinWatchDuration() != null, RGiftConfig::getMinWatchDuration, query.getMinWatchDuration());
        wrapper.le(query.getMaxWatchDuration() != null, RGiftConfig::getMaxWatchDuration, query.getMaxWatchDuration());
        wrapper.ge(query.getMinOnlineUsers() != null, RGiftConfig::getMinOnlineUsers, query.getMinOnlineUsers());
        wrapper.le(query.getMaxOnlineUsers() != null, RGiftConfig::getMaxOnlineUsers, query.getMaxOnlineUsers());
        wrapper.ge(query.getMinAmount() != null, RGiftConfig::getMinAmount, query.getMinAmount());
        
        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(RGiftConfig.class, wrapper, query.getSorts());
        } else {
            wrapper.orderByDesc(RGiftConfig::getCreateTime);
        }
        return wrapper;
    }
}




