/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2009-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

package com.persagy.server.jms

import com.persagy.base.extensions.toJson
import com.persagy.server.datacenter.models.jms.SBaseNotice
import org.springframework.amqp.core.AmqpTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import java.util.*

/**
 *
 * @author wx  <zhangweixin@sagacloud.com>
 * @date  2020/10/27 21:05
 */
@Component
@Service
open class RabbitMqBaseService {
    /** 指定 AMQP 操作的基本集合 */
    @Autowired
    private val amqpTemplate: AmqpTemplate? = null
    /** 延迟发送时间 */
    var delaySendTime = 3000L
    /** 实现迟延相关数据 */
    private val delayMap = HashMap<String, SDelayData>()

    /**
     * 发送通知
     *
     * @param   exchange     交换机
     * @param   routingKey   key
     * @param   notice      通知
     * @param   delaySend   是否启动延迟发送，默认延迟发送
     */
    fun sendMessage(exchange: String, routingKey: String, notice: SBaseNotice, delaySend: Boolean = true) {
        val delayData = delayMap[routingKey] ?: SDelayData()
        if (!delayMap.containsKey(routingKey)) {
            delayMap[routingKey] = delayData
        }

        // 合并请求
        if (!mergeNotice(exchange,routingKey, notice)) {
            if (delayData.lastNotice != null) {
                sendTopic(exchange,routingKey, delayData.lastNotice!!.toJson())
            }
            delayData.lastNotice = notice
        }

        // 是否延迟发送
        if (delaySend) {
            delaySend(exchange,routingKey)
        } else {
            flush(exchange,routingKey)
        }

        return
    } // Fun sendNotice()

    /**
     * 发送 topic 消息
     *
     * @param   topic       发送标题
     * @param   data        消息数据
     */
    fun sendTopic(exchange: String,routingKey: String, data: String) {
        amqpTemplate!!.convertAndSend(exchange, routingKey, data)
    } // Fun sendTopic()

    /**
     * 合并通知
     *
     * @param   lastNotice          缓存的通知
     * @param   notice              新的通知
     * @return  成功返回true，否则返回false
     */
    open fun mergeNotice(lastNotice: SBaseNotice, notice: SBaseNotice): Boolean {
        return false
    } // Function mergeNotice()

    /**
     * 延迟发送缓存的消息
     *
     * @param   topic       发送标题
     */
    private fun delaySend(exchange: String,routingKey: String) {
        val delayData = delayMap[routingKey] ?: return

        // 如果延迟任务不为空，则取消之前的延迟任务。保证延迟任务在最后一次发送后执行。
        if (delayData.delayTask != null) {
            delayData.delayTask!!.cancel()
        }

        // 创建延迟任务
        delayData.delayTask = object : TimerTask() {
            override fun run() {
                // 发送缓存的任务
                flush(exchange,routingKey)
            }
        }

        // 启动延迟发送任务
        delayData.delayTimer.schedule(delayData.delayTask, delaySendTime)

        return
    } // Fun delaySend()

    /**
     * 发送缓存的消息
     *
     * @param   topic       发送标题
     */
    fun flush(exchange: String,routingKey: String) {
        val delayData = delayMap[routingKey] ?: return
        // 如果没有缓存通知
        if (delayData.lastNotice == null) {
            return
        }

        sendTopic(exchange,routingKey, delayData.lastNotice!!.toJson())
        delayData.lastNotice = null

        return
    } // Fun flush()

    /**
     * 合并通知
     *
     * @param   topic       发送标题
     * @param   notice      要合并的通知
     * @return  成功返回true，否则返回false
     */
    private fun mergeNotice(exchange: String,routingKey: String, notice: SBaseNotice): Boolean {
        val delayData = delayMap[routingKey] ?: return false

        // 如果最后发送的通知为空
        if (delayData.lastNotice == null) {
            delayData.lastNotice = notice
            return true
        }

        return mergeNotice(delayData.lastNotice!!, notice)
    } // Fun mergeNotice()



    /**
     * 延迟处理数据
     */
    inner class SDelayData {
        /** 最后发送的通知 */
        var lastNotice: SBaseNotice? = null
        /** 延迟发送通知定时器 */
        val delayTimer = Timer()
        /** 延迟发送通知定时任务 */
        var delayTask: TimerTask? = null
    } // Class SDelayData

}