package com.ycwl.basic.profitsharing.repository;

import com.alibaba.fastjson.JSONObject;
import com.ycwl.basic.profitsharing.entity.ProfitSharingConfig;
import com.ycwl.basic.profitsharing.mapper.ProfitSharingConfigMapper;
import com.ycwl.basic.profitsharing.mapper.ProfitSharingUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class ProfitSharingRepository {
    @Autowired
    private ProfitSharingConfigMapper configMapper;
    @Autowired
    private ProfitSharingUserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public static final String PROFIT_SHARING_SCENIC_CONFIG_CACHE_KEY = "profit:scenic:%s";

    public ProfitSharingConfig getScenicConfig(Long id) {
        if (redisTemplate.hasKey(String.format(PROFIT_SHARING_SCENIC_CONFIG_CACHE_KEY, id))) {
            return JSONObject.parseObject(redisTemplate.opsForValue().get(String.format(PROFIT_SHARING_SCENIC_CONFIG_CACHE_KEY, id)), ProfitSharingConfig.class);
        }
        ProfitSharingConfig scenicConfig = configMapper.findByScenicId(id);
        if (scenicConfig != null) {
            scenicConfig.setUsers(userMapper.findByConfigId(scenicConfig.getId()));
            redisTemplate.opsForValue().set(String.format(PROFIT_SHARING_SCENIC_CONFIG_CACHE_KEY, id), JSONObject.toJSONString(scenicConfig));
        }
        return scenicConfig;
    }

    public void clearScenicConfigCache(Long id) {
        redisTemplate.delete(String.format(PROFIT_SHARING_SCENIC_CONFIG_CACHE_KEY, id));
    }
}
