package cn.com.capcloud.core.websocket;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.quartz.task.TaskService;
import cn.com.capcloud.core.system.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * RedisConfig
 * 创建Redis消息队列发布者
 * @Author LiaoJiaHui
 * @Create 2024/3/20 14:23
 **/
@Configuration
public class RedisPublication {

    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private ApiService apiService;

    /**
     * 根据userId推送消息
     */
    public void sendMessage(String message,String userId) {
        // 通过 ApplicationContext 获取 StringRedisTemplate
        StringRedisTemplate redisTemplate = null;
        if ("redis".equals(System.getProperty("rzth.cache.type"))) {  // 可以通过配置来判断缓存类型
            redisTemplate = applicationContext.getBean(StringRedisTemplate.class);
        }
        if (redisTemplate != null) {
            JackJSONObject messageObject = new JackJSONObject();
            messageObject.put("userId", userId);
            messageObject.put("content", message);
            redisTemplate.convertAndSend("channel:message", JackJSON.toJSONString(messageObject));
        }else{
            WebSocket.sendMessageById(message,userId);
        }
    }

    /**
     * 根据任务uuid执行任务
     */
    public void sendTask(String taskUUID,String type,String userId) {
        // 通过 ApplicationContext 获取 StringRedisTemplate
        StringRedisTemplate redisTemplate = null;
        TaskService taskService = null;
        if ("redis".equals(System.getProperty("rzth.cache.type"))) {  // 可以通过配置来判断缓存类型
            redisTemplate = applicationContext.getBean(StringRedisTemplate.class);
        }else{
            taskService = applicationContext.getBean(TaskService.class);
        }
        JackJSONObject messageObject = new JackJSONObject();
        messageObject.put("userId", userId);
        messageObject.put("taskUUID", taskUUID);
        messageObject.put("type", type);
        if (redisTemplate != null) {
            redisTemplate.convertAndSend("channel:task", JackJSON.toJSONString(messageObject));
        }else{
            taskService.runTask(messageObject);
        }
    }

    /**
     * 更新任务状态
     */
    public void sendUpdateTaskStatus() {
        // 通过 ApplicationContext 获取 StringRedisTemplate
        StringRedisTemplate redisTemplate = null;
        TaskService taskService = null;
        if ("redis".equals(System.getProperty("rzth.cache.type"))) {  // 可以通过配置来判断缓存类型
            redisTemplate = applicationContext.getBean(StringRedisTemplate.class);
        }else{
            taskService = applicationContext.getBean(TaskService.class);
        }
        if (redisTemplate != null) {
            JackJSONObject messageObject = new JackJSONObject();
            redisTemplate.convertAndSend("channel:updateTaskStatus", JackJSON.toJSONString(messageObject));
        }else{
            taskService.updateTaskStatus();
        }

    }

    @Async("taskExecutor")//可以加在类上或方法上（注意：taskExecutor不能随意更改，需要和配置文件一致）
    public void sendMessage(String message,String userId,long timeout) {
        try {
            // 通过 ApplicationContext 获取 StringRedisTemplate
            StringRedisTemplate redisTemplate = null;
            if ("redis".equals(System.getProperty("rzth.cache.type"))) {  // 可以通过配置来判断缓存类型
                redisTemplate = applicationContext.getBean(StringRedisTemplate.class);
            }
            if (redisTemplate != null) {
                Thread.sleep(timeout);
                JackJSONObject messageObject = new JackJSONObject();
                messageObject.put("userId", userId);
                messageObject.put("content", message);
                redisTemplate.convertAndSend("channel:message", JackJSON.toJSONString(messageObject));
            }else{
                WebSocket.sendMessageById(message,userId);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async("taskExecutor")//导入
    public void importExcelDataNew(String jsonStr, JackJSONObject retJson, HttpServletRequest request, User user) {
        apiService.importExcelDataNew(jsonStr,retJson,request,user);
    }

}
