package com.zzsmart.qomo.kn.cost.manage.plugin.webservice;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//import com.sun.org.apache.xml.internal.serialize.OutputFormat;
//import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.jdom2.Element;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SAPOrderServiceImpl implements SAPOrderService {
    RequestSapXmlData600 request = new RequestSapXmlData600();

    String url;

    public SAPOrderServiceImpl(String url)
    {
        this.url = url;
    }
    public SAPOrderServiceImpl(){
    }

    //全局变量，判断是否输出请求响应报文信息；
    public static boolean openXmlMessage = false;

    /**
     * 调用方法，控制是否输出请求响应报文；
     * true为输出，false为不输出；
     * @param open
     */
    public void printLog(boolean open)
    {
        openXmlMessage = open;
    }

    public boolean checkPrint(boolean checkinput){
        return checkinput;
    }
    /**
     * 用户名密码授权访问webservice规范
     * 新增返回状态标识
     * @param xml
     * @param url
     * @return
     * @throws Exception
     */
    public static String getUPTSoapStreama(String xml,String url) {
        try {
            String soap = xml;
            if (soap == null) {
                return null;
            }

            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            // 然后把Soap请求数据添加到PostMethod中
            RequestEntity requestEntity = new StringRequestEntity(soap, "application/soap+xml", "UTF-8");
            //设置请求头部，否则可能会报 “no SOAPAction header” 的错误
            postMethod.setRequestHeader("SOAPAction","");
            // 设置请求体
            postMethod.setRequestEntity(requestEntity);
            int status = client.executeMethod(postMethod);
            return status+"";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Document parseXmlFile(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static String xmlFormat(String unformattedXml) {
//        try {
//            Document document = parseXmlFile(unformattedXml);
//            OutputFormat format = new OutputFormat(document);
//            format.setLineWidth(65);
//            format.setIndenting(true);
//            format.setIndent(2);
//            Writer out = new StringWriter();
//            XMLSerializer serializer = new XMLSerializer(out, format);
//            serializer.serialize(document);
//            return (out.toString() +"").replace("\n","\r\n");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return unformattedXml;
//    }

    public static String getServerName(String url) {
        try{
            return url.substring(url.indexOf("//") + 2, url.indexOf(":",url.indexOf("//")));
        } catch	(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isEmpty(String str) {

        if (str == null || str.trim().isEmpty() || "null".equals(str)) {
            return true;
        }
        return false;
    }

    /**
     * xml转json
     * @param element
     * @param json
     */
    public static void dom4j2Json(org.dom4j.Element element,JSONObject json){
        //如果是属性
        for(Object o:element.attributes()){
            Attribute attr=(Attribute)o;
            if(!isEmpty(attr.getValue())){
                json.put("@"+attr.getName(), attr.getValue());
            }
        }
        List<org.dom4j.Element> chdEl=element.elements();
        if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
        }

        for(org.dom4j.Element e:chdEl){//有子元素
            if(!e.elements().isEmpty()){//子元素也有子元素
                JSONObject chdjson=new JSONObject();
                dom4j2Json(e,chdjson);
                Object o=json.get(e.getName());
                if(o!=null){
                    JSONArray jsona=null;
                    if(o instanceof JSONObject){//如果此元素已存在,则转为jsonArray
                        JSONObject jsono=(JSONObject)o;
                        json.remove(e.getName());
                        jsona=new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if(o instanceof JSONArray){
                        jsona=(JSONArray)o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                }else{
                    if(!chdjson.isEmpty()){
                        json.put(e.getName(), chdjson);
                    }
                }


            }else{//子元素没有子元素
                for(Object o:element.attributes()){
                    Attribute attr=(Attribute)o;
                    if(!isEmpty(attr.getValue())){
                        json.put("@"+attr.getName(), attr.getValue());
                    }
                }
                if(!e.getText().isEmpty()){
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    public  JSONObject xml2Json(String xmlStr) throws DocumentException {
        org.dom4j.Document doc= DocumentHelper.parseText(xmlStr);
        JSONObject json=new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    @Override
    public JSONObject getOrderState(HashMap hm, String url, String u, String p) {
        // TODO Auto-generated method stub
        String xml = request.getOrderState(hm);
        //System.out.println(xml);
        List<HashMap<String, String>> list = null;
        SoapUtil util = new SoapUtil();

        SoapResult soap = new SoapResult();
        Element root = null;
        String status = null,message = "";
        Map map = null;
        String[] out = null;
        //System.out.println("try之前");
        JSONObject json=new JSONObject();
        try {
//			FileUtil.TextToFile(new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").format(new Date())+"=>105接口：\r\n");
            //System.out.println("getUPSoapStream开始");
            String functions="urn:sap-com:document:sap:soap:functions:mc-style:ZSAP_DSJ_005:ZsapDsj005Request";
            soap = util.getUPSoapStream(xml, url,u,p,functions); //获取返回的报文；
            //System.out.println("getUPSoapStream结束");
            //System.out.println("响应报文："+soap.getContent());


            org.dom4j.Document doc= DocumentHelper.parseText(soap.getContent());
            //JSONObject json=new JSONObject();
            dom4j2Json(doc.getRootElement(),json);

            //System.out.println(json.toString());
            //String responsexml=soap.getContent().replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
            //创建 XMLSerializer对象
            //XMLSerializer xmlSerializer = new XMLSerializer();
            //将xml转为json（注：如果是元素的属性，会在json里的key前加一个@标识）
            //String result = xmlSerializer.read(responsexml).toString();
            //输出json内容
            //System.out.println(result);

            //请求sap响应报文写入到日志文档中记录
//			FileUtil.TextToFile(soap+"\r\n");

            //解析响应报文，状态--返回报文信息
//

//            System.out.println("1："+new Date());
//            root = util.getRootElement(soap.getContent()); //获取报文xml的根节点
//            //System.out.println(root);
//            System.out.println("2："+new Date());
//
//            System.out.println("3："+new Date());
//
//            status = util.getKeyParse(root, "MSGTY");
////            message = util.getKeyParse(root, "MSGTX");
//            System.out.println("status__________"+status);
//            if(status.equals("S")) {
//                //代表获取成功，获取item里的值
//                list = util.getListParse(root, "TOUDA", "item");
//                System.out.println(list.size());
//                //获取返回的报文列表信息
//                if(list.size()>0)
//                {
//                    status = "S";
//                    message = util.getKeyParse(root, "MSGTX");
//                }else{
//                    status = "E";
//                    message = util.getKeyParse(root, "MSGTX");
//                    System.out.println(message);
//                }
//            }else if(status.equals("E") ) {
//                //代表获取失败，无法关闭的订单
//                message = util.getKeyParse(root, "MSGTX");
//            }
//            System.out.println("4："+new Date());
            //message += "\r\n 请求报文："+xml+"\r\n 响应报文："+soap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
//			e.printStackTrace();
            message += " 请求报文解析失败";
        }

        //输出请求响应报文
        //if(openXmlMessage)
        //{
       //     message += "\r\n 请求报文："+xml+"\r\n 响应报文："+soap;
       // }

        //HashMap<String,Object> result = util.sendData(status, message, list, map);

        return json;
    }

    @Override
    public JSONObject getDSJ002(HashMap hm, String url, String u, String p) {
        // TODO Auto-generated method stub
        String xml = request.getDSJ002(hm);
        System.out.println(xml);
        List<HashMap<String, String>> list = null;
        SoapUtil util = new SoapUtil();

        SoapResult soap = new SoapResult();
        Element root = null;
        String status = null,message = "";
        Map map = null;
        String[] out = null;
        //System.out.println("try之前");
        JSONObject json=new JSONObject();
        try {
//			FileUtil.TextToFile(new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").format(new Date())+"=>105接口：\r\n");
            //System.out.println("getUPSoapStream开始");
            String functions="urn:sap-com:document:sap:rfc:functions:ZSAP_DSJ_002:ZSAP_DSJ_002Request";
            soap = util.getUPSoapStream(xml, url,u,p,functions); //获取返回的报文；
            //System.out.println("getUPSoapStream结束");
            System.out.println("响应报文："+soap.getContent());


            org.dom4j.Document doc= DocumentHelper.parseText(soap.getContent());
            //JSONObject json=new JSONObject();
            dom4j2Json(doc.getRootElement(),json);

            //System.out.println(json.toString());
            //String responsexml=soap.getContent().replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
            //创建 XMLSerializer对象
            //XMLSerializer xmlSerializer = new XMLSerializer();
            //将xml转为json（注：如果是元素的属性，会在json里的key前加一个@标识）
            //String result = xmlSerializer.read(responsexml).toString();
            //输出json内容
            //System.out.println(result);

            //请求sap响应报文写入到日志文档中记录
//			FileUtil.TextToFile(soap+"\r\n");

            //解析响应报文，状态--返回报文信息
//

//            System.out.println("1："+new Date());
//            root = util.getRootElement(soap.getContent()); //获取报文xml的根节点
//            //System.out.println(root);
//            System.out.println("2："+new Date());
//
//            System.out.println("3："+new Date());
//
//            status = util.getKeyParse(root, "MSGTY");
////            message = util.getKeyParse(root, "MSGTX");
//            System.out.println("status__________"+status);
//            if(status.equals("S")) {
//                //代表获取成功，获取item里的值
//                list = util.getListParse(root, "TOUDA", "item");
//                System.out.println(list.size());
//                //获取返回的报文列表信息
//                if(list.size()>0)
//                {
//                    status = "S";
//                    message = util.getKeyParse(root, "MSGTX");
//                }else{
//                    status = "E";
//                    message = util.getKeyParse(root, "MSGTX");
//                    System.out.println(message);
//                }
//            }else if(status.equals("E") ) {
//                //代表获取失败，无法关闭的订单
//                message = util.getKeyParse(root, "MSGTX");
//            }
//            System.out.println("4："+new Date());
            //message += "\r\n 请求报文："+xml+"\r\n 响应报文："+soap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
//			e.printStackTrace();
            message += " 请求报文解析失败";
        }

        //输出请求响应报文
        //if(openXmlMessage)
        //{
        //     message += "\r\n 请求报文："+xml+"\r\n 响应报文："+soap;
        // }

        //HashMap<String,Object> result = util.sendData(status, message, list, map);

        return json;
    }

    @Override
    public JSONObject getPDM(HashMap hm, String url, String u, String p){
        // TODO Auto-generated method stub
        String xml = request.getPDM(hm);
        System.out.println(xml);
        List<HashMap<String, String>> list = null;
        SoapUtil util = new SoapUtil();

        SoapResult soap = new SoapResult();
        Element root = null;
        String status = null,message = "";
        Map map = null;
        String[] out = null;
        //System.out.println("try之前");
        JSONObject json=new JSONObject();
        try {
            String functions="urn:sap-com:document:sap:soap:functions:mc-style:ZECC_PDM_MM015:ZeccPdmMm015Request";
            soap = util.getUPSoapStream(xml, url,u,p,functions); //获取返回的报文；
            System.out.println("响应报文："+soap.getContent());


            org.dom4j.Document doc= DocumentHelper.parseText(soap.getContent());
            //JSONObject json=new JSONObject();
            dom4j2Json(doc.getRootElement(),json);

        } catch (Exception e) {
            // TODO Auto-generated catch block
//			e.printStackTrace();
            message += " 请求报文解析失败";
        }



        return json;
    }

    @Override
    public JSONObject getDSJ003(HashMap hm, String url, String u, String p){
        // TODO Auto-generated method stub
        String xml = request.getDSJ003(hm);
        System.out.println(xml);
        List<HashMap<String, String>> list = null;
        SoapUtil util = new SoapUtil();

        SoapResult soap = new SoapResult();
        Element root = null;
        String status = null,message = "";
        Map map = null;
        String[] out = null;
        //System.out.println("try之前");
        JSONObject json=new JSONObject();
        try {
            String functions="urn:sap-com:document:sap:rfc:functions:ZSAP_DSJ_003:ZSAP_DSJ_003Request";
            soap = util.getUPSoapStream(xml, url,u,p,functions); //获取返回的报文；
            System.out.println("响应报文："+soap.getContent());


            org.dom4j.Document doc= DocumentHelper.parseText(soap.getContent());
            //JSONObject json=new JSONObject();
            dom4j2Json(doc.getRootElement(),json);

        } catch (Exception e) {
            // TODO Auto-generated catch block
//			e.printStackTrace();
            message += " 请求报文解析失败";
        }



        return json;
    }

    @Override
    public JSONObject getDSJ004(HashMap hm, String url, String u, String p){
        // TODO Auto-generated method stub
        String xml = request.getDSJ004(hm);
        System.out.println(xml);
        List<HashMap<String, String>> list = null;
        SoapUtil util = new SoapUtil();

        SoapResult soap = new SoapResult();
        Element root = null;
        String status = null,message = "";
        Map map = null;
        String[] out = null;
        //System.out.println("try之前");
        JSONObject json=new JSONObject();
        try {
            String functions="urn:sap-com:document:sap:rfc:functions:ZSAP_DSJ_004:ZSAP_DSJ_004Request";
            soap = util.getUPSoapStream(xml, url,u,p,functions); //获取返回的报文；
            System.out.println("响应报文："+soap.getContent());


            org.dom4j.Document doc= DocumentHelper.parseText(soap.getContent());
            //JSONObject json=new JSONObject();
            dom4j2Json(doc.getRootElement(),json);

        } catch (Exception e) {
            // TODO Auto-generated catch block
//			e.printStackTrace();
            message += " 请求报文解析失败";
        }



        return json;
    }

    @Override
    public JSONObject getOrderState12(HashMap hm, String url, String u, String p) {
        // TODO Auto-generated method stub
        String xml = request.getOrderState12(hm);
        //System.out.println(xml);
        List<HashMap<String, String>> list = null;
        SoapUtil util = new SoapUtil();

        SoapResult soap = new SoapResult();
        Element root = null;
        String status = null,message = "";
        Map map = null;
        String[] out = null;
        //System.out.println("try之前");
        JSONObject json=new JSONObject();
        try {
//			FileUtil.TextToFile(new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").format(new Date())+"=>105接口：\r\n");
            //System.out.println("getUPSoapStream开始");
            String functions="urn:sap-com:document:sap:soap:functions:mc-style:ZSAP_DSJ_005:ZsapDsj005Request";
            soap = util.getUPSoapStream(xml, url,u,p,functions); //获取返回的报文；
            //System.out.println("getUPSoapStream结束");
            //System.out.println("响应报文："+soap.getContent());


            org.dom4j.Document doc= DocumentHelper.parseText(soap.getContent());
            //JSONObject json=new JSONObject();
            dom4j2Json(doc.getRootElement(),json);

            //System.out.println(json.toString());
            //String responsexml=soap.getContent().replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
            //创建 XMLSerializer对象
            //XMLSerializer xmlSerializer = new XMLSerializer();
            //将xml转为json（注：如果是元素的属性，会在json里的key前加一个@标识）
            //String result = xmlSerializer.read(responsexml).toString();
            //输出json内容
            //System.out.println(result);

            //请求sap响应报文写入到日志文档中记录
//			FileUtil.TextToFile(soap+"\r\n");

            //解析响应报文，状态--返回报文信息
//

//            System.out.println("1："+new Date());
//            root = util.getRootElement(soap.getContent()); //获取报文xml的根节点
//            //System.out.println(root);
//            System.out.println("2："+new Date());
//
//            System.out.println("3："+new Date());
//
//            status = util.getKeyParse(root, "MSGTY");
////            message = util.getKeyParse(root, "MSGTX");
//            System.out.println("status__________"+status);
//            if(status.equals("S")) {
//                //代表获取成功，获取item里的值
//                list = util.getListParse(root, "TOUDA", "item");
//                System.out.println(list.size());
//                //获取返回的报文列表信息
//                if(list.size()>0)
//                {
//                    status = "S";
//                    message = util.getKeyParse(root, "MSGTX");
//                }else{
//                    status = "E";
//                    message = util.getKeyParse(root, "MSGTX");
//                    System.out.println(message);
//                }
//            }else if(status.equals("E") ) {
//                //代表获取失败，无法关闭的订单
//                message = util.getKeyParse(root, "MSGTX");
//            }
//            System.out.println("4："+new Date());
            //message += "\r\n 请求报文："+xml+"\r\n 响应报文："+soap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
//			e.printStackTrace();
            message += " 请求报文解析失败";
        }

        //输出请求响应报文
        //if(openXmlMessage)
        //{
        //     message += "\r\n 请求报文："+xml+"\r\n 响应报文："+soap;
        // }

        //HashMap<String,Object> result = util.sendData(status, message, list, map);

        return json;
    }

}
