package com.cf.imes.framework.organ.core.service;

import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.cache.CacheUtils;
import com.cf.imes.module.system.api.organ.OrganApi;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

import java.time.Duration;
import java.util.List;

/**
 * Organ 框架 Service 实现类
 *
 * @author 晨丰科技
 */
@RequiredArgsConstructor
public class OrganFrameworkServiceImpl implements OrganFrameworkService {

    private final OrganApi organApi;

    /**
     * 针对 {@link #getOrganIds()} 的缓存
     */
    private final LoadingCache<Object, List<Long>> getOrganIdsCache = CacheUtils.buildAsyncReloadingCache(
            Duration.ofMinutes(1L), // 过期时间 1 分钟
            new CacheLoader<Object, List<Long>>() {

                @Override
                public List<Long> load(Object key) {
                    return organApi.getOrganIdList().getCheckedData();
                }

            });

    /**
     * 针对 {@link #validOrgan(Long)} 的缓存
     */
    private final LoadingCache<Long, CommonResult<Boolean>> validOrganCache = CacheUtils.buildAsyncReloadingCache(
            Duration.ofMinutes(1L), // 过期时间 1 分钟
            new CacheLoader<Long, CommonResult<Boolean>>() {

                @Override
                public CommonResult<Boolean> load(Long id) {
                    return organApi.validOrgan(id);
                }

            });

    @Override
    @SneakyThrows
    public List<Long> getOrganIds() {
        return getOrganIdsCache.get(Boolean.TRUE);
    }

    @Override
    @SneakyThrows
    public void validOrgan(Long id) {
        validOrganCache.get(id).checkError();
    }

}
