package thyyxxk.webserver.service.hutoolcache;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.dao.his.hutoolcache.HutoolCacheDao;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.utils.StringUtil;

import java.util.List;

@Component
@RequiredArgsConstructor
public class RegionCache implements HutoolCacheInterface<String> {
    private final static Cache<String, String> cache = CacheUtil.newLFUCache(50);

    private final HutoolCacheDao dao;

    @Override
    public void put(String key, String value) {
        cache.put(key, value);
    }

    @Override
    public String get(String code) {
        if (StringUtil.isBlank(code)) {
            return null;
        }
        String regionName = cache.get(code);
        if (null == regionName) {
            CodeName region = dao.selectAdmdvsNameAndParentName(code);
            if (null == region) {
                region = dao.selectAdmdvsName(code);
                if (null == region) {
                    region = dao.selectAdmdvsNameAndParentName(code.substring(0, 4) + "00");
                    if (null == region) {
                        region = dao.selectAdmdvsName(code.substring(0, 4) + "00");
                    }
                }
            }
            if (null == region) {
                regionName = "未知";
            } else {
                regionName = region.getCode() + region.getName();
            }
            put(code, regionName);
        }
        return regionName;
    }

    @Override
    public void del(String key) {
        cache.remove(key);
    }


    @Override
    public List<CacheAll> getAll() {
        return this.getAllUtils(cache.cacheObjIterator());
    }

    @Override
    public void clear() {
        cache.clear();
    }


    @Override
    public String getLabel() {
        return "区域缓存";
    }
}
