package com.fs.company.cache.impl;

import com.fs.company.cache.ICompanyCacheService;
import com.fs.company.domain.Company;
import com.fs.company.service.ICompanyService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ICompanyCacheServiceImpl implements ICompanyCacheService {
    @Autowired
    private ICompanyService companyService;

    private static final Cache<Long, Company> COMPANY_CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(3, TimeUnit.MINUTES)
            .build();
    private static final Cache<Long, String> COMPANY_NAME_CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(7, TimeUnit.DAYS)
            .build();
    @Override
    public Company selectCompanyById(Long companyId) {
        return COMPANY_CACHE.get(companyId,e-> companyService.selectCompanyById(companyId));
    }

    @Override
    public String selectCompanyNameById(Long companyId) {
        if(companyId == null){
            return "未找到";
        }
        return COMPANY_NAME_CACHE.get(companyId, e-> {
            Company company = companyService.selectCompanyById(companyId);
            if(company == null){
                return "";
            }
            return String.format("%s_%s",company.getCompanyName(),company.getCompanyId());
        });
    }
}
