package com.base.plan.mq.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.api.client.FzTaskRpcService;
import com.base.api.model.FzTaskRpcDTO;
import com.base.api.model.request.FzTaskInfoRpcReqDTO;
import com.base.orbit.mq.model.BaseHeadMqDTO;
import com.base.orbit.mq.model.enums.MessageTypeEnums;
import com.base.orbit.mq.topics.TopicConst;
import com.base.orbit.utils.DateUtils;
import com.base.orbit.utils.IdGenerator;
import com.base.plan.model.dto.FzSystemIndicatorDTO;
import com.base.plan.model.dto.FzTargetIndicatorDTO;
import com.base.plan.model.dto.PlanDTO;
import com.base.plan.mq.model.*;
import com.base.plan.utils.FileUploadUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.plan.api.model.PlanIndicatorStepDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class PlanMqService {
//    @Resource
//    StepMqProducer stepMqProducer;

    @Resource
    FzTaskRpcService fzTaskRpcService;

    public static List<PlanIndicatorStepDTO> stepInfo = new ArrayList<>();

    @Value("${outputFile.planReportPath}")
    private String planReportPath;

    @Value("${outputFile.indicatorIssuancePath}")
    private String indicatorIssuancePath;

    private final static String PRODUCT_ID_INDICATOR_ENG = "indicatorIssuance";

    private final static String PRODUCT_ID_PLAN_ENG = "planReport";

    private final static String PRODUCT_ID_INDICATOR_CHN = "指标下发";

    private final static String PRODUCT_ID_PLAN_CHN = "计划上报";

    private final static String PRODUCT_FORMAT = "json";

    @Async
    public void sendTask(List<PlanDTO> planDTOS) {
        //  消息头
        FileSavePathMqNoticeDTO fileSavePathMqNoticeDTO = new FileSavePathMqNoticeDTO();
        BaseHeadMqDTO messageHeader = new BaseHeadMqDTO();
        String createTime = DateUtils.dateTimeNow();
//        messageHeader.setCreationTime(createTime);
//        messageHeader.setOriginator("YKSC");
//        messageHeader.setRecipient("JCPT");
        messageHeader.setMessageType(MessageTypeEnums.TASKRESULT.toString());
//        messageHeader.setMessageId(messageHeader.getMessageType() + "_" + messageHeader.getOriginator() + "_" + messageHeader.getCreationTime());
        fileSavePathMqNoticeDTO.setCreationTime(createTime);
        fileSavePathMqNoticeDTO.setOriginator("YKSC");
        fileSavePathMqNoticeDTO.setRecipient("JCPT");
        fileSavePathMqNoticeDTO.setMessageId(messageHeader.getMessageType() + "_YKSC"  + "_" + createTime);
        PlanTaskBodyMqResultDTO messageBody = new PlanTaskBodyMqResultDTO();

        Optional<PlanDTO> optionalPlanDTO = planDTOS.stream().findFirst();
        if (optionalPlanDTO.isPresent()) {
            PlanDTO planDTO = optionalPlanDTO.get();
            messageBody.setTaskId(planDTO.getTaskId());
            messageBody.setDataClassify("YKCS-WXTCRWCS");
            messageBody.setSatID(planDTO.getSatelliteId());
            messageBody.setTaskNum("1");

            //  wx任务集合
            List<PlanTaskBodySatelliteMqResultDTO> wxrwjh = new ArrayList<>();
            PlanTaskBodySatelliteMqResultDTO planTaskBodySatelliteMqResultDTO = new PlanTaskBodySatelliteMqResultDTO();
            planTaskBodySatelliteMqResultDTO.setSoutSerialNum(IdGenerator.getStrId());
            planTaskBodySatelliteMqResultDTO.setSoutTaskID(planDTO.getTaskId());
            planTaskBodySatelliteMqResultDTO.setAltitude(planDTO.getAltitude());
            planTaskBodySatelliteMqResultDTO.setPass(planDTO.getOrbitNum());
            //  访问时刻，条带的中间时刻
            Date accessTime = DateUtils.getMiddleTime(planDTO.getObservationStartTime(), planDTO.getObservationEndTime());
            planTaskBodySatelliteMqResultDTO.setAccessTime(DateUtils.dateTime(accessTime));
            wxrwjh.add(planTaskBodySatelliteMqResultDTO);

            //  数传站集合
            PlanTaskBodyStationMqResultDTO sczgs = new PlanTaskBodyStationMqResultDTO();
            sczgs.setSoutTaskID(planDTO.getTaskId());
            sczgs.setReceiveStationNum("1");
            List<PlanTaskBodyStationReceiveInfoDTO> receiveInfo = new ArrayList<>();
            PlanTaskBodyStationReceiveInfoDTO planTaskBodyStationReceiveInfoDTO = new PlanTaskBodyStationReceiveInfoDTO();

            planTaskBodyStationReceiveInfoDTO.setReceiveSerialNum(IdGenerator.getStrId());
            planTaskBodyStationReceiveInfoDTO.setReceiveTaskID(planDTO.getTaskId());
            planTaskBodyStationReceiveInfoDTO.setReceiveStationID(planDTO.getDataPassStationCode());
            planTaskBodyStationReceiveInfoDTO.setReceiveStartTime(DateUtils.dateTime(planDTO.getDataPassStartTime()));
            planTaskBodyStationReceiveInfoDTO.setReceiveEndTime(DateUtils.dateTime(planDTO.getDataPassEndTime()));
            receiveInfo.add(planTaskBodyStationReceiveInfoDTO);

            messageBody.setWxrwjh(wxrwjh);
            messageBody.setSczgs(sczgs);

            //将消息体生成JSON文件并输出到指定位置
            String reqId = planDTO.getReqId();
            String filename = planReportPath + reqId + "/planReportResult.json";
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] bytes = new byte[0];
            try {
                bytes = objectMapper.writeValueAsBytes(messageBody);
            } catch (JsonProcessingException e) {
                log.info("转化为json字节数组异常,原因为:{}", e.getMessage());
            }
            //输出文件流到指定位置
            FileUploadUtil.outputToFile(bytes, filename);
            //构建kafka消息体中的result
            String fileOutputDTOStr = buildResult(filename, PRODUCT_ID_PLAN_CHN, PRODUCT_ID_PLAN_ENG);
            //  发送
//            fileSavePathMqNoticeDTO.setMessageHeader(messageHeader);
            fileSavePathMqNoticeDTO.setBody(fileOutputDTOStr);
            //构建category
            Category category = new Category();
            List<String> reqIds = new ArrayList<>();
            reqIds.add(optionalPlanDTO.get().getReqId());
            List<FzTaskRpcDTO> fzTaskRpcDTOS = getFzTaskRpcDTOS(reqIds);
            category.setTaskId(fzTaskRpcDTOS.get(0).getTaskId());
            category.setDataClassify("YKCS-JHSB");
            fileSavePathMqNoticeDTO.setCategory(category);
//            stepMqProducer.push(TopicConst.WXPTFZ_XNZB, "data", fileSavePathMqNoticeDTO);
        }
    }


    /**
     * 构建kafka消息体中的result
     *
     * @param filename
     * @return
     */
    private String buildResult(String filename, String productIdCHN, String productIdENG) {
        List<FileOutputDTO> fileOutputDTOS = new ArrayList<>();
        FileOutputDTO fileOutputDTO = new FileOutputDTO();
        fileOutputDTO.setFilePath(filename);
        fileOutputDTO.setProductIdCHN(productIdCHN);
        fileOutputDTO.setProductIdENG(productIdENG);
        fileOutputDTO.setFileFormat(PRODUCT_FORMAT);
        fileOutputDTO.setFileDate(DateUtils.dateTimeNow());
        fileOutputDTOS.add(fileOutputDTO);
        Map<String, List<FileOutputDTO>> fileInfoMap = new HashMap<>();
        fileInfoMap.put("fileInfo",fileOutputDTOS);
        String fileInfoStr = JSON.toJSONString(fileInfoMap);
        return fileInfoStr;
    }

    /**
     * 指标下发
     *
     * @param fzSystemIndicatorDTO
     */
    @Async
    public void sendIndicator(FzSystemIndicatorDTO fzSystemIndicatorDTO) {
        //  消息头
        FileSavePathMqNoticeDTO fileSavePathMqNoticeDTO = new FileSavePathMqNoticeDTO();
        BaseHeadMqDTO messageHeader = new BaseHeadMqDTO();
        String createTime = DateUtils.dateTimeNow();
//        messageHeader.setCreationTime(createTime);
//        messageHeader.setOriginator("JCPT");
//        messageHeader.setRecipient("YKSC");
        messageHeader.setMessageType(MessageTypeEnums.TASKRESULT.toString());
//        messageHeader.setMessageId(messageHeader.getMessageType() + "_" + messageHeader.getOriginator() + "_" + messageHeader.getCreationTime());
        fileSavePathMqNoticeDTO.setCreationTime(createTime);
        fileSavePathMqNoticeDTO.setOriginator("YKSC");
        fileSavePathMqNoticeDTO.setRecipient("JCPT");
        fileSavePathMqNoticeDTO.setMessageId(messageHeader.getMessageType() + "_YKSC" + "_" + createTime);

//        List<PlanBodyChMqResultDTO> planBodyChMqResultDTOS = new ArrayList<>();
//        fzSystemIndicatorDTO.getFzTargetIndicatorDTOList().forEach(fzTargetIndicatorDTO -> {
//            PlanBodyChMqResultDTO planBodyChMqResultDTO = new PlanBodyChMqResultDTO();
//            planBodyChMqResultDTO.setTaskId(fzTargetIndicatorDTO.getReqId());
//            planBodyChMqResultDTO.setSatId(fzTargetIndicatorDTO.getSatelliteCode());
//            planBodyChMqResultDTO.setDataClassify("YKCS-ZBXF");
//            planBodyChMqResultDTO.setTargetId(fzTargetIndicatorDTO.getTargetCode());
//            planBodyChMqResultDTO.setCoverArea(fzTargetIndicatorDTO.getCoverageInfo());
//            planBodyChMqResultDTO.setCoverCount(fzTargetIndicatorDTO.getCoverageAresNumberInfo());
//            planBodyChMqResultDTO.setAreaCovTime(fzTargetIndicatorDTO.getCoverageAresTimeInfo());
//            planBodyChMqResultDTO.setBoStorageResUtilization(fzSystemIndicatorDTO.getSatelliteStorageUtilization());
//            planBodyChMqResultDTO.setDigitalResUtilization(fzSystemIndicatorDTO.getDataPassResourceUtilization());
//            planBodyChMqResultDTOS.add(planBodyChMqResultDTO);
//        });
//        PlanBodyMqResultDTO planBodyMqResultDTO = new PlanBodyMqResultDTO();
//        planBodyMqResultDTO.setTaskCodes(planBodyChMqResultDTOS);

        FzTargetIndicatorDTO fzTargetIndicatorDTO = fzSystemIndicatorDTO.getFzTargetIndicatorDTOList().get(0);
        PlanBodyChMqResultDTO planBodyChMqResultDTO = new PlanBodyChMqResultDTO();
            planBodyChMqResultDTO.setTaskId(fzTargetIndicatorDTO.getReqId());
            planBodyChMqResultDTO.setSatId(fzTargetIndicatorDTO.getSatelliteCode());
            planBodyChMqResultDTO.setDataClassify("YKCS-ZBXF");
            planBodyChMqResultDTO.setTargetId(fzTargetIndicatorDTO.getTargetCode());
            planBodyChMqResultDTO.setCoverArea(fzTargetIndicatorDTO.getCoverageInfo());
            planBodyChMqResultDTO.setCoverCount(fzTargetIndicatorDTO.getCoverageAresNumberInfo());
            planBodyChMqResultDTO.setAreaCovTime(fzTargetIndicatorDTO.getCoverageAresTimeInfo());
            planBodyChMqResultDTO.setBoStorageResUtilization(fzSystemIndicatorDTO.getSatelliteStorageUtilization());
            planBodyChMqResultDTO.setDigitalResUtilization(fzSystemIndicatorDTO.getDataPassResourceUtilization());

        //将消息体生成JSON文件并输出到指定位置
        String reqId = fzSystemIndicatorDTO.getFzTargetIndicatorDTOList().get(0).getReqId();
        String filename = indicatorIssuancePath + reqId + "/indicatorIssuanceResult.json";
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(planBodyChMqResultDTO);
        } catch (JsonProcessingException e) {
            log.info("转化为json字节数组异常,原因为:{}", e.getMessage());
        }
        //输出文件流到指定位置
        FileUploadUtil.outputToFile(bytes, filename);
        //构建kafka消息体
        String fileOutputDTOStr = buildResult(filename, PRODUCT_ID_INDICATOR_CHN, PRODUCT_ID_INDICATOR_ENG);
//        fileSavePathMqNoticeDTO.setMessageHeader(messageHeader);
        fileSavePathMqNoticeDTO.setBody(fileOutputDTOStr);
        //构建category
        Category category = new Category();
        List<String> reqIds = new ArrayList<>();
        reqIds.add(fzSystemIndicatorDTO.getFzTargetIndicatorDTOList().get(0).getReqId());
        List<FzTaskRpcDTO> fzTaskDTOList = getFzTaskRpcDTOS(reqIds);
        category.setTaskId(fzTaskDTOList.get(0).getTaskId());
        category.setDataClassify("YKCS-ZBXF");
        fileSavePathMqNoticeDTO.setCategory(category);

//        stepMqProducer.push(TopicConst.WXPTFZ_XNZB, "data", fileSavePathMqNoticeDTO);
    }

    /**
     * 根据reqId查询对应任务
     * @param reqIds:需求id集合
     * @return
     */
    private List<FzTaskRpcDTO> getFzTaskRpcDTOS(List<String> reqIds) {
        FzTaskInfoRpcReqDTO fzTaskInfoRpcReqDTO = new FzTaskInfoRpcReqDTO();
        fzTaskInfoRpcReqDTO.setReqIds(reqIds);
        List<FzTaskRpcDTO> fzTaskDTOList = fzTaskRpcService.getFzTaskDTOList(fzTaskInfoRpcReqDTO);
        return fzTaskDTOList;
    }
}
