package com.base.track.task.handler;

import com.base.orbit.utils.DateUtils;
import com.base.orbit.utils.FileUtil;
import com.base.orbit.utils.IdGenerator;
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.mapper.EphDataMapper;
import com.base.track.model.entity.StationBaseBizInfo;
import com.base.track.model.entity.TrbutData;
import com.base.track.model.entity.TrbutHrpreData;
import com.base.track.service.EphDataService;
import com.base.track.service.TrbutAntennaDataService;
import com.base.track.service.TrbutDataService;
import com.base.track.service.TrbutHrpreDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Mapping(taskTypeEnum = TaskTypeEnum.ORBIT_NUM)
@Service
@Slf4j
public class StationArcTaskHander implements TaskHandler {

    @Resource
    EphDataMapper ephDataMapper;

    @Resource
    EphDataService ephDataService;


    @Resource
    TrbutDataService trbutDataService;
    @Resource
    TrbutAntennaDataService trbutAntennaDataService;

    @Resource
    TrbutHrpreDataService trbutHrpreDataService;


    @Override
    public void taskExecute(Task task) throws IOException, ParseException {
        try {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            FileInputStream fileInputStream = new FileInputStream(task.getResultDataSavePath() + task.getResultDataSaveName());
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader1 = new BufferedReader(inputStreamReader);
            BufferedReader bufferedReader = new BufferedReader(bufferedReader1);
            String result;
            int line = 0;
            String code = task.getSatelliteCode();
            List<TrbutData> trbutDatas = new ArrayList<>();
            while ((result = bufferedReader.readLine()) != null) {
                if (line != 0 && line != 1) {
                    List<String> r = FileUtil.getLineArray(result);
                    String pitStr = r.get(0) + " " + r.get(1);
                    String rsStr = r.get(3) + " " + r.get(4);
                    String reStr = r.get(5) + " " + r.get(6);
                    String exitStr = r.get(7) + " " + r.get(8);
                    Date pitTime = new Date(sdf.parse(pitStr).getTime() + 8 * 3600 * 1000);
                    Date rsTime = new Date(sdf.parse(rsStr).getTime() + 8 * 3600 * 1000);
                    Date reTime = new Date(sdf.parse(reStr).getTime() + 8 * 3600 * 1000);
                    Date exitTime = new Date(sdf.parse(exitStr).getTime() + 8 * 3600 * 1000);
                    Date date = sdf.parse(pitStr);
                    // 获取弧段时间和日凌事件事件交叉的个数
                    /* long count = astronomicalForecastList.stream().filter(t -> !(t.getStartTime().compareTo(reTime) > 0 || rsTime.compareTo(t.getEndTime()) > 0)).count();
                     */
                    // 若该资源没有日凌事件影响，则保存
                    /* if (count == 0) {*/
                    TrbutData trbutData = new TrbutData();
//                    trbutData.setId(code + date.getTime());
                    //  id生成策略由圈号+进站方位角+出站方位角组成
                    double startAzimuthDb = Double.parseDouble(r.get(2));
                    double endAzimuthDb = Double.parseDouble(r.get(9));
                    trbutData.setId(code + Integer.parseInt(r.get(12)) + String.valueOf(startAzimuthDb).replace(".", "") + String.valueOf(endAzimuthDb).replace(".", "") + DateUtils.dateTimeNow());
                    trbutData.setPitTime(pitTime);
                    trbutData.setStartAzimuth(startAzimuthDb);
                    trbutData.setReceiveStartTime(rsTime);
                    trbutData.setReceiveEndTime(reTime);
                    trbutData.setExitTime(exitTime);
                    trbutData.setEndAzimuth(endAzimuthDb);
                    trbutData.setHighestElevationAngle(Double.parseDouble(r.get(10)));
                    trbutData.setHighestAzimuth(Double.parseDouble(r.get(11)));
                    trbutData.setOrbitNum(Integer.parseInt(r.get(12)));
                    trbutData.setSatelliteName(task.getSatelliteName());
                    trbutData.setCreate_time(new Date());
                    trbutData.setStationType(0);
                    trbutData.setStationCode(task.getStationCode());
                    trbutData.setStationName(task.getStationName());
                    trbutData.setSatelliteCode(task.getSatelliteCode());
                    //  通过任务中获取
                    StationBaseBizInfo stationBaseBizInfo = (StationBaseBizInfo) task.getBaseBizInfo();
                    trbutData.setStationId(stationBaseBizInfo.getStationId());
                    trbutData.setSatelliteId(stationBaseBizInfo.getSatelliteId());

                    long diff = reTime.getTime() - rsTime.getTime();
                    trbutData.setDuration((int) diff);
                    List<TrbutData> list = new ArrayList<>();
                    list.add(trbutData);
                    trbutDataService.saveOrUpdateByPitTimeAndSatelliteIdAndStationIdAndExitTime(list);
                    /* trbutAntennaDataService.asyncSaveTrbutAntennaData(trbutData);*/
                }
                line++;
            }

            //发送消息
            /* task.getCountDownLatch().countDown();*/
            //俯仰角解析保存
            /* saveHrpre(task);*/

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            task.getCountDownLatch().countDown();
        }

    }

    public void saveHrpre(Task task) {
        log.info("开始计算天线引导数据");
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            if (task.getResultHrpreDataSaveName() != null) {
                FileInputStream fileInputStream = new FileInputStream(task.getResultDataSavePath() + task.getResultHrpreDataSaveName());
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader1 = new BufferedReader(inputStreamReader);
                BufferedReader bufferedReader = new BufferedReader(bufferedReader1);
                String result;
                int line = 0;
                long time = 0;

                String code = task.getSatelliteCode();
                List<TrbutHrpreData> trbutHrpreDataList = new ArrayList<>();
                List<TrbutHrpreData> trbutHrpreDataListsave = new ArrayList<>();
                while ((result = bufferedReader.readLine()) != null) {
                    if (line != 0 && line != 1) {
                        List<String> r = FileUtil.getLineArray(result);
                        String pitStr = r.get(0) + " " + r.get(1);
                        Date pitTime = new Date(sdf.parse(pitStr).getTime() + 8 * 3600 * 1000);
                        TrbutHrpreData trbutHrpreData = new TrbutHrpreData();
                        trbutHrpreData.setId(String.valueOf(IdGenerator.getId()));
                        trbutHrpreData.setPitTime(pitTime);
                        trbutHrpreData.setStartAzimuth(Double.parseDouble(r.get(2)));
                        trbutHrpreData.setStartAzimuthRate(Double.parseDouble(r.get(3)));
                        trbutHrpreData.setPitchAngle(Double.parseDouble(r.get(4)));
                        trbutHrpreData.setPitchAngleRate(Double.parseDouble(r.get(5)));
                        trbutHrpreData.setStationSlopeDistance(Double.parseDouble(r.get(6)));
                        trbutHrpreData.setStationSlopeDistanceRate(Double.parseDouble(r.get(7)));
                        trbutHrpreData.setSatelliteName(task.getSatelliteName());
                        trbutHrpreData.setCreateTime(new Date());
                        trbutHrpreData.setStationType(0);
                        trbutHrpreData.setStationCode(task.getStationCode());
                        trbutHrpreData.setStationName(task.getStationName());
                        trbutHrpreData.setSatelliteCode(task.getSatelliteCode());
                        //  通过任务中获取
                        StationBaseBizInfo stationBaseBizInfo = (StationBaseBizInfo) task.getBaseBizInfo();
                        trbutHrpreData.setStationId(stationBaseBizInfo.getStationId());
                        trbutHrpreData.setSatelliteId(stationBaseBizInfo.getSatelliteId());
                        trbutHrpreDataList.add(trbutHrpreData);
                    }
                    line++;
                }
                if (Objects.nonNull(trbutHrpreDataList) && trbutHrpreDataList.size() > 0) {
                    trbutHrpreDataListsave.add(trbutHrpreDataList.get(0));

                    int count = 60;
                    for (int i = 0; i < trbutHrpreDataList.size() - 2; i++, count += 60) {
                        if (count < trbutHrpreDataList.size() - 2) {
                            trbutHrpreDataListsave.add(trbutHrpreDataList.get(count));
                        }
                    }
                    trbutHrpreDataListsave.add(trbutHrpreDataList.get(trbutHrpreDataList.size() - 1));

                    trbutHrpreDataService.saveBatch(trbutHrpreDataListsave);
                    log.info("天线引导数据计算入库成功！！！");
                }

            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
