package com.base.track.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.api.client.AntennaRpcService;
import com.base.api.client.SatelliteRpcService;
import com.base.api.client.SatelliteStationMatchRpcService;
import com.base.api.client.StationRpcService;
import com.base.api.model.AntennaRpcDTO;
import com.base.api.model.InstanceRpcDTO;
import com.base.api.model.SatelliteRpcDTO;
import com.base.api.model.request.QueryStationAddRpcDTO;
import com.base.orbit.log.ServerNameEnum;
import com.base.track.mapper.TrbutDataMapper;
import com.base.track.mapper.VisualDataMapper;
import com.base.track.model.dto.request.QueryVisualDTO;
import com.base.track.model.dto.request.VisualRequestDTO;
import com.base.track.model.dto.response.VisualDTO;
import com.base.track.model.entity.TrbutData;
import com.base.track.model.entity.VisualData;
import com.base.track.utils.VisualAlgorithmFacde;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xj
 * @since 2023-05-06
 */
@Service
@Slf4j
public class VisualDataService extends ServiceImpl<VisualDataMapper, VisualData> {

    @Resource
    VisualDataMapper visualDataMapper;
    @Resource
    TrbutDataMapper trbutDataMapper;
    @Resource
    StationRpcService stationRpcService;
    @Resource
    SatelliteRpcService satelliteRpcService;
    @Resource
    VisualAlgorithmFacde visualAlgorithmFacde;
    @Resource
    AntennaRpcService antennaRpcService;
    @Resource
    TrbutAntennaDataService trbutAntennaDataService;

    public Object selVisualById(String id) {
        List<VisualData> visualDataList = visualDataMapper.selVisualById(id);
        log.info("sel visual data is success", ServerNameEnum.TRACK_SERVER);
        return visualDataList;
    }

    public Object countVisualByVo(QueryVisualDTO queryVisualDTO) {
        return createDTOByVo(queryVisualDTO.getSatelliteCode(), queryVisualDTO.getStationId(), queryVisualDTO.getAntennaId(), queryVisualDTO.getAntennaVal());
    }

    @Transactional(rollbackFor = Exception.class)
    public Object countVisualByDTO(QueryVisualDTO queryVisualDTO) {
        String id = queryVisualDTO.getId();
        if (countVisualAlg(id, queryVisualDTO.getAntennaVal())) {
            List<VisualDTO> visualDTOS = createDTOByVo(queryVisualDTO.getSatelliteCode(), queryVisualDTO.getStationId(), null, queryVisualDTO.getAntennaVal());
            return visualDTOS;
        }
        return null;
    }


    public List<VisualDTO> createDTOByVo(String satelliteCode, String stationId, String antennaId, String antennaVal) {
        List<VisualDTO> visualDTOS = new LinkedList<>();
        QueryStationAddRpcDTO queryStationAddRpcDTO = selStationInfoById(stationId);
        SatelliteRpcDTO satelliteRpcDTO = selSatelliteById(satelliteCode);
        List<AntennaRpcDTO> antennaRpcDTOList = null;
        if (!StringUtils.isEmpty(antennaId)) {
            antennaRpcDTOList = antennaRpcService.selAntenaInfoByIds(Arrays.asList(queryStationAddRpcDTO.getStationCode()))
                    .stream().filter(antennaRpcDTO -> antennaRpcDTO.getId().equals(antennaId)).collect(Collectors.toList());
        } else {
            antennaRpcDTOList = antennaRpcService.selAntenaInfoByIds(Arrays.asList(queryStationAddRpcDTO.getStationCode()));
        }
        antennaRpcDTOList = antennaRpcDTOList.stream().filter(antennaRpcDTO -> antennaRpcDTO.getTxkj().equals(antennaVal)).collect(Collectors.toList());
        //  载波频率根据卫星获取
        List<Double> fList = new ArrayList<>();
        fList.add(Double.valueOf(satelliteRpcDTO.getCarrier()));
        List<Double> gtList = antennaRpcDTOList.stream().map(AntennaRpcDTO::getDmzGT).collect(Collectors.toList()).stream().map(f -> Double.parseDouble(f)).collect(Collectors.toList());
        //  天线口径
        List<Double> txkjList = new ArrayList<>();
        txkjList.add(Double.valueOf(antennaVal));
        List<Double> elevationList = antennaRpcDTOList.stream().map(AntennaRpcDTO::getZxjsyj).collect(Collectors.toList()).stream().map(f -> Double.parseDouble(f)).collect(Collectors.toList());
        double eirpVal = Double.parseDouble(satelliteRpcDTO.getEirp());

        //  构建余量计算所需参数
        VisualDTO visualDTO = new VisualDTO();
        visualDTO.setEirp(eirpVal);
        visualDTO.setF(fList);
        visualDTO.setH(Double.parseDouble(satelliteRpcDTO.getAltitude()));
        visualDTO.setElevation(elevationList);
        visualDTO.setD(elevationList);
        visualDTO.setLpath(fList, elevationList);
        visualDTO.setGT(gtList);
        visualDTO.setAntenna(txkjList);
        visualDTO.setCno(eirpVal, gtList, visualDTO.getLpath());
        visualDTO.setFb(Double.valueOf(satelliteRpcDTO.getXxsl()));
        visualDTO.setEbNo(visualDTO.getCno());
        visualDTOS.add(visualDTO);

        return visualDTOS;
    }


    /**
     * 根据地面站code查询地面站信息
     *
     * @param stationId
     * @return
     */
    public QueryStationAddRpcDTO selStationInfoById(String stationId) {
        try {
            List<QueryStationAddRpcDTO> stationListByStationIdList = stationRpcService.getStationListByStationIdList(Arrays.asList(stationId));
            Optional<QueryStationAddRpcDTO> stationListByStationIds = stationListByStationIdList.stream().findFirst();
            if (stationListByStationIds.isPresent()) {
                QueryStationAddRpcDTO queryStationAddRpcDTO = stationListByStationIds.get();
                return queryStationAddRpcDTO;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("sel station info by station id is error msg is " + e.getMessage() + "", ServerNameEnum.TRACK_SERVER);
        }
        return null;
    }

    /**
     * 根据WX编号查询WX相关信息
     *
     * @param satelliteCode
     * @return
     */
    public SatelliteRpcDTO selSatelliteById(String satelliteCode) {
        try {
            List<SatelliteRpcDTO> satelliteRpcDTOS = satelliteRpcService.listByIds(Arrays.asList(satelliteCode));
            Optional<SatelliteRpcDTO> satelliteRpcs = satelliteRpcDTOS.stream().findFirst();
            if (satelliteRpcs.isPresent()) {
                SatelliteRpcDTO satelliteRpcDTO = satelliteRpcs.get();
                return satelliteRpcDTO;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("sel satellite info by station id is error msg is " + e.getMessage() + "", ServerNameEnum.TRACK_SERVER);
        }
        return null;
    }


    /**
     * 计算仰角\距离\余量 入库
     *
     * @param id 进出站id
     * @return
     */
    public boolean countVisualAlg(String id, String antennaVal) {
        TrbutData trbutData = trbutDataMapper.selectById(id);       //  进出站
        SatelliteRpcDTO satelliteRpcDTO = selSatelliteById(trbutData.getSatelliteCode());
        QueryStationAddRpcDTO queryStationAddRpcDTO = selStationInfoById(trbutData.getStationId());
        VisualRequestDTO visualRequestDTO = new VisualRequestDTO();     //  链路余量填充对象
        visualRequestDTO.setPitTime(trbutData.getPitTime());
        visualRequestDTO.setExitTime(trbutData.getExitTime());
        visualRequestDTO.setReceiveStartTime(trbutData.getReceiveStartTime());
        visualRequestDTO.setTrbutDataId(id);
        visualRequestDTO.setReceiveEndTime(trbutData.getReceiveEndTime());
        visualRequestDTO.setMinTraceElevation(queryStationAddRpcDTO.getMinTraceElevation());
        visualRequestDTO.setMinWorkElevation(queryStationAddRpcDTO.getMinWorkElevation());
        visualRequestDTO.setH(Double.valueOf(satelliteRpcDTO.getAltitude()));
        visualRequestDTO.setEirp(Double.valueOf(satelliteRpcDTO.getEirp()));
        visualRequestDTO.setFb(Double.valueOf(satelliteRpcDTO.getXxsl()));
        visualRequestDTO.setCarrier(Double.valueOf(satelliteRpcDTO.getCarrier()));
        visualRequestDTO.setAntenna(Double.valueOf(antennaVal));        //  天线口径

        List<VisualData> visualDatas = visualAlgorithmFacde.visualAlg(visualRequestDTO);
        if (CollectionUtils.isEmpty(visualDatas)) {
            return Boolean.FALSE;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("trbut_data_id", id);
        visualDataMapper.delete(queryWrapper);
        for (VisualData visualData : visualDatas) {
            visualDataMapper.insert(visualData);
            trbutAntennaDataService.asyncUpTrbutAntennaData(visualData);
        }
        return Boolean.TRUE;
    }
}
