package thyyxxk.webserver.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.Forest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.constants.Message;
import thyyxxk.webserver.entity.socketmessage.ApiMessageBody;

import java.util.Map;


/**
 * 发送系统消息
 *
 * @author 肖蟾
 */
@Component
public class SocketMsg {

    private static String SOCKET_URL;

    @Value("${forest.variables.socketCenter}")
    public void setUrl(String key) {
        SocketMsg.SOCKET_URL = key;
    }

    public static void sendMessageByUserCode(String code, Message messageName, JSONObject js) {
        String body = socketVo(messageName, js);
        ApiMessageBody apiMessageBody = new ApiMessageBody(code, body);
        Forest.post(SOCKET_URL + "/sendMessageByUserCode")
                .async()
                .addHeader("Content-Type", "application/json")
                .addBody(apiMessageBody)
                .execute();
    }


    public static String socketVo(Message messageName, JSONObject map) {
        JSONObject msg = new JSONObject();
        msg.put("name", messageName.getName());
        msg.put("message", map);
        return msg.toJSONString();
    }

    public static String socketVo(Message messageName, Map<String, Object> map) {
        JSONObject msg = new JSONObject();
        msg.put("name", messageName.getName());
        msg.put("message", map);
        return JSON.toJSONStringWithDateFormat(msg, DateUtil.DEFAULT_PATTERN);
    }


    public static String socketVo(Message messageName, String data) {
        JSONObject msg = new JSONObject();
        msg.put("name", messageName.getName());
        msg.put("message", data);
        return msg.toJSONString();
    }

}
