package com.ruoyi.commonapi.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.commonapi.domain.VerificationSource;
import com.ruoyi.commonapi.entity.dto.VerificationDTO;
import com.ruoyi.commonapi.entity.enums.VerificationSourceEnum;
import com.ruoyi.commonapi.mapper.VerificationSourceMapper;
import com.ruoyi.commonapi.service.VerificationSourceService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 验证码资源维护 业务层实现
 *
 * @author Chopper
 * @since 2020/11/17 3:48 下午
 */
@Service
public class VerificationSourceServiceImpl implements VerificationSourceService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private VerificationSourceMapper verificationSourceMapper;

    @Override
    public VerificationDTO initCache() {
        List<VerificationSource> dbList = verificationSourceMapper.selectVerificationSourceList(new VerificationSource());
        List<VerificationSource> resourceList = new ArrayList<>();
        List<VerificationSource> sliderList = new ArrayList<>();
        for (VerificationSource item : dbList) {
            if (item.getType().equals(VerificationSourceEnum.RESOURCE.name())) {
                resourceList.add(item);
            } else if (item.getType().equals(VerificationSourceEnum.SLIDER.name())) {
                sliderList.add(item);
            }
        }
        VerificationDTO verificationDTO = new VerificationDTO();
        verificationDTO.setVerificationResources(resourceList);
        verificationDTO.setVerificationSlider(sliderList);
        redisCache.setCacheObject(VERIFICATION_CACHE, verificationDTO);
        return verificationDTO;
    }

    @Override
    public VerificationDTO getVerificationCache() {
        VerificationDTO verificationDTO;
        try {
            verificationDTO = redisCache.getCacheObject(VERIFICATION_CACHE);
        } catch (ClassCastException cce) {
            verificationDTO = null;
        }
        if (verificationDTO == null) {
            return initCache();
        }
        return verificationDTO;
    }
}