package com.base.track.task.handler;


import com.base.orbit.mq.model.BaseHeadMqDTO;
import com.base.orbit.mq.topics.TopicConst;
import com.base.orbit.utils.DateUtils;
import com.base.orbit.utils.IdGenerator;
import com.base.orbit.utils.StringUtil;
import com.base.task.handler.TaskHandler;
import com.base.task.model.Enums.TaskTypeEnum;
import com.base.task.model.Mapping;
import com.base.task.model.Task;
import com.base.track.config.sharding.ShardingAlgorithmTool;
import com.base.track.config.sharding.enums.ShardingTableCacheEnum;
import com.base.track.mapper.EphDataMapper;
import com.base.track.model.dto.request.QueryEphListDTO;
import com.base.track.model.entity.*;
//import com.base.track.mq.MqProducer;
import com.base.track.mq.model.TrackBodyMqResultDTO;
import com.base.track.mq.model.TrackMqResultDTO;
import com.base.track.service.EphDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Mapping(taskTypeEnum = TaskTypeEnum.EPHEMERIS_CALCULATION)
@Service
@Slf4j
public class EphemerisCalculationTaskHander implements TaskHandler {

    @Resource
    EphDataMapper ephDataMapper;

    @Resource
    EphDataService ephDataService;
//    @Resource
//    MqProducer mqProducer;



    @Override
    public void taskExecute(Task task) {
        try {
            log.info("星历入库");
            String code = String.valueOf(task.getSatelliteCodes().get(0));
            // 判断如果为12或14，并且不是J2000，则不做任何处理
            if ((code.contains("QWERT12") || code.contains("QWERT14"))) {
                return;
            }
            String[] split = task.getStartTime().split("-");

            // 星历结果文件地址
            String ephFileName = code + "_" + split[0] + "_" + split[1] + ".eph";

            FileInputStream fileInputStream = new FileInputStream(task.getResultDataSavePath()+ephFileName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader1 = new BufferedReader(inputStreamReader);
            BufferedReader bufferedReader = new BufferedReader(bufferedReader1);
            List<EphData> list = new ArrayList<>();
            String result = null;
            code = StringUtil.change(code);
            while ((result = bufferedReader.readLine()) != null) {
                //  根据空格进行截取
                String[] str = result.split("\\s+");
                EphData rpcDTO = new EphData();
                rpcDTO.setId(IdGenerator.getId());
                String time = str[2].replace(".000", "");
                rpcDTO.setEphTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str[1] + " " + time));
                Date newdate = new Date(rpcDTO.getEphTime().getTime()+8*3600*1000);
                rpcDTO.setEphTime(newdate);
                rpcDTO.setX(BigDecimal.valueOf(Double.parseDouble(str[3])));
                rpcDTO.setY(BigDecimal.valueOf(Double.parseDouble(str[4])));
                rpcDTO.setZ(BigDecimal.valueOf(Double.parseDouble(str[5])));
                rpcDTO.setVX(BigDecimal.valueOf(Double.parseDouble(str[6])));
                rpcDTO.setVY(BigDecimal.valueOf(Double.parseDouble(str[7])));
                rpcDTO.setVZ(BigDecimal.valueOf(Double.parseDouble(str[8])));
                rpcDTO.setCirCle(str[9]);
                String codemin=code.toLowerCase();
                rpcDTO.setCode(codemin);
                list.add(rpcDTO);
            }
            //先删除
            String codemin=code.toLowerCase();
            if (ShardingAlgorithmTool.getShardingTable(ShardingTableCacheEnum.BASEEPHDATA, "base_eph_data_" + codemin)) {
                // 删除表中该时间内的信息
                Date startTime1 = list.get(0).getEphTime();
                Date endTime1 = list.get(list.size() - 1).getEphTime();
                QueryEphListDTO queryEphListDTO = new QueryEphListDTO();
                queryEphListDTO.setStartTime(startTime1);
                queryEphListDTO.setEndTime(endTime1);
                queryEphListDTO.setCode(code);
                ephDataMapper.delData(queryEphListDTO);
            }
       /*     for (EphData ephData:list){
                ephDataService.save(ephData);
            }*/
            ephDataService.saveBatch(list);
            //发送消息
            //发送消息
           /* task.getCountDownLatch().countDown();*/
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }finally {
            task.getCountDownLatch().countDown();
        }
    }
}
