package com.tofly.gpsboot.util;

import com.alibaba.fastjson.JSON;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.StringUtil;
import com.tofly.es.EsInfo;
import com.tofly.gpsboot.mapper.es.EsSaveInfoMapper;
import com.tofly.gpsboot.service.es.IEsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tuonbed
 * @date 2020/5/15  15:48
 */
@Component
@Slf4j
public class EsSaveInfoUtil {
    @Autowired
    private IEsInfoService iEsInfoService;

    @Autowired
    private EsSaveInfoMapper esSaveInfoMapper;

    private Map<String, String> esIndexCacheMap = new HashMap<>();

    @Value("${gps.data.max}")
    private Integer max;

    private volatile Map<String,Long> carGpsInfo =new HashMap<>();

    public void checkInsertEsInfo(String index) {
        if (isSave(index)) {
            String yearMonth = Date8Util.getYearMonth();
            EsInfo esInfo = new EsInfo();
            esInfo.setEsIndex(index);
            esInfo.setFristTime(yearMonth);
            // 存入缓存
            Map<String, String> map = new HashMap<>(12);
            map.put("esIndex", index);
            map.put("fristTime", yearMonth);
            iEsInfoService.save(esInfo);
            log.info("es缓存插入: {}", JSON.toJSONString(esInfo));
            esIndexCacheMap.putAll(map);
        }
    }

    @PostConstruct
    public void getUsersRtInfo() {
        // 获取当前所有es数据
        Map<String, String> esMap = iEsInfoService.list().stream().collect(Collectors.toMap(EsInfo::getEsIndex, EsInfo::getFristTime, ((k, v) -> v)));
        log.info("初始化加载esgps数据:{}", esMap);
        esIndexCacheMap.putAll(esMap);

        List<Map> carGpsList=esSaveInfoMapper.getCarGpsInfo();
        log.info("初始化加载escargps数据:{}", carGpsList);
        carGpsInfo=carGpsList.stream().collect(Collectors.toMap(m->String.valueOf(m.get("meid")),n-> Long.parseLong(String.valueOf(n.get("carId")))));
    }

    private boolean isSave(String index) {
        return !esIndexCacheMap.containsKey(index);
    }

    /**
     * 最大获取es数据范围判断
     * @param index
     * @return
     */
    public int DyMonth(String index) {
        int t = Date8Util.between(esIndexCacheMap.get(index));
        return Math.min(t, max);
    }

    public long getCarId(String meid){
        return StringUtil.isNotEmpty(meid) ? carGpsInfo.get(meid) : 0;
    }

    public void updateCarGpsInfo(){
        List<Map> cargpsList=esSaveInfoMapper.getCarGpsInfo();
        carGpsInfo=cargpsList.stream().collect(Collectors.toMap(m->(String)m.get("meid"),n-> (Long) n.get("carId")));
    }

}
