package com.sckw.excel.translate.context;

import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.exception.SourceInitializeException;
import com.sckw.core.model.enums.LogisticsOrderEnum;
import com.sckw.excel.translate.Sources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author lfdc
 * @version v1
 * @create 2022-01-24 16:23:31
 * @copyright
 */
@Component("enumsSource")
public class Enums implements Source, Ordered {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public Enums() {
        initial();
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<Integer, Object> get() throws SourceInitializeException {
        Object values = redisTemplate.opsForValue().get(Sources.SOURCE_ENUMERATE);
        if (values == null) {
            return flush();
        }
        return (Map<Integer, Object>) values;
    }

    /**
     * 该方法获取枚举数据
     * @return
     * @throws SourceInitializeException
     */
    @Override
    @SuppressWarnings("unchecked")
    public Map<Integer, Object> flush() throws SourceInitializeException {
        try {
            Map<Integer, Object> source = new HashMap<>(NumberConstant.SIXTEEN);
//            source.putAll(Stream.of(OrderCancelEnum.values()).collect(Collectors.toMap(OrderCancelEnum::getCode, OrderCancelEnum::getMsg)));
//            source.putAll(Stream.of(WarehouseCheckEnum.values()).collect(Collectors.toMap(WarehouseCheckEnum::getCode, WarehouseCheckEnum::getMsg)));
            source.putAll(Stream.of(LogisticsOrderEnum.values()).collect(Collectors.toMap(LogisticsOrderEnum::getCode, LogisticsOrderEnum::getDestination)));
            redisTemplate.opsForValue().set(Sources.SOURCE_ENUMERATE, source, 1, TimeUnit.DAYS);
            return source;
        } catch (Exception e) {
            throw new SourceInitializeException("failed to get enumerate cache data, ex:" + e.toString());
        }
    }

    @Override
    public void clear() {
        redisTemplate.delete(Sources.SOURCE_ENUMERATE);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

}