package com.base.biz.mq.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.api.client.PayloadRpcService;
import com.base.api.model.BizTaskStepEnum;
import com.base.api.model.PayloadRpcDTO;
import com.base.api.model.request.PayloadRpcReqDTO;
import com.base.biz.model.dto.request.FzTaskBodyMqDTO;
import com.base.biz.model.dto.request.FzTaskBodyMsgMqDTO;
import com.base.biz.model.entity.FzTaskInfo;
import com.base.biz.model.entity.PointInfo;
import com.base.biz.mq.factory.HandlerMqFactory;
import com.base.biz.service.FzTaskService;
import com.base.biz.service.PointService;
import com.base.orbit.log.ServerNameEnum;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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

/**
 * @author xj
 * @date 2023/5/22 11:24
 * @Description: 接收基础平台下发的运控数传仿真任务
 */
@Component
@Slf4j
public class FzTaskMqConsumerHandler extends AbstractMqInfoHandler {

    @Resource
    FzTaskService fzTaskService;
    @Resource
    PayloadRpcService payloadRpcService;
    @Resource
    PointService pointService;


    @Override
    public void process(List<String> var1) {
        String message = var1.get(0);
        log.info("receive fzTaskInfo message: " + message, ServerNameEnum.BASE_SERVER);
        //  入库
        List<FzTaskInfo> fzTaskInfos = new ArrayList<>();
        try {
            BaseHeadMqDTO baseHeadMqDTO = buildHeadDTO(message);
            FzTaskBodyMqDTO fzTaskBodyMqDTO = buildBodyDTO(message);
            log.info("fz task  body info taskId is " + fzTaskBodyMqDTO.getTaskId());
            List<FzTaskBodyMsgMqDTO> requireList = fzTaskBodyMqDTO.getRequireList();
            Integer reqCount = fzTaskBodyMqDTO.getReqCount();
            if (requireList.size() != reqCount) {
                log.error("require size must be equals req count!");
                throw new RuntimeException("require size must be equals req count!！");
            }
            for (int i = 0; i < reqCount; i++) {
                FzTaskInfo fzTaskInfo = new FzTaskInfo();
                FzTaskBodyMsgMqDTO fzTaskBodyMsgMqDTO = requireList.get(i);
                BeanUtils.copyProperties(fzTaskBodyMsgMqDTO, fzTaskInfo);
                formatBasePlatformDispatchTaskInfo(fzTaskInfo);
                buildFzTaskPayLoadId(fzTaskInfo);
                fzTaskInfo.setMessageId(baseHeadMqDTO.getMessageId());
                fzTaskInfo.setReqId(fzTaskBodyMsgMqDTO.getReqID());
                fzTaskInfo.setTargetId(fzTaskBodyMsgMqDTO.getTargetID());
                buildPointInfoByFzTaskId(fzTaskInfo);
                fzTaskInfo.setReqStartTime(DateUtils.string2LocalDate(DateUtils.TimeStampCastToStrDate(Long.valueOf(fzTaskBodyMsgMqDTO.getReqStartTime())), DateUtils.YYYY_MM_DD_HH_MM_SS));
                fzTaskInfo.setReqEndTime(DateUtils.string2LocalDate(DateUtils.TimeStampCastToStrDate(Long.valueOf(fzTaskBodyMsgMqDTO.getReqEndTime())), DateUtils.YYYY_MM_DD_HH_MM_SS));
                fzTaskInfo.setReqTime(DateUtils.string2LocalDate(DateUtils.TimeStampCastToStrDate(Long.valueOf(fzTaskBodyMsgMqDTO.getReqTime())), DateUtils.YYYY_MM_DD_HH_MM_SS));
                fzTaskInfo.setWorkMode(fzTaskBodyMsgMqDTO.getSensorMode());
                fzTaskInfo.setTaskId(fzTaskBodyMqDTO.getTaskId());
                fzTaskInfos.add(fzTaskInfo);
            }
        } catch (Exception e) {
            log.error("json str value cast to java bean is error, msg is " + e.getMessage() + "");
            e.printStackTrace();
        }
        fzTaskService.saveBatch(fzTaskInfos);
    }

    private void formatBasePlatformDispatchTaskInfo(FzTaskInfo fzTaskInfo) {
        fzTaskInfo.setId(IdGenerator.getStrId());
        fzTaskInfo.setFzTaskStep(BizTaskStepEnum.TASK_GET.toString());
        fzTaskInfo.setFzTaskState("0");
        fzTaskInfo.setCreateTime(LocalDateTime.now());
    }

    private void buildFzTaskPayLoadId(FzTaskInfo fzTaskInfo) {
        if (!StringUtils.isEmpty(fzTaskInfo.getSatellite())) {
            PayloadRpcReqDTO req = new PayloadRpcReqDTO();
            req.setSatelliteCodes(Arrays.asList(fzTaskInfo.getSatellite()));
            List<PayloadRpcDTO> payloadRpcDTOList = payloadRpcService.getPayloadRpcDTOList(req);
            List<PayloadRpcDTO> payloadRpcDTOS = payloadRpcDTOList.stream().filter(e -> fzTaskInfo.getSensorID().contains(e.getPayloadType())).collect(Collectors.toList());
            Optional<PayloadRpcDTO> payloadRpcDTO = payloadRpcDTOS.stream().findFirst();
            if (payloadRpcDTO.isPresent()) {
                PayloadRpcDTO payloadRpcDTO1 = payloadRpcDTO.get();
                fzTaskInfo.setPayloadIds(payloadRpcDTO1.getId());
            }
        }
    }

    private void buildPointInfoByFzTaskId(FzTaskInfo fzTaskInfo) {
        //  区域对应的范围
        String centerLocation = fzTaskInfo.getCenterLocation();
        String[] strArray = centerLocation.split(";");
        List<String> arrayList = new ArrayList<>(strArray.length);
        Collections.addAll(arrayList, strArray);
        List<PointInfo> pointInfos = new ArrayList<>();

        for (int i = 0; i < arrayList.size(); i++) {
            String[] str = arrayList.get(i).split(",");
            PointInfo pointInfo = new PointInfo();
            pointInfo.setId(IdGenerator.getStrId());
            pointInfo.setLongitude(str[0]);
            pointInfo.setLatitude(str[1]);
            pointInfo.setSort("1");
            pointInfo.setPointType("TARGET");
            pointInfo.setParentId(fzTaskInfo.getTargetId());
            pointInfo.setCreateTime(DateUtils.getNowDate());
            pointInfo.setSerial(i + "");
            pointInfos.add(pointInfo);
        }
        pointService.saveBatch(pointInfos);
        log.info("insert point info is success!");
    }

    /**
     * 构建请求头信息
     *
     * @param message 传入报文
     * @throws Exception
     */
    public static BaseHeadMqDTO buildHeadDTO(String message) {
        BaseHeadMqDTO baseHeadMqDTO = new BaseHeadMqDTO();
        JSONObject headObj = JSONObject.parseObject(message);
        baseHeadMqDTO.setMessageType(headObj.getString("messageType"));
        baseHeadMqDTO.setCreationTime(headObj.getString("creationTime"));
        baseHeadMqDTO.setRecipient(headObj.getString("recipient"));
        baseHeadMqDTO.setMessageId(headObj.getString("messageId"));
        baseHeadMqDTO.setOriginator(headObj.getString("originator"));
        return baseHeadMqDTO;
    }

    /**
     * 构建请求体信息
     *
     * @param message 传入报文
     * @return
     */
    public static FzTaskBodyMqDTO buildBodyDTO(String message) {
        JSONObject obj = JSONObject.parseObject(message);
        JSONObject body = obj.getJSONObject("body");
        log.info("json body task Id is" + body.getString("taskId"));
        String requireList = body.getString("requireList");
        FzTaskBodyMqDTO fzTaskBodyMqDTO = new FzTaskBodyMqDTO();
        fzTaskBodyMqDTO.setReqCount(Integer.valueOf(body.getString("reqCount")));
        fzTaskBodyMqDTO.setTaskId(body.getString("taskId"));
        List<FzTaskBodyMsgMqDTO> fzTaskBodyMsgMqDTOS = JSON.parseArray(requireList, FzTaskBodyMsgMqDTO.class);
        fzTaskBodyMqDTO.setRequireList(fzTaskBodyMsgMqDTOS);
        return fzTaskBodyMqDTO;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        HandlerMqFactory.register(TopicConst.FZ_TASK_TOPIC, this);
    }

}
