package com.multictrl.modules.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.multictrl.common.service.impl.BaseServiceImpl;
import com.multictrl.modules.business.dao.CacheDao;
import com.multictrl.modules.business.entity.CacheEntity;
import com.multictrl.modules.business.service.CacheService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 数据缓存表
 *
 * @author Sdy
 * @since 1.0.0 2026-04-27
 */
@Service
public class CacheServiceImpl extends BaseServiceImpl<CacheDao, CacheEntity> implements CacheService {
    private final Map<String, ReentrantLock> cacheLock = new ConcurrentHashMap<>();

    @Override
    public void saveOrUpdateCache(String key, String value) {
        ReentrantLock lock = cacheLock.computeIfAbsent(key, k -> new ReentrantLock());
        lock.lock();
        try {
            CacheEntity cacheEntity = baseDao.selectOne(new QueryWrapper<CacheEntity>().eq("key", key));
            if (cacheEntity == null) {
                cacheEntity = new CacheEntity();
                cacheEntity.setKey(key);
                cacheEntity.setValue(value);
                baseDao.insert(cacheEntity);
            } else {
                cacheEntity.setValue(value);
                cacheEntity.setUpdateDate(new Date());
                baseDao.updateById(cacheEntity);
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public String getCache(String key) {
        CacheEntity cacheEntity = baseDao.selectOne(new QueryWrapper<CacheEntity>().eq("key", key));
        if (cacheEntity == null) {
            return null;
        }

        return cacheEntity.getValue();
    }
}