package net.northking.cctp.dw.schedule;

import net.northking.cctp.dw.api.service.MtManualExecJobApiService;
import net.northking.cctp.dw.constant.DWConstant;
import net.northking.cctp.dw.db.entity.DwManualExecJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;


//@Component
public class MtManualExecJobProducer {

    private final static Logger logger = LoggerFactory.getLogger(MtManualExecJobProducer.class);

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    @Autowired
    private MtManualExecJobApiService mtManualExecJobApiService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 用例执行通过率
     */
    @Scheduled(fixedDelayString = "${nk.scheduled2:120000}")
    public void execJobRatioProducer() {
        //  加锁解决集群后多次触发问题
        Lock lock = redisLockRegistry.obtain("exec-job-ratio-producer");
        boolean b = lock.tryLock();
        try {
            if (b) {
                List<DwManualExecJob> dwManualExecJobList = mtManualExecJobApiService.findProIdList();
                if (!dwManualExecJobList.isEmpty()) {
                    // 根据租户id分组
                    Map<String, List<DwManualExecJob>> map = dwManualExecJobList.stream().collect(Collectors.groupingBy(DwManualExecJob::getTenantId));
                    Iterator<Map.Entry<String, List<DwManualExecJob>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<DwManualExecJob>> next = iterator.next();
                        List<DwManualExecJob> jobList = next.getValue();
                        // 每20个系统作为一个队列
                        int count = 20;
                        Integer num = jobList.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<DwManualExecJob> list = jobList.subList(i * count, stop);
                            // 发送消息
                            amqpTemplate.convertAndSend(DWConstant.MQ_HANDLE_DATA_EXCHANGE, DWConstant.BugRoutingKey.EXEC_JOB_RATIO_PRODUCER_DATA, list);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (b) {
                lock.unlock();
            }
        }
    }

    /**
     * 用例执行总体情况
     */
    @Scheduled(fixedDelayString = "${nk.scheduled2:120000}")
    public void execJobOverallProducer() {
        //  加锁解决集群后多次触发问题
        Lock lock = redisLockRegistry.obtain("exec-job-overall-producer");
        boolean b = lock.tryLock();
        try {
            if (b) {
                List<DwManualExecJob> dwManualExecJobList = mtManualExecJobApiService.findProIdList();
                if (!dwManualExecJobList.isEmpty()) {
                    // 根据租户id分组
                    Map<String, List<DwManualExecJob>> map = dwManualExecJobList.stream().collect(Collectors.groupingBy(DwManualExecJob::getTenantId));
                    Iterator<Map.Entry<String, List<DwManualExecJob>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<DwManualExecJob>> next = iterator.next();
                        List<DwManualExecJob> jobList = next.getValue();
                        // 每20个系统作为一个队列
                        int count = 20;
                        Integer num = jobList.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<DwManualExecJob> list = jobList.subList(i * count, stop);
                            // 发送消息
                            amqpTemplate.convertAndSend(DWConstant.MQ_HANDLE_DATA_EXCHANGE, DWConstant.BugRoutingKey.EXEC_JOB_OVERALL_PRODUCER_DATA, list);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (b) {
                lock.unlock();
            }
        }
    }

    /**
     * 用例执行统计图
     */
    @Scheduled(fixedDelayString = "${nk.scheduled2:120000}")
    public void execJobChartProducer() {
        //  加锁解决集群后多次触发问题
        Lock lock = redisLockRegistry.obtain("exec-job-chart-producer");
        boolean b = lock.tryLock();
        try {
            if (b) {
                List<DwManualExecJob> dwManualExecJobList = mtManualExecJobApiService.findProIdList();
                if (!dwManualExecJobList.isEmpty()) {
                    // 根据租户id分组
                    Map<String, List<DwManualExecJob>> map = dwManualExecJobList.stream().collect(Collectors.groupingBy(DwManualExecJob::getTenantId));
                    Iterator<Map.Entry<String, List<DwManualExecJob>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<DwManualExecJob>> next = iterator.next();
                        List<DwManualExecJob> jobList = next.getValue();
                        // 每20个系统作为一个队列
                        int count = 20;
                        Integer num = jobList.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<DwManualExecJob> list = jobList.subList(i * count, stop);
                            // 发送消息
                            amqpTemplate.convertAndSend(DWConstant.MQ_HANDLE_DATA_EXCHANGE, DWConstant.BugRoutingKey.EXEC_JOB_CHART_PRODUCER_DATA, list);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (b) {
                lock.unlock();
            }
        }
    }

    /**
     * 测试执行趋势图
     */
    @Scheduled(fixedDelayString = "${nk.scheduled2:120000}")
    public void execJobTrendChartProducer() {
        //  加锁解决集群后多次触发问题
        Lock lock = redisLockRegistry.obtain("exec-job-trend-chart-producer");
        boolean b = lock.tryLock();
        try {
            if (b) {
                List<DwManualExecJob> dwManualExecJobList = mtManualExecJobApiService.findProIdList();
                if (!dwManualExecJobList.isEmpty()) {
                    // 根据租户id分组
                    Map<String, List<DwManualExecJob>> map = dwManualExecJobList.stream().collect(Collectors.groupingBy(DwManualExecJob::getTenantId));
                    Iterator<Map.Entry<String, List<DwManualExecJob>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<DwManualExecJob>> next = iterator.next();
                        List<DwManualExecJob> jobList = next.getValue();
                        // 每20个系统作为一个队列
                        int count = 20;
                        Integer num = jobList.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<DwManualExecJob> list = jobList.subList(i * count, stop);
                            // 发送消息
                            amqpTemplate.convertAndSend(DWConstant.MQ_HANDLE_DATA_EXCHANGE, DWConstant.BugRoutingKey.EXEC_JOB_TREND_CHART_PRODUCER_DATA, list);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (b) {
                lock.unlock();
            }
        }
    }














}
