package com.ruoyi.cai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.constant.RedisConstant;
import com.ruoyi.cai.domain.Citys;
import com.ruoyi.cai.mapper.CitysMapper;
import com.ruoyi.cai.service.CitysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 城市Service业务层处理
 *
 * @author 77
 * @date 2023-12-30
 */
@Service
public class CitysServiceImpl extends ServiceImpl<CitysMapper, Citys> implements CitysService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        List<Citys> list = this.list();
        Map<Long, String> map = list.stream().collect(Collectors.toMap(Citys::getId, Citys::getName));
        redisTemplate.opsForHash().putAll(RedisConstant.CITY_CACHE_REDIS, map);
    }

    @Override
    public Map<Long, String> all() {
        String value = redisTemplate.opsForValue().get(RedisConstant.CITY_CACHE_ALL_REDIS);
        if(value != null){
            return JSON.parseObject(value, new TypeReference<LinkedHashMap<Long, String>>(){});
        }
        List<Citys> list = this.list();
        Map<Long, String> map = list.stream().collect(Collectors.toMap(Citys::getId, Citys::getName));
        redisTemplate.opsForValue().set(RedisConstant.CITY_CACHE_REDIS,JSON.toJSONString(map),30, TimeUnit.DAYS);
        return map;
    }

    @Override
    public String getByCityId(Integer cityId){
        if(cityId == null || cityId == 0){
            return null;
        }
        Object val = redisTemplate.opsForHash().get(RedisConstant.CITY_CACHE_REDIS, cityId);
        if(val != null){
            return String.valueOf(val);
        }
        Citys city = this.getById(cityId);
        if(city == null){
            return null;
        }
        redisTemplate.opsForHash().put(RedisConstant.CITY_CACHE_REDIS, cityId, city.getName());
        return city.getName();
    }
}
