package com.inzy.wsmock

import com.alibaba.fastjson2.JSONObject
import com.inzy.wsmock.RequestParamHandler.Companion.PARAM_TYPE_KEY
import com.inzy.wsmock.RequestParamHandler.Companion.PARAM_TYPE_VALUE_1
import com.inzy.wsmock.RequestParamHandler.Companion.PARAM_TYPE_VALUE_2
import com.inzy.wsmock.RequestParamHandler.Companion.REQUEST_PARAMS_KEY
import com.inzy.wsmock.utils.FileIoUtil
import io.netty.channel.Channel
import jakarta.annotation.PostConstruct
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import org.springframework.core.io.ResourceLoader
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDateTime


@Component
class ScheduledAdasPushTask(
//    private val webSocketHandler: WebSocketHandler,
//    private val pushConfig: PushConfig,
    // 注入Spring资源加载器（Spring自动装配）
    private val resourceLoader: ResourceLoader
) {

    private val logger = LoggerFactory.getLogger(javaClass)

    // 注入ChannelManager单例
    private val channelManager = ChannelManager.instance

    //车辆位姿
    private var carDst = mutableListOf<String>()
    private var carDstIndex = 0

//    @PostConstruct
    fun readMockFile() {
        val classpathResource = resourceLoader.getResource("classpath:adasm/CarVehicle_fz.txt")
        // 读取文件内容（Kotlin简化写法）
        CoroutineScope(Dispatchers.Default).launch {
//            val content = classpathResource.inputStream.bufferedReader()
            FileIoUtil.getMockToList(classpathResource.inputStream, carDst)
//            println("读取到文件内容：${dst.count()}")
        }
    }

    /**
     * 定时推送任务（type=1） 车辆位姿
     */
//    @Scheduled(fixedDelayString = "#{@pushConfig.pushInterval}")
//    @Scheduled(fixedDelayString = "#{@pushConfig.pushInterval}")
    fun pushMsgToType1() {
/*        val onlineChannels = channelManager.getAllChannels()
        //得到设置了type属性的channel
        val typeChannels = filterTypeChannels(PARAM_TYPE_VALUE_1)
//        println("onlineChannels.size = ${onlineChannels.size}  typeChannels.size = ${typeChannels.size}")
//        val msgObj = JSONObject()
//        msgObj["content"] = "定时推送消息 type=1  ${LocalDateTime.now()}"
        if (carDst.isNotEmpty()){
            println("-------------carDstIndex = ${carDstIndex}")

            channelManager.sendMsgFromType(typeChannels, carDst.get(carDstIndex))
            carDstIndex = (carDstIndex + 1) % carDst.size // 循环索引
        }*/
    }


//    @Scheduled(fixedDelayString = "200")
  /*  fun pushMsgToType2() {
        //得到设置了type属性的channel
        val typeChannels = filterTypeChannels(PARAM_TYPE_VALUE_2)
//        println("onlineChannels.size = ${onlineChannels.size}  typeChannels.size = ${typeChannels.size}")
        val msgObj = JSONObject()
        msgObj["content"] = "定时推送消息 type=2 ${LocalDateTime.now()}"
        channelManager.sendMsgFromType(typeChannels, msgObj.toJSONString())
    }*/


    /**
     * @param type 前端的查询参数
     * **/
   /* private fun filterTypeChannels(type: String): Map<String, Channel> {
        val onlineChannels = channelManager.getAllChannels()
        //得到设置了type属性的channel
        val typeChannels =
            onlineChannels.filter { (id, channel) ->
                if (channel.hasAttr(REQUEST_PARAMS_KEY)) {
                    val params = channel.attr(REQUEST_PARAMS_KEY).get()
                    return@filter params.get(PARAM_TYPE_KEY) == type
                }
                false
            }
        return typeChannels
    }*/


    /**
     * 定时推送任务（固定延迟，避免任务叠加）
     */
//    @Scheduled(fixedDelayString = "#{@pushConfig.pushInterval}")
    fun pushMsgToClients() {
        // 增加日志，确认函数是否执行
//        logger.info("定时推送任务开始执行 - ${LocalDateTime.now()}")
        // 开关关闭时跳过
//        if (!pushConfig.pushEnabled.get()) {
//            return
//        }
        val onlineChannels = channelManager.getAllChannels()
//        if (onlineChannels.isEmpty()) {
////            println("定时推送：无在线客户端，跳过")
//            return
//        }
        //得到设置了type属性的channel
//        val typeChannels =
//            onlineChannels.filter { (id, channel) -> channel.hasAttr(WebSocketHandler.WS_QUERY_PARAMS_KEY) }

//        println("onlineChannels.size = ${onlineChannels.size}  typeChannels.size = ${typeChannels.size}")

        // 构造推送消息（适配前端格式）
        val msgObj = JSONObject()
        msgObj["content"] = "定时推送消息 - ${LocalDateTime.now()}"
        logger.debug("msgObj = ${msgObj}")
        // 广播给所有客户端
//        webSocketHandler.broadcastMsg(msgObj.toJSONString())
    }
}