package com.fs.qw.cache;

import com.fs.common.utils.StringUtils;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.sop.domain.SopUserLogs;
import com.fs.sop.mapper.QwSopMapper;
import com.fs.sop.mapper.SopUserLogsMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class QwSopCacheService {
    @Autowired
    private QwSopMapper qwSopMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private SopUserLogsMapper sopUserLogsMapper;

    private static final Cache<String, String> QW_SOP_NAME_CACHE = Caffeine.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();

    private static final Cache<String, String> QW_SOP_LOG_NAME_CACHE = Caffeine.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();


    public String getQwSopNameBySopId(String sopId) {
        return QW_SOP_NAME_CACHE.get(sopId,e->{
            String sopName = qwSopMapper.selectQwSopNameBySopId(sopId);
            if(StringUtils.isNotBlank(sopName)){
                return sopName;
            }
            return "-";
        });
    }

    public String getQwSopLogNameBySopId(String periodId) {
        return QW_SOP_LOG_NAME_CACHE.get(periodId,e->{
            SopUserLogs sopUserLogs = sopUserLogsMapper.selectSopUserLogsById(periodId);

            if(sopUserLogs != null) {
                String qwUserName = qwUserMapper.selectQwUserName(sopUserLogs.getQwUserId(), sopUserLogs.getCorpId());
                if(qwUserName != null) {
                    return qwUserName+"_"+sopUserLogs.getStartTime();
                }
            }
            return "-";
        });
    }
}
