package com.crm.rely.backend.configuration;

import com.alibaba.fastjson.JSON;
import com.crm.rely.backend.aspect.LogType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 日志定时发送服务
 */
@Component
public class LogQuartzComponent {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private BaseActiveMqConfiguration baseAcitveMqConfiguration;

    /**
     * 日志内存队列
     */
//    public static Queue<Map<String,Map<String, Map<Long, Map<LogType, Object>>>>> logQueue = new ConcurrentLinkedQueue<>();
    public static Queue<Map<String, Map<Long, Map<LogType, Object>>>> logQueue = new ConcurrentLinkedQueue<>();
    /**
     * 向队列中添加日志
     *
     * @param log
     */
//    public static void add(Map<String, Map<Long, Map<LogType, Object>>> log,String url) {
//        Map<String,Object> map=  new HashMap<>();
//        map.put(url,log);
//        logQueue.add(map);
//    }
    public static void add(Map<String, Map<Long, Map<LogType, Object>>> log) {

        logQueue.add(log);
    }

    /**
     * 每五秒先activemq发送操作日志
     *
     * @throws Exception
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void activeMqSendByFive() throws Exception {
        /**
         * 取队列第一个 并删除 如果队列为空 返回null 用于下列判断
         */
//        Map<String,Map<String, Map<Long, Map<LogType, Object>>>> object = logQueue.poll();
        Map<String, Map<Long, Map<LogType, Object>>> object = logQueue.poll();
        while (object != null) {
            jmsTemplate.convertAndSend(baseAcitveMqConfiguration.logQueue(), JSON.toJSONString(object));
            object = logQueue.poll();
        }
    }
}
