package thyyxxk.webserver.service.hutoolcache;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.YiZhuLuRuDao;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.YaoPinXinXi;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.YaoPingJiLiang;
import thyyxxk.webserver.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class DrugCache implements HutoolCacheInterface<DrugCache.YpInfo> {
    private final YiZhuLuRuDao dao;
    private static final int CACHE_SIZE = 100;
    Cache<String, DrugCache.YpInfo> cache = CacheUtil.newLFUCache(CACHE_SIZE);

    @Data
    public static class YpInfo {
        private YaoPinXinXi info;
        private List<YaoPingJiLiang> jiLiang;
    }

    @Override
    public void put(String key, DrugCache.YpInfo value) {
        if (value != null) {
            cache.put(key, value);
        }
    }

    @Override
    public DrugCache.YpInfo get(String key) {
        YpInfo ypInfo = cache.get(key);
        if (ypInfo == null) {
            YaoPinXinXi yp = dao.huoQuYaoPin(key);
            if (null != yp) {
                ypInfo = new YpInfo();
                ypInfo.setInfo(yp);
                List<YaoPingJiLiang> yaoPingJiLiang = new ArrayList<>();
                if (StringUtil.notBlank(yp.getWeighUnit())) {
                    yaoPingJiLiang.add(new YaoPingJiLiang(yp.getWeighUnit(), yp.getWeighUnitName(), yp.getWeight()));
                }
                if (StringUtil.notBlank(yp.getVolUnit())) {
                    yaoPingJiLiang.add(new YaoPingJiLiang(yp.getVolUnit(), yp.getVolUnitName(), yp.getVolum()));
                }
                if (StringUtil.notBlank(yp.getPackUnit())) {
                    yaoPingJiLiang.add(new YaoPingJiLiang(yp.getPackUnit(), yp.getPackUnitName(), yp.getPackSize()));
                }
                ypInfo.setJiLiang(yaoPingJiLiang);
                put(key, ypInfo);
            }
        }
        return ypInfo;
    }

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

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

    @Override
    public String getLabel() {
        return "药品缓存";
    }

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


}
