package com.base.biz.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.api.client.PointRpcService;
import com.base.api.model.PointRpcDTO;
import com.base.api.model.TargetDemandRpcDTO;
import com.base.api.model.request.PointListRpcReqDTO;
import com.base.biz.config.IdGenerator;
import com.base.biz.mapper.PayloadInfoMapper;
import com.base.biz.mapper.SceneBasisTargetMapper;
import com.base.biz.mapper.SceneTargetPointMapper;
import com.base.biz.mapper.TargetDemandMapper;
import com.base.biz.model.PointDTO;
import com.base.biz.model.dto.request.*;
import com.base.biz.model.dto.response.*;
import com.base.biz.model.entity.*;
import com.base.biz.model.enums.ReconnaissancePurposeEnums;
import com.base.orbit.Exception.AssertException;
import com.base.orbit.domain.AjaxResult;
import com.base.orbit.utils.BizUtils;
import com.base.orbit.utils.DateUtils;
import com.base.orbit.utils.NonEmptyUtils;
import com.plan.api.client.AlgSchemeWindowsPassRpcService;
import com.plan.api.client.StripRpcService;
import com.plan.api.model.AlgSchemeWindowPassRpcDTO;
import com.plan.api.model.StripRpcDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.validation.Payload;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TargetDemandService extends ServiceImpl<TargetDemandMapper, TargetDemand> {

    private static final String DATE_FORMAT = "YYMMdd";

    @Resource
    TargetDemandMapper targetDemandMapper;

    @Resource
    SceneBasisTargetMapper sceneBasisTargetMapper;

    @Resource
    SceneTargetPointMapper sceneTargetPointMapper;

    @Resource
    SatelliteService satelliteService;

    @Resource
    PayloadInfoMapper payloadInfoMapper;

    @Resource
    StripRpcService stripRpcService;

    @Resource
    PointRpcService pointRpcService;

    @Resource
    AlgSchemeWindowsPassRpcService algSchemeWindowsPassRpcService;

    @Resource
    StationService stationService;

    /**
     * 新增
     *
     * @param request
     * @return
     */
    public Boolean addList(List<QueryTargetRelationAddDTO> request) {
        if (CollectionUtils.isEmpty(request)) {
            return false;
        }
        List<SceneBasisTarget> targets = sceneBasisTargetMapper.selectBatchIds(request.stream().map(QueryTargetRelationAddDTO::getId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(targets)) {
            return false;
        }
        List<TargetDemand> relations = getTargetRelations(request, targets, request.stream().map(QueryTargetRelationAddDTO::getParentId).collect(Collectors.toList()));
        targetDemandMapper.batch(relations);
        return true;
    }

    public AjaxResult selAllTargetList(QueryTargetDemandDTO queryTargetDemandDTO) {
        QueryWrapper<TargetDemand> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(!CollectionUtils.isEmpty(queryTargetDemandDTO.getParentIds()), "parent_id", queryTargetDemandDTO.getParentIds());
        queryWrapper.ge(Objects.nonNull(queryTargetDemandDTO.getStartTime()), "start_time", queryTargetDemandDTO.getStartTime());
        queryWrapper.le(Objects.nonNull(queryTargetDemandDTO.getEndTime()), "end_time", queryTargetDemandDTO.getEndTime());
        List<TargetDemand> targetDemands = this.list(queryWrapper);
        List<TargetDemandDTO> targetDemandDTOS = BizUtils.copyEntityToDto(TargetDemandDTO.class, targetDemands);
        //  带上目标点位信息
        List<String> targetIds = targetDemandDTOS.stream().map(TargetDemandDTO::getTargetId).collect(Collectors.toList());
        QueryWrapper<SceneTargetPoint> pointQueryWrapper = new QueryWrapper<>();
        pointQueryWrapper.in("target_id", targetIds);
        List<SceneTargetPoint> sceneTargetPoints = sceneTargetPointMapper.selectList(pointQueryWrapper);
        for (TargetDemandDTO targetDemandDTO : targetDemandDTOS) {
            //  点目标集合
            List<PointDTO> pointDTOList = new ArrayList<>();
            //  根据目标id匹配点目标
            List<SceneTargetPoint> sceneTargetPointList = sceneTargetPoints.stream().filter(sceneTargetPoint ->
                    sceneTargetPoint.getTargetId().equals(targetDemandDTO.getTargetId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(sceneTargetPointList)) {
                for (SceneTargetPoint sceneTargetPoint : sceneTargetPointList) {
                    PointDTO pointDTO = new PointDTO();
                    pointDTO.setLng(sceneTargetPoint.getLongitude().doubleValue());
                    pointDTO.setLat(sceneTargetPoint.getLatitude().doubleValue());
                    pointDTO.setSequence(sceneTargetPoint.getSequence());
                    pointDTOList.add(pointDTO);
                }
            }
            targetDemandDTO.setPointDTOList(pointDTOList);
        }
        return AjaxResult.success(targetDemandDTOS);
    }

    /**
     * 通过需求编号查询条带信息
     *
     * @param queryTargetDemandDTO
     * @return
     */
    public AjaxResult selStripByParentId(QueryTargetDemandDTO queryTargetDemandDTO) {
        List<StripRpcDTO> stripRpcDTOS = getIsSelectStripDTO();
        //  根据条带id查询point点
        PointListRpcReqDTO pointListReqDTO = new PointListRpcReqDTO();
        pointListReqDTO.setPointType("STRIP");
        pointListReqDTO.setParentIds(stripRpcDTOS.stream().map(StripRpcDTO::getId).collect(Collectors.toList()));
        List<PointRpcDTO> pointInfos = pointRpcService.getPointDTOList(pointListReqDTO);

        if (!CollectionUtils.isEmpty(queryTargetDemandDTO.getParentIds())) {
            stripRpcDTOS = stripRpcDTOS.stream().filter(stripRpcDTO -> queryTargetDemandDTO.getParentIds().
                    contains(stripRpcDTO.getParentId())).collect(Collectors.toList());
        }
        //  所有载荷
        List<PayloadInfo> payloadInfos = payloadInfoMapper.selectList(new QueryWrapper<>());
        List<SatelliteObserveDTO> satelliteObserveDTOS = new ArrayList<>();

        //  所有需求
        List<TargetDemand> targetDemands = this.list(new QueryWrapper<>());
        stripRpcDTOS.stream().forEach(stripRpcDTO -> {
            SatelliteObserveDTO satelliteObserveDTO = new SatelliteObserveDTO();
            satelliteObserveDTO.setId(stripRpcDTO.getId());
            satelliteObserveDTO.setSatelliteName(stripRpcDTO.getSatelliteCode());
            satelliteObserveDTO.setParentId(stripRpcDTO.getParentId());
            satelliteObserveDTO.setAccessTime(DateUtils.getMiddleTime(stripRpcDTO.getObservationStartTime(), stripRpcDTO.getObservationEndTime()));
            Optional<PayloadInfo> payloadInfoOptional = payloadInfos.stream().filter(payloadInfo -> payloadInfo.getSatelliteId().equals(stripRpcDTO.getSatelliteId())).findFirst();
            if (payloadInfoOptional.isPresent()) {
                PayloadInfo payloadInfo = payloadInfoOptional.get();
                satelliteObserveDTO.setWorkMode(payloadInfo.getPayloadType());
            }
            Optional<TargetDemand> targetDemandOptional = targetDemands.stream().filter(targetDemand -> targetDemand.getParentId().equals(stripRpcDTO.getParentId())).findFirst();
            if (targetDemandOptional.isPresent()) {
                satelliteObserveDTO.setTargetName(targetDemandOptional.get().getTargetName());
            }
            List<PointRpcDTO> pointRpcDTOS = pointInfos.stream().filter(pointInfo -> pointInfo.getParentId().equals(stripRpcDTO.getId())).collect(Collectors.toList());
            List<com.base.biz.model.dto.PointDTO> pointDTOList = BizUtils.copyEntityToDto(com.base.biz.model.dto.PointDTO.class, pointRpcDTOS);
            pointDTOList.sort(Comparator.comparing(e -> Integer.parseInt(e.getSerial())));
            //  设置每一个条带区域集合
            satelliteObserveDTO.setPointDTOList(pointDTOList);
            satelliteObserveDTOS.add(satelliteObserveDTO);
        });
        return AjaxResult.success(satelliteObserveDTOS);
    }

    /**
     * 根据载荷类型进行卫星分组
     *
     * @return
     */
    public AjaxResult selSatellieByPayload() {
        List<SatelliteInfo> satelliteInfos = satelliteService.list();
        if (!CollectionUtils.isEmpty(satelliteInfos)) {
            Map<String, List<SatelliteInfo>> satelliteInfoByLoadType = satelliteInfos.stream().collect(Collectors.groupingBy(SatelliteInfo::getLoadType));
            return AjaxResult.success(satelliteInfoByLoadType);
        }
        return AjaxResult.error("查询卫星信息失败！");
    }

    /**
     * 根据载荷类型进行卫星分组
     *
     * @return
     */
    public AjaxResult selStationTaskInfo() {
        List<StationInfo> stationInfos = stationService.list();
        if (!CollectionUtils.isEmpty(stationInfos)) {
            Map<String, List<StationInfo>> stationByType = stationInfos.stream().collect(Collectors.groupingBy(StationInfo::getResourceType));
            return AjaxResult.success(stationByType);
        }
        return AjaxResult.error("查询地面站信息失败！");
    }


    /**
     * 查询卫星任务信息
     *
     * @return
     */
    public AjaxResult selSatellieTaskInfo(SatelliteTaskReqDTO satelliteTaskReqDTO) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(satelliteTaskReqDTO.getParentId())) {
            return AjaxResult.error("任务编号不能为空!");
        }
        List<SatelliteTaskInfoDTO> satelliteTaskInfoDTOS = new ArrayList<>();
        SatelliteTaskInfoResDTO satelliteTaskInfoResDTO = new SatelliteTaskInfoResDTO();
        //  1.根据任务id匹配所有需求,一个任务可能包含多个需求，parentId前三段相同的属于同一个任务
        QueryWrapper<TargetDemand> queryWrapper = new QueryWrapper();
        queryWrapper.like("parent_id", satelliteTaskReqDTO.getParentId());
        List<TargetDemand> targetDemands = targetDemandMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(targetDemands)) {
            return AjaxResult.error("根据任务【" + satelliteTaskReqDTO.getParentId() + "】没有找到对应的需求列表");
        }
        //  2.获取需求中最早开始时间和最晚结束时间
        Date startTimeMin = Collections.min(targetDemands.stream().map(TargetDemand::getStartTime).collect(Collectors.toList()));
        Date endTimeMax = Collections.max(targetDemands.stream().map(TargetDemand::getEndTime).collect(Collectors.toList()));
        List<StripRpcDTO> isSelectStripDTOs = getIsSelectStripDTO();
        if (CollectionUtils.isEmpty(isSelectStripDTOs)) {
            return AjaxResult.error("不存在已挑选的条带！");
        }
        List<String> satelliteCodes = satelliteTaskReqDTO.getSatelliteCodes();
        //  3.挑选出确认的条带后，在根据卫星过滤
        if (!CollectionUtils.isEmpty(satelliteCodes)) {
            isSelectStripDTOs = isSelectStripDTOs.stream().filter(isSelectStrip -> satelliteCodes.contains(isSelectStrip.getSatelliteCode())).collect(Collectors.toList());
        }
        //  4.根据任务id进行模糊匹配
        isSelectStripDTOs = isSelectStripDTOs.stream().filter(isSelectStripDTO -> isSelectStripDTO.getParentId().contains(satelliteTaskReqDTO.getParentId())).collect(Collectors.toList());
        //  5.获取挑选条带中的窗口id，根据窗口id匹配数传和测控弧段
        for (StripRpcDTO stripRpcDTO : isSelectStripDTOs) {
            String windowId = stripRpcDTO.getWindowId();
            //  6.取测控\数传弧段
            List<AlgSchemeWindowPassRpcDTO> algSchemeWindowPassRpcDTOS = algSchemeWindowsPassRpcService.getWindowsPass(Arrays.asList(windowId));
            //  测控
//            AlgSchemeWindowPassRpcDTO algSchemeWindowPassCk = algSchemeWindowPassRpcDTOS.stream().filter(algSchemeWindowPassRpcDTO -> algSchemeWindowPassRpcDTO.getPassType().equals(1)).collect(Collectors.toList()).get(0);
            AlgSchemeWindowPassRpcDTO algSchemeWindowPassSc = algSchemeWindowPassRpcDTOS.stream().filter(algSchemeWindowPassRpcDTO -> algSchemeWindowPassRpcDTO.getPassType().equals(2)).collect(Collectors.toList()).get(0);
            SatelliteTaskInfoDTO satelliteTaskInfoDTO = new SatelliteTaskInfoDTO();
            satelliteTaskInfoDTO.setStartTime(algSchemeWindowPassSc.getStartTime());
            satelliteTaskInfoDTO.setEndTime(algSchemeWindowPassSc.getEndTime());
            satelliteTaskInfoDTO.setSatelliteCode(stripRpcDTO.getSatelliteCode());
            satelliteTaskInfoDTO.setTaskStatus(1);
            satelliteTaskInfoDTO.setType(2);
            //  7.根据parentId需求id获取目标信息
            String parentId = stripRpcDTO.getParentId();
            Optional<TargetDemand> targetDemandOptional = targetDemands.stream().filter(targetDemand -> targetDemand.getParentId().equals(parentId)).findFirst();
            if (targetDemandOptional.isPresent()) {
                satelliteTaskInfoDTO.setTargetName(targetDemandOptional.get().getTargetName());
            }
            satelliteTaskInfoDTOS.add(satelliteTaskInfoDTO);
        }
        satelliteTaskInfoResDTO.setTaskStartTime(startTimeMin);
        satelliteTaskInfoResDTO.setTaskEndTime(endTimeMax);
        satelliteTaskInfoResDTO.setSatelliteTaskInfoDTOList(satelliteTaskInfoDTOS);
        return AjaxResult.success(satelliteTaskInfoResDTO);
    }

    /**
     * 获取已经挑选的条带
     *
     * @return
     */
    public List<StripRpcDTO> getIsSelectStripDTO() {
        List<StripRpcDTO> stripInfo = stripRpcService.getStripInfo(new ArrayList<>());
        // 已经被选中的条带
        List<StripRpcDTO> stripRpcDTOS = stripInfo.stream().filter(stripRpcDTO -> stripRpcDTO.getIsSelected().equals(2)).collect(Collectors.toList());
        return stripRpcDTOS;
    }

    public List<TargetDemandRpcDTO> selTargetDemandByParentId(Set<String> parents) {
        QueryWrapper<TargetDemand> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("parent_id", parents);
        List<TargetDemand> targetDemands = this.list(queryWrapper);
        List<TargetDemandRpcDTO> targetDemandRpcDTOS = BizUtils.copyEntityToDto(TargetDemandRpcDTO.class, targetDemands);
        //  带上目标点位信息
        List<String> targetIds = targetDemandRpcDTOS.stream().map(TargetDemandRpcDTO::getTargetId).collect(Collectors.toList());
        QueryWrapper<SceneTargetPoint> pointQueryWrapper = new QueryWrapper<>();
        pointQueryWrapper.in("target_id", targetIds);
        List<SceneTargetPoint> sceneTargetPoints = sceneTargetPointMapper.selectList(pointQueryWrapper);

        for (TargetDemandRpcDTO targetDemandRpcDTO : targetDemandRpcDTOS) {
            //  点目标集合
            List<PointRpcDTO> pointDTOList = new ArrayList<>();
            //  根据目标id匹配点目标
            List<SceneTargetPoint> sceneTargetPointList = sceneTargetPoints.stream().filter(sceneTargetPoint ->
                    sceneTargetPoint.getTargetId().equals(targetDemandRpcDTO.getTargetId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(sceneTargetPointList)) {
                for (SceneTargetPoint sceneTargetPoint : sceneTargetPointList) {
                    PointRpcDTO pointRpcDTO = new PointRpcDTO();
                    pointRpcDTO.setLongitude(sceneTargetPoint.getLongitude().toString());
                    pointRpcDTO.setLatitude(sceneTargetPoint.getLatitude().toString());
                    pointRpcDTO.setSerial(sceneTargetPoint.getSequence().toString());
                    pointDTOList.add(pointRpcDTO);
                }
            }
            targetDemandRpcDTO.setPointDTOList(pointDTOList);
        }
        return targetDemandRpcDTOS;
    }


    public void update(QueryTargetRelationUpdateDTO queryTargetRelationUpdateDTO) {
        TargetDemand targetDemand = targetDemandMapper.selectById(queryTargetRelationUpdateDTO.getId());
        if (targetDemand == null) {
            return;
        }
        targetDemand.setPriority(queryTargetRelationUpdateDTO.getPriority());
        targetDemand.setObservationPurpose(queryTargetRelationUpdateDTO.getObservationPurpose());
        targetDemand.setStartTime(queryTargetRelationUpdateDTO.getStartTime());
        targetDemand.setEndTime(queryTargetRelationUpdateDTO.getEndTime());
        targetDemand.setRate(queryTargetRelationUpdateDTO.getRate());
        targetDemand.setInvestigativeMeans(queryTargetRelationUpdateDTO.getInvestigativeMeans());
        //  界面不选择侦察手段，则默认传0。根据观测目的快速选取载荷，根据载荷类型匹配相对应的卫星
        if (queryTargetRelationUpdateDTO.getInvestigativeMeans().equals("0")) {
            String satelliteIds = getSatelliteIds(queryTargetRelationUpdateDTO.getObservationPurpose());
            targetDemand.setSatelliteSelected(satelliteIds);
        } else {

            targetDemand.setSatelliteSelected(JSONArray.parseArray(JSON.toJSONString(queryTargetRelationUpdateDTO.getSatelliteSelected())).toJSONString());
        }

        targetDemandMapper.updateById(targetDemand);
    }

    private String getsatelliteIdAndPayloadDTOStr(String satelliteIds) {
        if (StringUtils.isEmpty(satelliteIds)) {
            return null;
        }
        List<PayloadInfo> list = payloadInfoMapper.selectByStaelliteIdList(Arrays.asList(satelliteIds.split(",")));
        if (!CollectionUtils.isEmpty(list)) {
            List<SatelliteIdAndPayloadDTO> satelliteIdAndPayloadDTOS = new ArrayList<>();
            for (PayloadInfo payloadInfo : list) {
                SatelliteIdAndPayloadDTO satelliteIdAndPayloadDTO = new SatelliteIdAndPayloadDTO();
                satelliteIdAndPayloadDTO.setSatelliteId(payloadInfo.getSatelliteId());
                satelliteIdAndPayloadDTO.setType(payloadInfo.getType());
                satelliteIdAndPayloadDTOS.add(satelliteIdAndPayloadDTO);
            }
            return JSONArray.toJSONString(satelliteIdAndPayloadDTOS);
        } else {
            return null;
        }
    }


    public void updateByParentId(QueryBatchUpdateRelationDTO queryBatchUpdateRelationDTO) {
        if (StringUtils.isEmpty(queryBatchUpdateRelationDTO.getParentId()) || StringUtils.isEmpty(queryBatchUpdateRelationDTO.getRelationId()) || queryBatchUpdateRelationDTO.getType() == null) {
            throw new AssertException(202, "参数缺失");
        }
        TargetDemand targetDemand = targetDemandMapper.selectById(queryBatchUpdateRelationDTO.getRelationId());
        if (queryBatchUpdateRelationDTO.getType() == 1) {
            targetDemandMapper.updateTimeByParentId(queryBatchUpdateRelationDTO.getParentId(), targetDemand.getStartTime(), targetDemand.getEndTime());
        } else {
            // 根据枚举查询卫星
            if (!targetDemand.getInvestigativeMeans().equals("0")) {
//                targetDemandMapper.updateInvestigativeMeansByParentId(queryBatchUpdateRelationDTO.getParentId(), targetDemand.getInvestigativeMeans(), getsatelliteIdAndPayloadDTOStr(targetDemand.getSatelliteSelected()));
                targetDemandMapper.updateInvestigativeMeansByParentId(queryBatchUpdateRelationDTO.getParentId(), targetDemand.getInvestigativeMeans(), targetDemand.getSatelliteSelected());
            }
        }
    }


    public void deleteByIds(String ids) {
        Set<String> id = new HashSet<>(Arrays.asList(ids.split(",")));
        targetDemandMapper.deleteBatchIds(id);
    }


    public void deleteByParentId(String parentId) {
        targetDemandMapper.deleteByParentId(parentId);
    }


    public synchronized String getParentId() {
        String res = null;
        String parentId = targetDemandMapper.getParentId();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
        String date = simpleDateFormat.format(new Date());
        if (parentId == null) {
            res = date + "_XQCH" + "_10000";
        } else {
            String[] arr = parentId.split("_");
            int count = Integer.parseInt(arr[2]) + 1;
            res = date + "_XQCH_" + count;
        }
        return res;
    }

    /**
     * 根据parentId批量查询需求
     *
     * @param parents
     * @return
     */
    public List<TargetDemandDTO> selBatchIds(Set<String> parents) {
        List<TargetDemand> list = targetDemandMapper.selectTargetRelationDTOListByParentIds(parents);
        return castToRelationDTO(list, null);
    }


    public List<TargetDemandDTO> getTargetRelationDTOList(QueryTargetRelationListDTO request) {
        List<TargetDemand> list = null;
        if (request == null) {
            list = targetDemandMapper.selectList(null);
        } else {
            list = targetDemandMapper.selectTargetRelationDTOList(request);
        }
        //查询目标对应的GPS点
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<SceneTargetPoint> points = sceneTargetPointMapper.getPointListByTargetIds(list.stream().map(TargetDemand::getTargetId).collect(Collectors.toSet()));
        return castToRelationDTO(list, points);
    }

    /**
     * 对象转换
     *
     * @param list
     * @return
     */
    public List<TargetDemandDTO> castToRelationDTO(List<TargetDemand> list, List<SceneTargetPoint> points) {
        List<TargetDemandDTO> res = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        for (TargetDemand TargetRelation : list) {
            TargetDemandDTO targetDemandDTO = new TargetDemandDTO();
            targetDemandDTO.setId(TargetRelation.getId());
            targetDemandDTO.setTargetCode(TargetRelation.getTargetCode());
            targetDemandDTO.setTargetName(TargetRelation.getTargetName());
            targetDemandDTO.setObservationPurpose(TargetRelation.getObservationPurpose());
            targetDemandDTO.setStatus(TargetRelation.getStatus());
            targetDemandDTO.setType(TargetRelation.getType());
            targetDemandDTO.setSatelliteSelected(TargetRelation.getSatelliteSelected());
            targetDemandDTO.setStartTime(TargetRelation.getStartTime());
            targetDemandDTO.setEndTime(TargetRelation.getEndTime());
            targetDemandDTO.setPriority(TargetRelation.getPriority());
            targetDemandDTO.setParentId(TargetRelation.getParentId());
            targetDemandDTO.setRate(TargetRelation.getRate());
            targetDemandDTO.setInvestigativeMeans(TargetRelation.getInvestigativeMeans());

            if (CollectionUtils.isEmpty(points)) {
                res.add(targetDemandDTO);
                continue;
            }
            //设置点GPS
            List<SceneTargetPoint> SceneTargetPointList = points.stream().filter(k -> k.getTargetId().equals(TargetRelation.getTargetId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(SceneTargetPointList)) {
                res.add(targetDemandDTO);
                continue;
            }
            if (!CollectionUtils.isEmpty(SceneTargetPointList)) {
                List<PointDTO> pointDTOList = new ArrayList<>();
                for (SceneTargetPoint SceneTargetPoint : SceneTargetPointList) {
                    PointDTO pointDTO = new PointDTO();
                    pointDTO.setPointId(SceneTargetPoint.getId());
                    pointDTO.setSequence(SceneTargetPoint.getSequence());
                    pointDTO.setLat(SceneTargetPoint.getLatitude().doubleValue());
                    pointDTO.setLng(SceneTargetPoint.getLongitude().doubleValue());
                    pointDTOList.add(pointDTO);
                    targetDemandDTO.setPointDTOList(pointDTOList);
                }
            }
            res.add(targetDemandDTO);
        }
        return res;
    }

    /**
     * @param list
     * @return
     */
    public List<TargetDemand> castTargetDTO(List<TargetDemandDTO> list) {
        List<TargetDemand> relations = new ArrayList<>();
        for (TargetDemandDTO relationDTO : list) {
            TargetDemand targetRelation = new TargetDemand();
            //  进行对象拷贝
            BeanUtils.copyProperties(relationDTO, targetRelation);
            targetRelation.setStartTime(relationDTO.getStartTime());
            targetRelation.setEndTime(relationDTO.getEndTime());
            //  将需求状态改为已提交
            targetRelation.setStatus(1);
            relations.add(targetRelation);
        }
        return relations;
    }

    /**
     * 批量修改需求状态信息
     *
     * @param list
     */
    public int batchStatus(List<TargetDemandDTO> list) {
        try {
            List<TargetDemand> res = new ArrayList<>();
            for (TargetDemandDTO targetDemandDTO : list) {
                TargetDemand TargetDemand = new TargetDemand();
                BeanUtils.copyProperties(targetDemandDTO, TargetDemand);
                TargetDemand.setStatus(1);
                res.add(TargetDemand);
            }
            int val = targetDemandMapper.batchUpdateStatus(res);
            return val;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("^^^^^^^^^^^^batch update status is error msg is {}", e.getMessage());
        }
        return 0;
    }


    /**
     * 新增，目标库，新增关系库，新增点集合
     *
     * @param queryTargetRelationPointAddDTOList 新增
     */
    public void addTargetRelationPoint(List<QueryTargetRelationPointAddDTO> queryTargetRelationPointAddDTOList) {

        //新增目标,和点集合
        List<QueryTargetRelationAddDTO> relationAddDTOS = createTarget(queryTargetRelationPointAddDTOList);

        //新增需求
        addList(relationAddDTOS);
    }


    /**
     * 构建点
     *
     * @param queryTargetRelationPointAddDTO 点基本信息
     * @param targetId                       目标ID
     * @return 点集合
     */
    private List<QueryTargetPointBatchDTO> createSceneTargetPoints(QueryTargetRelationPointAddDTO queryTargetRelationPointAddDTO, String targetId) {
        List<QueryTargetPointBatchDTO> SceneTargetPointList = new ArrayList<>();
        List<PointDTO> pointDTOList = queryTargetRelationPointAddDTO.getPointDTOList();
        NonEmptyUtils.objectNotNull(pointDTOList);
        for (PointDTO pointDTO : pointDTOList) {
            QueryTargetPointBatchDTO SceneTargetPoint = new QueryTargetPointBatchDTO();
            SceneTargetPoint.setId(UUID.randomUUID().toString());
            SceneTargetPoint.setCreatedDate(new Date());
            SceneTargetPoint.setLatitude(BigDecimal.valueOf(pointDTO.getLat()));
            SceneTargetPoint.setSource(1);
            SceneTargetPoint.setLongitude(BigDecimal.valueOf(pointDTO.getLng()));
            SceneTargetPoint.setTargetId(targetId);
            SceneTargetPoint.setSequence(pointDTO.getSequence());
            SceneTargetPointList.add(SceneTargetPoint);
        }
        return SceneTargetPointList;
    }

    /**
     * 创建目标
     *
     * @param queryTargetRelationPointAddDTOList 目标基本信息
     * @return 目标
     */
    private List<QueryTargetRelationAddDTO> createTarget(List<QueryTargetRelationPointAddDTO> queryTargetRelationPointAddDTOList) {
        List<SceneBasisTarget> SceneBasisTargetList = new ArrayList<>();
        List<QueryTargetRelationAddDTO> relationAddDTOS = new ArrayList<>();
        //导入，新增的parentId都是一样的，所以只取第一个
        List<QueryTargetPointBatchDTO> points = new ArrayList<>();
        for (QueryTargetRelationPointAddDTO queryTargetRelationPointAddDTO : queryTargetRelationPointAddDTOList) {
            SceneBasisTarget SceneBasisTarget = new SceneBasisTarget();
            SceneBasisTarget.setTargetName(queryTargetRelationPointAddDTO.getTargetName());
            SceneBasisTarget.setTargetCode("LT" + IdGenerator.getId());
            SceneBasisTarget.setTargetType(0);
            SceneBasisTarget.setId(UUID.randomUUID().toString());
            SceneBasisTarget.setPointCount(queryTargetRelationPointAddDTO.getPointDTOList().size());
            SceneBasisTarget.setCountryName(queryTargetRelationPointAddDTO.getCountryName());
            SceneBasisTarget.setTargetLevel(queryTargetRelationPointAddDTO.getTargetLevel());
            SceneBasisTarget.setPointDirection(queryTargetRelationPointAddDTO.getPointDirection());
            SceneBasisTarget.setSource(1);
            SceneBasisTarget.setType(queryTargetRelationPointAddDTO.getType());
            SceneBasisTarget.setTargetState(0);
            SceneBasisTarget.setCreatedDate(new Date());
            SceneBasisTarget.setPriority(queryTargetRelationPointAddDTO.getPriority());
            List<QueryTargetPointBatchDTO> list = createSceneTargetPoints(queryTargetRelationPointAddDTO, SceneBasisTarget.getId());
            points.addAll(list);
            SceneBasisTargetList.add(SceneBasisTarget);

            //新增关系库
            QueryTargetRelationAddDTO queryTargetRelationAddDTO = new QueryTargetRelationAddDTO();
            queryTargetRelationAddDTO.setParentId(queryTargetRelationPointAddDTO.getParentId());
            queryTargetRelationAddDTO.setId(SceneBasisTarget.getId());
            queryTargetRelationAddDTO.setStartTime(queryTargetRelationPointAddDTO.getStartTime());
            queryTargetRelationAddDTO.setType(queryTargetRelationAddDTO.getType());
//            queryTargetRelationAddDTO.setEndTime(new Date());
            queryTargetRelationAddDTO.setEndTime(queryTargetRelationPointAddDTO.getEndTime());
            relationAddDTOS.add(queryTargetRelationAddDTO);
        }
        //新增目标点集合
        sceneTargetPointMapper.batch(points);
        //批量添加
        sceneBasisTargetMapper.batch(SceneBasisTargetList);
        return relationAddDTOS;
    }

    private List<TargetDemand> getTargetRelations(List<QueryTargetRelationAddDTO> request, List<SceneBasisTarget> targets, List<String> parentIds) {
        List<TargetDemand> relations = new ArrayList<>();

        for (SceneBasisTarget sceneBasisTarget : targets) {
            TargetDemand relation = new TargetDemand();
            BeanUtils.copyProperties(sceneBasisTarget, relation);
            relation.setStationSelected(null);
            relation.setId(UUID.randomUUID().toString());
            relation.setTargetId(sceneBasisTarget.getId());
            relation.setPriority(999);
            if (relation.getObservationPurpose() == null) {
                relation.setObservationPurpose(1);
            }
            relation.setInvestigativeMeans("0");
            relation.setCreatedDate(new Date());
            relation.setSatelliteSelected(getSatelliteIds(relation.getObservationPurpose()));
            relation.setStatus(0);
            relation.setTargetState(0);
            Optional<QueryTargetRelationAddDTO> optionalQueryTargetRelationAddDTO = request.stream().filter(e -> e.getId().equals(sceneBasisTarget.getId())).findFirst();
            if (optionalQueryTargetRelationAddDTO.isPresent()) {
                relation.setParentId(optionalQueryTargetRelationAddDTO.get().getParentId());
                if (optionalQueryTargetRelationAddDTO.get().getStartTime() != null) {
                    relation.setStartTime(optionalQueryTargetRelationAddDTO.get().getStartTime());
                } else {
                    relation.setStartTime(new Date());
                }
                if (optionalQueryTargetRelationAddDTO.get().getEndTime() != null) {
                    relation.setEndTime(optionalQueryTargetRelationAddDTO.get().getEndTime());
                } else {
                    relation.setEndTime(new Date(relation.getStartTime().getTime() + 360000 * 60));
                }

            }

            relations.add(relation);
        }

        return relations;
    }


    private String getSatelliteIds(Integer key) {
        ReconnaissancePurposeEnums reconnaissancePurposeEnums = ReconnaissancePurposeEnums.getReconnaissancePurposeEnums(key);
        if (reconnaissancePurposeEnums == null) {
            return null;
        }
        String payload = reconnaissancePurposeEnums.payload;

        List<SatellitePayloadDTO> list = satelliteService.getSatellitePayloadDTOList(payload);
        if (!CollectionUtils.isEmpty(list)) {
            //根据载荷类型查卫星
            List<SatellitePayloadDTO> satellitePayloadDTOList = list.stream().filter(e -> !StringUtils.isEmpty(e.getId()))
                    .collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(SatellitePayloadDTO::getId)))
                            , ArrayList::new)
                    );
            if (CollectionUtils.isEmpty(satellitePayloadDTOList)) {
                return null;
            }
            List<SatelliteIdAndPayloadDTO> satelliteIdList = new ArrayList<>();
            for (SatellitePayloadDTO satellitePayloadDTO : satellitePayloadDTOList) {
                SatelliteIdAndPayloadDTO satelliteIdAndPayloadDTO = new SatelliteIdAndPayloadDTO();
                satelliteIdAndPayloadDTO.setSatelliteId(satellitePayloadDTO.getId());
                satelliteIdAndPayloadDTO.setType(satellitePayloadDTO.getPayloadType());
                satelliteIdList.add(satelliteIdAndPayloadDTO);
            }
            return JSONArray.toJSONString(satelliteIdList);
        }
        return "";
    }
}
