package cn.com.taiji.track.service.impl;

import cn.com.taiji.track.entity.BeidouLocationEntity;
import cn.com.taiji.track.mapper.BeidouLocationMapper;
import cn.com.taiji.track.service.IBeidouLocationService;
import cn.com.taiji.track.utils.LatLngUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 * @Author: hujie@umisoft.cn
 * @Date: 2021/11/30 9:59 下午
 */
@Service
@Slf4j
public class BeidouLocationServiceImpl extends ServiceImpl<BeidouLocationMapper, BeidouLocationEntity> implements IBeidouLocationService {
    private Vector<BeidouLocationEntity> locationEntities= new Vector<>();

    @Override
    public void beidouDynamicShipToCache(List<ConsumerRecord<?, ?>> records){
        try {
            for (ConsumerRecord<?, ?> record : records) {
                Optional message = Optional.ofNullable(record.value());
                if (message.isPresent()) {
                    Object msg = message.get();
                    BeidouLocationEntity locationEntity = JSONObject.parseObject(msg.toString(), BeidouLocationEntity.class);
                    locationEntity.setLocation(String.format("POINT(%s %s)",locationEntity.getLongitude(),locationEntity.getLatitude()));
                    BigDecimal longitudeDecimal = new BigDecimal(locationEntity.getLongitude());
                    locationEntity.setLongitude(LatLngUtil.latLng2Dfm(longitudeDecimal.doubleValue()));
                    BigDecimal latitudeDecimal = new BigDecimal(locationEntity.getLatitude());
                    locationEntity.setLatitude(LatLngUtil.latLng2Dfm(latitudeDecimal.doubleValue()));
                    locationEntities.add(locationEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void cacheBeidouToMySql() {
        Date begin = new Date();
        if(locationEntities.size() > 0){
            List<BeidouLocationEntity> saveList = new ArrayList<>(locationEntities);
            locationEntities.clear();
            saveBatch(saveList);
//            log.info("位置数据写入数据库完成！耗时 {} 毫秒, 合计保存 {} 条记录", (new Date()).getTime() - begin.getTime(), saveList.size());
        }
    }
}
