package com.yihu.jw.hospital.prescription.service.entrance.util;

import com.ibm.mq.MQQueueManager;
import com.yihu.jw.util.date.DateUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.slf4j.Logger;
import com.ewell.mq.queue.QueueTools;
import com.ibm.mq.MQException;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date;
import java.util.List;


/**
 * Created by zdm on 2019/5/16.
 */
public class MqSdkUtil {
    private static final Logger log = LoggerFactory.getLogger(MqSdkUtil.class);
    //    @Value("${ftp.pwd}")
    private static String gateKeeper="QMGR.S60";
    private QueueTools queueTools;
    private MQQueueManager queueManager;


    /**
     * 通过工具类获取队列管理器实例。connect函数的参数为配置文件中队列管理器配置标签名。该实例如果不调用方法进行断开操作可长期保持连接
     * gateKeeper
     *
     * @return
     */
    public MQQueueManager getMQQueueManager(String gateKeeper) throws Exception {
        QueueTools queueTools = new QueueTools();
        MQQueueManager queueManager = null;
        queueManager = queueTools.connect(gateKeeper);
        return queueManager;
    }

    /**
     * 发送请求消息，保存MsgId
     *
     * @return
     * @throws Exception
     */
    public String putMsg(String reqMsg, String xmlNodeName) throws Exception {
        String msgId = queueTools.putMsg(queueManager, xmlNodeName, reqMsg);
        return msgId;
    }

    /**
     * 根据发送时的MsgId提取请求（使用get-wait短期监听提取方式，可自定义超时时间）
     *
     * @param xmlNodeName
     * @param msgId
     * @return
     * @throws Exception
     */
    public String getResp(String xmlNodeName, String msgId) throws Exception {
        //响应数据
        String respMsg = queueTools.getMsgById(queueManager, xmlNodeName, msgId, 3);
        return respMsg;
    }


    /**
     * 返回的响应数据中会包含此次请求的返回数据量和当前消息在返回消息中的顺序编号，进行判断是否还要继续获取
     * @param reqMsg 请求的数据
     * @param xmlNodeName 获取请求节点
     * @param parsingWay 解析方式：1为单个对象，2为数组
     * @param stringList 需要转的字符串
     */
    public static String putReqAndGetResp(String reqMsg,String xmlNodeName,String parsingWay, List<String> stringList) throws Exception{
        QueueTools queueTools = new QueueTools();
        // 队列管理器实例
        MQQueueManager queueManager = null;
        // 消息Id
        String msgId = null;
        // 响应数据
        String respMsg = null;
        try {
            // 连接MQ，获取队列管理器实例，该实例如果不调用方法进行断开操作可长期保持连接。连接函数会自动读取配置文件标签名为“QMGR.SXX”下的配置信息进行连接。，
            queueManager = queueTools.connect(gateKeeper);
            // 发送请求消息
            msgId = queueTools.putMsg(queueManager, xmlNodeName, json2xml(reqMsg,xmlNodeName,"JKZL","123456","S60","S01",stringList));
            // 获取响应消息
            respMsg = queueTools.getMsgById(queueManager, xmlNodeName, msgId, 3);
            if(null==respMsg){
                throw new Exception("获取相应消息失败！reqMsg="+reqMsg);
            }
            return respMsg;
        } catch (MQException e) {
            // 2033表示队列中没有消息
            if (e.reasonCode == 2033) {
            } else {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //断开MQ连接
            if (null != queueManager) {
                try {
                    queueManager.disconnect();
                } catch (MQException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 返回的响应数据中会包含此次请求的返回数据量和当前消息在返回消息中的顺序编号，进行判断是否还要继续获取
     * 请求值为前端拼接的xml字符串
     * @param reqMsg 请求的数据
     * @param xmlNodeName 获取请求节点
     */
    public static String putReqAndGetRespByQueryStr(String reqMsg,String xmlNodeName) throws Exception{
        QueueTools queueTools = new QueueTools();
        // 队列管理器实例
        MQQueueManager queueManager = null;
        log.info("reqMsg"+reqMsg);
        // 消息Id
        String msgId = null;
        // 响应数据
        String respMsg = null;
        try {
            // 连接MQ，获取队列管理器实例，该实例如果不调用方法进行断开操作可长期保持连接。连接函数会自动读取配置文件标签名为“QMGR.SXX”下的配置信息进行连接。，
            queueManager = queueTools.connect(gateKeeper);
            // 发送请求消息
            msgId = queueTools.putMsg(queueManager, xmlNodeName, reqMsg);
            // 获取响应消息
            respMsg = queueTools.getMsgById(queueManager, xmlNodeName, msgId, 1200000000);
            log.info("respMsg=="+reqMsg);
            return respMsg;
        } catch (MQException e) {
            // 2033表示队列中没有消息
            if (e.reasonCode == 2033) {
            } else {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //断开MQ连接
            if (null != queueManager) {
                try {
                    queueManager.disconnect();
                } catch (MQException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }


    //=======================================================封装xml=============================================================================================

    /**
     * JSON(数组)字符串<STRONG>转换</STRONG>成XML字符串
     *@param fid 服务id
     * @param passWord
     * @param userName
     * @param sourceSysCode
     * @param targetSysCode
     * @param jsonString
     * @return
     */
    public static String json2xml(String jsonString,String fid,String passWord,String userName,String sourceSysCode,String targetSysCode, List<String> stringList) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        //是否展示类型
        xmlSerializer.setObjectName("ESBEntry");
        xmlSerializer.setTypeHintsEnabled(false);
        xmlSerializer.setSkipNamespaces(true);
        JSONObject jsonObject=new JSONObject();
        JSONObject accessControl=new JSONObject();
        accessControl.put("Fid",fid);
        accessControl.put("Password",passWord);
        accessControl.put("UserName",userName);
        jsonObject.put("AccessControl",accessControl);

        JSONObject messageHeader=new JSONObject();
        messageHeader.put("Fid",fid);
        messageHeader.put("MsgDate", DateUtil.dateToStr(new Date(),DateUtil.YYYY_MM_DD_HH_MM_SS));
        messageHeader.put("SourceSysCode",sourceSysCode);
        messageHeader.put("TargetSysCode",targetSysCode);
        jsonObject.put("MessageHeader",messageHeader);

        jsonObject.put("MsgInfo",JSONSerializer.toJSON(jsonString));
//{"Fid":"BS15017","Password":[],"UserName":[]},"MessageHeader":{"Fid":"BS15017","MsgDate":"2018-11-21 13:20:40","SourceSysCode":"S60","TargetSysCode":"S01"},"MsgInfo":{"endNum":"20000","Msg":[],"query":{"@compy":"=","@item":"CARD_NO","@splice":"and","@value":"D26818411"},"startNum":"1"}}
        String root="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
        String xmlString=xmlSerializer.write(jsonObject);
        try {
            for (String str:stringList){
                xmlString=xmlString.replace(str+"","'"+str+"'");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlString.replace(root,"");
    }


    //=================================================================解析xml=======================================================================

    /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串
     * XML中Msg为数组
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2jsonArray(String xmlString) throws Exception {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
        if (null != jsonObject) {
            net.sf.json.JSONObject jsonObject1 = (net.sf.json.JSONObject) jsonObject;
            //获取到数组中的CDATA进行再解析
            net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) jsonObject1.get("Msg");
            net.sf.json.JSONArray jsonArray1 = new net.sf.json.JSONArray();
            for (Object object : jsonArray) {
                JSON jsonsub = xmlSerializer.read(object.toString());
                jsonArray1.add(((net.sf.json.JSONObject) jsonsub).get("row"));
            }
            //重新封装到json中
            ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
        }
        return getMsgInfo(json);
    }

    /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串,msg的根节点为row
     * XML中Msg为数组
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2jsonArrayRootRow(String xmlString) throws Exception {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        Object retInfo=  ((JSONObject) json).get("RetInfo");
        Object retCode= ((JSONObject) retInfo).get("RetCode");
        if(retCode.equals("1")){
            //成功
            Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
            net.sf.json.JSONArray jsonArray1 = new net.sf.json.JSONArray();
            if (null != jsonObject) {
                net.sf.json.JSONObject jsonObject1 = (net.sf.json.JSONObject) jsonObject;
                Object objectMsg=jsonObject1.get("Msg");
                if(objectMsg instanceof String){
                    JSON jsonsub = xmlSerializer.read(jsonObject1.get("Msg").toString());
                    jsonArray1.add(jsonsub);
                    //重新封装到json中
                    ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
                }else if(objectMsg instanceof JSONArray){
                    //获取到数组中的CDATA进行再解析
                    net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) jsonObject1.get("Msg");
                    for (Object object : jsonArray) {
                        JSON jsonsub = xmlSerializer.read(object.toString());
                        jsonArray1.add(jsonsub);
                    }
                    //重新封装到json中
                    ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
                }

            }
        }else if(retCode.equals("0")){
            log.info("ERRORMSG=="+ ((JSONObject) retInfo).get("RetCon").toString());
            //重新封装到json中
            ((net.sf.json.JSONObject) json).element("MsgInfo",   ((JSONObject) retInfo).get("RetCon"));
        }
        return getMsgInfo(json);
    }

 /*   *//**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串,msg的根节点为row
     * XML中Msg为数组
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     *//*
    public static String xml2jsonArrayByMsg(String xmlString) throws Exception {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        Object retInfo=  ((JSONObject) json).get("RetInfo");
        Object retCode= ((JSONObject) retInfo).get("RetCode");
        if(retCode.equals("1")) {
            //成功
            Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
            net.sf.json.JSONArray jsonArray1 = new net.sf.json.JSONArray();
            if (null != jsonObject) {
                net.sf.json.JSONObject jsonObject1 = (net.sf.json.JSONObject) jsonObject;
                Object objectMsg=jsonObject1.get("Msg");
                if(objectMsg instanceof String){
                    JSON jsonsub = xmlSerializer.read(jsonObject1.get("Msg").toString());
                    jsonArray1.add(jsonsub);
                    //重新封装到json中
                    ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
                }else if(objectMsg instanceof JSONArray){
                    //获取到数组中的CDATA进行再解析
                    net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) jsonObject1.get("Msg");
                    for (Object object : jsonArray) {
                        JSON jsonsub = xmlSerializer.read(object.toString());
                        jsonArray1.add(jsonsub);
                    }
                    //重新封装到json中
                    ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
                }
            }
        }else if(retCode.equals("0")){
            //重新封装到json中
            ((net.sf.json.JSONObject) json).element("MsgInfo",   ((JSONObject) retInfo).get("RetCon"));
        }
        return getMsgInfo(json);
    }*/

    /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串
     * 其中Msg为一个对象
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2jsonObject(String xmlString) throws Exception {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
        if (null != jsonObject) {
            net.sf.json.JSONObject jsonObject1 = (net.sf.json.JSONObject) jsonObject;
            //获取到数组中的CDATA进行再解析
            JSON jsonsub = xmlSerializer.read((jsonObject1).get("Msg").toString());
            //重新封装到json中
            ((net.sf.json.JSONObject) jsonObject).element("Msg", jsonsub);
        }
        return getMsgInfo(json);
    }

    /**
     * 获取返参的主体信息
     * @param json
     * @return
     * @throws Exception
     */
    public static String getMsgInfo(JSON json)throws Exception{
        JSONObject jsonObjectBak=new JSONObject();

        Object jsonObject= (( net.sf.json.JSONObject) json).get("RetInfo");
        if(null!=jsonObject) {
            net.sf.json.JSONObject jsonObject1 = (net.sf.json.JSONObject) jsonObject;
            jsonObjectBak.element("code", jsonObject1.get("RetCode").toString());
            jsonObjectBak.element("MsgInfo", ((net.sf.json.JSONObject) json).get("MsgInfo").toString());
            return jsonObjectBak.toString();
        }
        return "";
    }

    /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串,msg的根节点为row
     * XML中Msg为数组
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2jsonArrayRootRowMS02003(String xmlString) throws Exception {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        Object retInfo=  ((JSONObject) json).get("RetInfo");
        Object retCode= ((JSONObject) retInfo).get("RetCode");
        if(retCode.equals("1")){
            //成功
            Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
            net.sf.json.JSONArray jsonArray1 = new net.sf.json.JSONArray();
            if (null != jsonObject) {
                net.sf.json.JSONObject jsonObject1 = (net.sf.json.JSONObject) jsonObject;
                Object objectMsg=jsonObject1.get("Msg");
                if(objectMsg instanceof String){
                    JSON jsonsub = xmlSerializer.read(jsonObject1.get("Msg").toString());
                    Object jsonsubBody=  ((JSONObject) jsonsub).get("body");
                    jsonArray1.add(jsonsubBody);
                    //重新封装到json中
                    ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
                }else if(objectMsg instanceof JSONArray){
                    //获取到数组中的CDATA进行再解析
                    net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) jsonObject1.get("Msg");
                    for (Object object : jsonArray) {
                        JSON jsonsub = xmlSerializer.read(object.toString());
                        jsonArray1.add(jsonsub);
                    }
                    //重新封装到json中
                    ((net.sf.json.JSONObject) json).element("MsgInfo", jsonArray1);
                }

            }
        }else if(retCode.equals("0")){
            //重新封装到json中
            ((net.sf.json.JSONObject) json).element("MsgInfo",   ((JSONObject) retInfo).get("RetCon"));
        }
        return getMsgInfo(json);
    }

    /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串,msg的根节点为row
     * XML中Msg为数组
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static JSON xml2jsonArrayRootRowBS16011(String xmlString) throws Exception {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        Object retInfo=  ((JSONObject) json).get("RetInfo");
        Object retCode= ((JSONObject) retInfo).get("RetCode");
        if(retCode.equals("1")){
            //成功
            Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
            ((net.sf.json.JSONObject) json).element("MsgInfo",  jsonObject);
        }else if(retCode.equals("0")){
            //重新封装到json中
            ((net.sf.json.JSONObject) json).element("MsgInfo",   ((JSONObject) retInfo).get("RetCon"));
        }
        return json;
    }


    /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串,msg的根节点为row
     * XML中Msg为数组
     *
     * @param xmlString xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2jsonArrayRootRowBS10144(String xmlString) throws Exception {

        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        log.info("xmlString"+json);
        Object retInfo=  ((JSONObject) json).get("RetInfo");
        Object retCode= ((JSONObject) retInfo).get("RetCode");
        if(retCode.equals("1")){
            //成功
            Object jsonObject = ((net.sf.json.JSONObject) json).get("MsgInfo");
            ((net.sf.json.JSONObject) json).element("MsgInfo",  jsonObject);
            log.info("xmlString===="+json);
        }else if(retCode.equals("0")){
            //重新封装到json中
            ((net.sf.json.JSONObject) json).element("MsgInfo",   ((JSONObject) retInfo).get("RetCon"));
        }
        return getMsgInfo(json);
    }
}

