package com.jeeplus.common.utils;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SmackUtils {
    private static Logger logger = LoggerFactory.getLogger(SmackUtils.class);
    private static String openfireServer = Global.getOpenfireServer();
    private static String sysNotify = Global.getSysNotify();
    private static String pres_base_url = "http://";

    static {
        pres_base_url=pres_base_url+openfireServer+":9090/plugins/presence/status?type=xml&jid=";
    }

    public static AjaxJson sendSmackMessage(String userId, String body,String sys) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            if(com.jeeplus.common.utils.StringUtils.isBlank(userId)){
                userId = UserUtils.getUser().getId();
            }
            String message = "";
            if("_online_all_status_".equals(sys)){
                message = "{\"msg\":" + body + "," +
                        "\"fromPortrait\":\"" + sysNotify + "\"," +
                        "\"xmppChatType\":\"" + sys + "\"," +
                        "\"fromUserName\":\"系统消息\"," +
                        "\"bodyType\":\"txt\"}";
            }else {
                message = "{\"msg\":\"审批信息 " + body + "\"," +
                        "\"fromPortrait\":\"" + sysNotify + "\"," +
                        "\"xmppChatType\":\"" + sys + "\"," +
                        "\"fromUserName\":\"系统消息\"," +
                        "\"bodyType\":\"txt\"}";
            }
            AbstractXMPPConnection con = getXmpptcpConnection();
            con.connect();
            // 用户登录
            con.login();
            // 是否已经通过身份验证
            System.out.println("Authenticated = " + con.isAuthenticated());
            // Assume we've created an XMPPConnection name "connection"._
            ChatManager chatManager = ChatManager.getInstanceFor(con);
            chatManager.addIncomingListener(new IncomingChatMessageListener() {
                @Override
                public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
                    System.out.println("New message from " + from + ": " + message.getBody());
                }
            });
            EntityBareJid jid = JidCreate.entityBareFrom( userId+"@"+openfireServer);//设置发送目标);
            Chat chat = chatManager.chatWith(jid);
            chat.send(message);
            con.disconnect();
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("审批发送成功");
        } catch (Exception e) {
            System.out.println("Exception e:"+e);
            e.printStackTrace();
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("审批发送失败::"+e);
        }
        return ajaxJson;
    }

    private static AbstractXMPPConnection getXmpptcpConnection() throws XmppStringprepException {
        XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
        configBuilder.setUsernameAndPassword("1@"+openfireServer, "admin");
        configBuilder.setResource("sys");
        configBuilder.setXmppDomain(openfireServer);
        configBuilder.setHost(openfireServer);
        configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
        return connection;
    }

    /**
     * @param id
     * @return
     */
    public static String IsUserOnLine(String id){
        String state = "online";
        String strUrl = pres_base_url+id+"@"+openfireServer;
        try{
            URL oUrl  = new URL(strUrl);
//            System.out.println("========="+oUrl.toString());
            URLConnection oConn = oUrl.openConnection();
            if(oConn!=null){
                BufferedReader oIn = new BufferedReader(new InputStreamReader(oConn.getInputStream()));
                if(null!=oIn){
                    String strFlag = oIn.readLine();
                    oIn.close();
                    if(strFlag.indexOf("Unavailable")>=0||strFlag.indexOf("type=\"error\"")>=0){
                        state = "offline";
                    }
                }
            }
        }catch(Exception e){
            logger.error("查询用户在线信息异常：",e);
            state = "offline";
        }
        return state;
    }

}
