package com.kingtom.shengtai.app.message.ws;

import java.text.MessageFormat;
import java.util.List;

import com.kingtom.kirin.app.system.model.SystemUser;
import com.kingtom.kirin.app.system.service.ISystemUserService;
import com.kingtom.shengtai.app.message.util.UniAppUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * 应用模块名称</p>
 * 代码描述</p>
 * Copyright: Copyright (C) 2024 , Inc. All rights reserved. <p>
 * Company: 成都诚唐科技有限责任公司</p>
 *
 * @author wany
 * @since 2024/1/3
 */
@Slf4j
@Component
public class WsSendService{

    @Autowired
    private WsHandler wsHandler;

    @Autowired
    private ISystemUserService systemUserService;

    public void sendMsg(List<String> userIds, String text){
        userIds.forEach(e -> sendMsg(e, text));
    }

    public void sendMsg(String userId, String text){
        if(StringUtils.isAnyBlank(text, userId)){
            return;
        }
        sendWebSocketMsg(userId, text);
        sendUniAppCloudMsg(userId, text);
    }

    private void sendUniAppCloudMsg(String userId, String text){
        SystemUser systemUser = systemUserService.getById(userId);
        if(systemUser != null && StringUtils.isNotEmpty(systemUser.getExt1())){
            UniAppUtils.sendCloudMessage(systemUser.getExt1(), text);
        }
    }

    private void sendWebSocketMsg(String userId, String text){
        WebSocketSession webSocketSession = WsSessionManager.get(userId);
        if(webSocketSession == null){
            return;
        }
        TextMessage message = new TextMessage(text);
        try{
            wsHandler.handleTextMessage(webSocketSession, message);
        } catch(Exception e){
            log.warn(MessageFormat.format("发送websocket消息给用户（{0}）时出错，消息内容：{1}", userId, text));
        }
    }

}
