package thyyxxk.webserver.service.hutoolcache;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.dao.his.hutoolcache.HutoolCacheDao;

import java.util.List;

@Service
public class DeptCache implements HutoolCacheInterface<DeptCache.Dept> {
    private final HutoolCacheDao dao;
    private static final int CACHE_SIZE = 128;
    Cache<String, Dept> cache = CacheUtil.newLFUCache(CACHE_SIZE);
    Cache<String, String> ybCache = CacheUtil.newLFUCache(CACHE_SIZE);

    @Data
    public static class Dept {
        private String code;
        private String name;
        private String pyCode;
        private String siCaty;
        private String siCatyName;
        private String wjwCode;
    }

    @Autowired
    public DeptCache(HutoolCacheDao dao) {
        this.dao = dao;
    }

    @Override
    public void put(String key, Dept value) {
        if (value != null) {
            cache.put(key, value);
            ybCache.put(value.getSiCaty(), value.getSiCatyName());
        }
    }

    @Override
    public Dept get(String key) {
        if (StrUtil.isBlank(key)) {
            return new Dept();
        }
        Dept dept = cache.get(key);
        if (dept == null) {
            dept = dbInfo(key);
            put(key, dept);
        }
        return dept;
    }

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

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

    public String getDeptName(String code) {
        Dept dept = get(code);
        if (dept == null) {
            return null;
        }
        return dept.getName();
    }

    public String getYbDept(String code) {
        Dept dept = get(code);
        if (dept == null) {
            return null;
        }
        return dept.getSiCaty();
    }

    public String getYbDeptName(String code) {
        String name = ybCache.get(code);
        if (null == name) {
            Dept dept = dao.selectZdUnitCodeByYbCode(code);
            if (dept != null) {
                put(dept.getCode(), dept);
            }
        }
        return ybCache.get(code);
    }

    public Dept dbInfo(String key) {
        return dao.selectZdUnitCode(key);
    }

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

    @Override
    public void refreshCache(String key) {
        put(key, dbInfo(key));
    }

    @Override
    public String getLabel() {
        return "科室";
    }
}
