package net.northking.cctp.executePlan.bus;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.executePlan.api.service.MqSynchronizeTaskApiService;
import net.northking.cctp.executePlan.constants.MsgConstant;
import net.northking.cctp.executePlan.db.entity.*;
import net.northking.cctp.executePlan.enums.ErrorMessage;
import net.northking.cctp.executePlan.enums.TaskTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: baoxt
 * @@CreateDate: 2023-09-15
 */
@Component
public class SyncData2DwPublisher {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(SyncData2DwPublisher.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MqSynchronizeTaskApiService mqSynchronizeTaskApiService;
    @Autowired
    private RedisLockRegistry redisLockRegistry;

    //同步执行计划数据
    @Scheduled(fixedDelayString ="${atu.plan.syncAtuPlanInfo:120000}")
    public void syncAtuPlanInfo() {
        Lock lock = redisLockRegistry.obtain(MsgConstant.SYNC_ATUPLAN_INFO);
        try {
            boolean b = lock.tryLock(10, TimeUnit.SECONDS);
            if (b){
                byte[] json;
                //查询
                List<MqSynchronizeTask> mqSynchronizeTasks= mqSynchronizeTaskApiService.findByTypes(Collections.singletonList(TaskTypeEnum.SYNC_PLAN_INFO.getCode()));
                //处理推送数据
                if (mqSynchronizeTasks.size()!=0){
                    //删除
                    List<Object> ids = mqSynchronizeTasks.stream().map(MqSynchronizeTask::getId).collect(Collectors.toList());
                    mqSynchronizeTaskApiService.deleteBatch(ids);
                    //数据处理
                    List<AtuPlanInfo> atuPlanInfoList = new ArrayList<>();
                    for (MqSynchronizeTask mqSynchronizeTask: mqSynchronizeTasks) {
                        AtuPlanInfo atuCaseInfo = JSONObject.parseObject(mqSynchronizeTask.getTaskInfo(), AtuPlanInfo.class);
                        atuPlanInfoList.add(atuCaseInfo);
                    }
                    //根据更新时间获取相同id最新的更新记录
                    List<String> idList = atuPlanInfoList.stream().map(AtuPlanInfo::getId).distinct().collect(Collectors.toList());
                    Map<String, List<AtuPlanInfo>> map = atuPlanInfoList.stream().collect(Collectors.groupingBy(AtuPlanInfo::getId));
                    List<AtuPlanInfo> atuPlanInfos = new ArrayList<>();
                    for (String id:idList) {
                        List<AtuPlanInfo> atuPlanInfoListTemp = map.get(id);
                        List<AtuPlanInfo> collect = atuPlanInfoListTemp.stream().sorted(Comparator.comparing(AtuPlanInfo::getUpdatedTime).reversed()).collect(Collectors.toList());
                        atuPlanInfos.add(collect.get(0));
                    }
                    // 分包发送
                    int count = 20;
                    Integer num = atuPlanInfos.size();
                    for (int i = 0; i < num / count + 1; i++) {
                        if (i * count == num) {
                            break;
                        }
                        int stop = (i + 1) * count > num ? num : (i + 1) * count;
                        List<AtuPlanInfo> subAtuPlanInfos = atuPlanInfos.subList(i * count, stop);

                        json = objectMapper.writeValueAsBytes(subAtuPlanInfos);
                        MessageBuilder mb = MessageBuilder.withBody(json);
                        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        rabbitTemplate.send(MsgConstant.DW_ATUPLANINFO_INSERT_REQ, mb.build());
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new PlatformRuntimeException(new ErrorMessage(e.getMessage()));
        } catch (JsonProcessingException e) {
            throw new PlatformRuntimeException(new ErrorMessage("同步执行计划信息消息发送失败！！！"));
        }finally {
            lock.unlock();
        }
    }


    @Scheduled(fixedDelayString ="${atu.plan.syncAtuPlanBatch:120000}")
    public void syncAtuPlanBatch() {
        Lock lock = redisLockRegistry.obtain(MsgConstant.SYNC_ATUPLAN_BATCH);
        try {
            boolean b = lock.tryLock(10, TimeUnit.SECONDS);
            if (b){
                byte[] json;
                //查询
                List<MqSynchronizeTask> mqSynchronizeTasks= mqSynchronizeTaskApiService.findByTypes(Collections.singletonList(TaskTypeEnum.SYNC_PLAN_BATCH.getCode()));
                //处理推送数据
                if (mqSynchronizeTasks.size()!=0){
                    //删除
                    List<Object> ids = mqSynchronizeTasks.stream().map(MqSynchronizeTask::getId).collect(Collectors.toList());
                    mqSynchronizeTaskApiService.deleteBatch(ids);
                    //数据处理
                    List<AtuPlanBatch> atuPlanBatchList = new ArrayList<>();
                    for (MqSynchronizeTask mqSynchronizeTask: mqSynchronizeTasks) {
                        AtuPlanBatch atuPlanBatch = JSONObject.parseObject(mqSynchronizeTask.getTaskInfo(), AtuPlanBatch.class);
                        atuPlanBatchList.add(atuPlanBatch);
                    }
                    //根据更新时间获取相同id最新的更新记录
                    List<String> idList = atuPlanBatchList.stream().map(AtuPlanBatch::getId).distinct().collect(Collectors.toList());
                    Map<String, List<AtuPlanBatch>> map = atuPlanBatchList.stream().collect(Collectors.groupingBy(AtuPlanBatch::getId));
                    List<AtuPlanBatch> atuPlanBatches = new ArrayList<>();
                    for (String id:idList) {
                        List<AtuPlanBatch> atuPlanInfoListTemp = map.get(id);
                        List<AtuPlanBatch> collect = atuPlanInfoListTemp.stream().sorted(Comparator.comparing(AtuPlanBatch::getCreatedTime).reversed()).collect(Collectors.toList());
                        atuPlanBatches.add(collect.get(0));
                    }
                    // 分包发送
                    int count = 20;
                    Integer num = atuPlanBatches.size();
                    for (int i = 0; i < num / count + 1; i++) {
                        if (i * count == num) {
                            break;
                        }
                        int stop = (i + 1) * count > num ? num : (i + 1) * count;
                        List<AtuPlanBatch> subAtuPlanBatchs = atuPlanBatches.subList(i * count, stop);

                        json = objectMapper.writeValueAsBytes(subAtuPlanBatchs);
                        MessageBuilder mb = MessageBuilder.withBody(json);
                        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        rabbitTemplate.send(MsgConstant.DW_ATUPLANBATCH_INSERT_REQ, mb.build());
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new PlatformRuntimeException(new ErrorMessage(e.getMessage()));
        } catch (JsonProcessingException e) {
            throw new PlatformRuntimeException(new ErrorMessage("同步执行计划信息消息发送失败！！！"));
        }finally {
            lock.unlock();
        }
    }


    @Scheduled(fixedDelayString ="${atu.plan.syncAtuPlanScriptLink:120000}")
    public void syncAtuPlanScriptLink(){
        Lock lock = redisLockRegistry.obtain(MsgConstant.SYNC_ATUPLAN_SCRIPTLINK);
        try {
            boolean b = lock.tryLock(10, TimeUnit.SECONDS);
            if(b){
                byte[] json;
                //查询
                List<MqSynchronizeTask> mqSynchronizeTasks= mqSynchronizeTaskApiService.findByTypes(Collections.singletonList(TaskTypeEnum.SYNC_PLAN_SCRIPT_LINK.getCode()));
                //处理推送数据
                if (mqSynchronizeTasks.size()!=0){
                    //删除
                    List<Object> ids = mqSynchronizeTasks.stream().map(MqSynchronizeTask::getId).collect(Collectors.toList());
                    mqSynchronizeTaskApiService.deleteBatch(ids);
                    //数据处理
                    List<AtuPlanScriptLink> atuPlanScriptLinkList = new ArrayList<>();
                    for (MqSynchronizeTask mqSynchronizeTask: mqSynchronizeTasks) {
                        AtuPlanScriptLink atuPlanScriptLink = JSONObject.parseObject(mqSynchronizeTask.getTaskInfo(), AtuPlanScriptLink.class);
                        atuPlanScriptLinkList.add(atuPlanScriptLink);
                    }
                    //根据更新时间获取相同id最新的更新记录
                    List<Long> idList = atuPlanScriptLinkList.stream().map(AtuPlanScriptLink::getId).distinct().collect(Collectors.toList());
                    Map<Long, List<AtuPlanScriptLink>> map = atuPlanScriptLinkList.stream().collect(Collectors.groupingBy(AtuPlanScriptLink::getId));
                    List<AtuPlanScriptLink> atuPlanScriptLinks = new ArrayList<>();
                    for (Long id:idList) {
                        List<AtuPlanScriptLink> atuPlanScriptLinkListTemp = map.get(id);
                        List<AtuPlanScriptLink> collect = atuPlanScriptLinkListTemp.stream().collect(Collectors.toList());
                        atuPlanScriptLinks.add(collect.get(0));
                    }
                    // 分包发送
                    int count = 20;
                    Integer num = atuPlanScriptLinks.size();
                    for (int i = 0; i < num / count + 1; i++) {
                        if (i * count == num) {
                            break;
                        }
                        int stop = (i + 1) * count > num ? num : (i + 1) * count;
                        List<AtuPlanScriptLink> subAtuPlanScriptLinks = atuPlanScriptLinks.subList(i * count, stop);

                        json = objectMapper.writeValueAsBytes(subAtuPlanScriptLinks);
                        MessageBuilder mb = MessageBuilder.withBody(json);
                        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        rabbitTemplate.send(MsgConstant.DW_ATUPLANSCRIPTLINK_INSERT_REQ, mb.build());
                    }
                }
            }
        }catch (InterruptedException e){
            Thread.currentThread().interrupt();
            throw new PlatformRuntimeException(new ErrorMessage(e.getMessage()));
        }catch (JsonProcessingException e){
            throw new PlatformRuntimeException(new ErrorMessage("同步执行计划信息消息发送失败！！！"));
        }finally {
            lock.unlock();
        }
    }

    @Scheduled(fixedDelayString ="${atu.plan.syncAtuPlanEnvLink:120000}")
    public void syncAtuPlanEnvLink(){
        Lock lock = redisLockRegistry.obtain(MsgConstant.SYNC_ATUPLAN_ENVLINK);
        try {
            boolean b = lock.tryLock(10, TimeUnit.SECONDS);
            if(b){
                byte[] json;
                //查询
                List<MqSynchronizeTask> mqSynchronizeTasks= mqSynchronizeTaskApiService.findByTypes(Collections.singletonList(TaskTypeEnum.SYNC_PLAN_ENV_LINK.getCode()));
                //处理推送数据
                if (mqSynchronizeTasks.size()!=0){
                    //删除
                    List<Object> ids = mqSynchronizeTasks.stream().map(MqSynchronizeTask::getId).collect(Collectors.toList());
                    mqSynchronizeTaskApiService.deleteBatch(ids);
                    //数据处理
                    List<AtuPlanEnvLink> atuPlanEnvLinkList = new ArrayList<>();
                    for (MqSynchronizeTask mqSynchronizeTask: mqSynchronizeTasks) {
                        AtuPlanEnvLink atuPlanEnvLink = JSONObject.parseObject(mqSynchronizeTask.getTaskInfo(), AtuPlanEnvLink.class);
                        atuPlanEnvLinkList.add(atuPlanEnvLink);
                    }
                    //根据更新时间获取相同id最新的更新记录
                    List<Long> idList = atuPlanEnvLinkList.stream().map(AtuPlanEnvLink::getId).distinct().collect(Collectors.toList());
                    Map<Long, List<AtuPlanEnvLink>> map = atuPlanEnvLinkList.stream().collect(Collectors.groupingBy(AtuPlanEnvLink::getId));
                    List<AtuPlanEnvLink> atuPlanEnvLinks = new ArrayList<>();
                    for (Long id:idList) {
                        List<AtuPlanEnvLink> atuPlanEnvLinkListTemp = map.get(id);
                        List<AtuPlanEnvLink> collect = atuPlanEnvLinkListTemp.stream().collect(Collectors.toList());
                        atuPlanEnvLinks.add(collect.get(0));
                    }
                    // 分包发送
                    int count = 20;
                    Integer num = atuPlanEnvLinks.size();
                    for (int i = 0; i < num / count + 1; i++) {
                        if (i * count == num) {
                            break;
                        }
                        int stop = (i + 1) * count > num ? num : (i + 1) * count;
                        List<AtuPlanEnvLink> subAtuPlanEnvLinks = atuPlanEnvLinks.subList(i * count, stop);

                        json = objectMapper.writeValueAsBytes(atuPlanEnvLinks);
                        MessageBuilder mb = MessageBuilder.withBody(json);
                        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        rabbitTemplate.send(MsgConstant.DW_ATUPLANEnvLink_INSERT_REQ, mb.build());
                    }
                }
            }
        }catch (InterruptedException e){
            Thread.currentThread().interrupt();
            throw new PlatformRuntimeException(new ErrorMessage(e.getMessage()));
        }catch (JsonProcessingException e){
            throw new PlatformRuntimeException(new ErrorMessage("同步执行计划信息消息发送失败！！！"));
        }finally {
            lock.unlock();
        }
    }

    @Scheduled(fixedDelayString ="${atu.plan.syncAtuPlanTask:120000}")
    public void syncAtuPlanTask() {
        Lock lock = redisLockRegistry.obtain(MsgConstant.SYNC_ATUPLAN_TASK);
        try {
            boolean b = lock.tryLock(10, TimeUnit.SECONDS);
            if (b){
                byte[] json;
                //查询
                List<MqSynchronizeTask> mqSynchronizeTasks= mqSynchronizeTaskApiService.findByTypes(Collections.singletonList(TaskTypeEnum.SYNC_PLAN_TASK.getCode()));
                //处理推送数据
                if (mqSynchronizeTasks.size()!=0){
                    //删除
                    List<Object> ids = mqSynchronizeTasks.stream().map(MqSynchronizeTask::getId).collect(Collectors.toList());
                    mqSynchronizeTaskApiService.deleteBatch(ids);
                    //数据处理
                    List<AtuPlanTask> atuPlanTaskList = new ArrayList<>();
                    for (MqSynchronizeTask mqSynchronizeTask: mqSynchronizeTasks) {
                        AtuPlanTask atuPlanTask = JSONObject.parseObject(mqSynchronizeTask.getTaskInfo(), AtuPlanTask.class);
                        atuPlanTaskList.add(atuPlanTask);
                    }
                    //根据更新时间获取相同id最新的更新记录
                    List<String> idList = atuPlanTaskList.stream().map(AtuPlanTask::getId).distinct().collect(Collectors.toList());
                    Map<String, List<AtuPlanTask>> map = atuPlanTaskList.stream().collect(Collectors.groupingBy(AtuPlanTask::getId));
                    List<AtuPlanTask> atuPlanTasks = new ArrayList<>();
                    for (String id:idList) {
                        List<AtuPlanTask> atuPlanInfoListTemp = map.get(id);
                        List<AtuPlanTask> collect = atuPlanInfoListTemp.stream().sorted(Comparator.comparing(AtuPlanTask::getCreatedTime).reversed()).collect(Collectors.toList());
                        atuPlanTasks.add(collect.get(0));
                    }
                    // 分包发送
                    int count = 20;
                    Integer num = atuPlanTasks.size();
                    for (int i = 0; i < num / count + 1; i++) {
                        if (i * count == num) {
                            break;
                        }
                        int stop = (i + 1) * count > num ? num : (i + 1) * count;
                        List<AtuPlanTask> subAtuPlanTasks = atuPlanTasks.subList(i * count, stop);

                        json = objectMapper.writeValueAsBytes(subAtuPlanTasks);
                        MessageBuilder mb = MessageBuilder.withBody(json);
                        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        rabbitTemplate.send(MsgConstant.DW_ATUPLANTASK_INSERT_REQ, mb.build());
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new PlatformRuntimeException(new ErrorMessage(e.getMessage()));
        } catch (JsonProcessingException e) {
            throw new PlatformRuntimeException(new ErrorMessage("同步计划执行任务发送失败！！！"));
        }finally {
            lock.unlock();
        }
    }

}
