package com.saye.hrs.commons.webservice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import com.saye.hrs.commons.getBean.BeanUtil;
import com.saye.hrs.mapper.system.LoggerMapper;
import com.saye.hrs.service.system.LoggerService;


public class WSUtil {

	private static final Logger logger = LoggerFactory.getLogger(WSUtil.class);
	public static RestTemplate restTemplate = new RestTemplate();
	/** 调用webservice接口
     * @param url
     * @param tranCode
     * @param inputXml
     * @return
     */
    public static HashMap<String,String> webserviceRequest(String url, String tranCode, String inputXml) {
    	logger.info("请求参数----------"+inputXml);
    	HashMap<String,String> resultMap=new HashMap<>();
        String errCode="0";
        String errMsg="";
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
            // 请求类型ContentType text/xml;charset=UTF-8
            headers.setContentType(type);

            //请求数据体
            StringBuffer soapRequestData = new StringBuffer("");
            soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:kws=\"http://www.winning.com.cn/KWS/\">");
            soapRequestData.append("<soapenv:Header/>");
            soapRequestData.append("<soapenv:Body>");
            soapRequestData.append("<kws:WebBusiness>");
            soapRequestData.append("<kws:TranCode>");

            //交易码
            soapRequestData.append(tranCode);

            soapRequestData.append("</kws:TranCode>");
            soapRequestData.append("<kws:InXml>");

            //<>符号要转码
            inputXml=inputXml.replaceAll("<","&lt;");
            inputXml=inputXml.replaceAll(">","&gt;");

            soapRequestData.append(inputXml);

            soapRequestData.append("</kws:InXml>");
            soapRequestData.append("</kws:WebBusiness>");
            soapRequestData.append("</soapenv:Body>");
            soapRequestData.append("</soapenv:Envelope>");

            // 请求
            HttpEntity<String> request = new HttpEntity<String>(soapRequestData + "", headers);

            // 返回结果
            String str = restTemplate.postForObject(url, request, String.class);
            logger.info("返回结果----------"+str);
            Document document= DocumentHelper.parseText(str);
            Element rootElt = document.getRootElement();

            //解析
            Iterator body = rootElt.elementIterator("Body");
            Element recordEless = (Element) body.next();

            Iterator callHisResponse = recordEless.elementIterator("WebBusinessResponse");
            Element hisResponse = (Element) callHisResponse.next();

            Iterator callHisResult = hisResponse.elementIterator("OutXml");
            Element hisResult = (Element)callHisResult.next();

            String text = hisResult.getText();

            resultMap.put("outXml",text);
        } catch (Exception e) {
        	logger.info("返回结果异常----------"+e.toString());
            errCode="999";
            errMsg=e.getMessage();
        }
        resultMap.put("errCode",errCode);
        resultMap.put("errMsg",errMsg);
        return resultMap;
    }
    
    /**
     * @description 门诊充值
     */
	public static HashMap<Object, Object> mzRecharge(String patid, String czje, String czlx, String cardno,
			String cardtype, String czyh, String zzjjylsh, String czlsh, String tradeNo, String outerOrderNo,
			String innerOrderNo, String paytype) throws Exception{

        String errMsg = "";
        List<HashMap<Object,Object>> list = new ArrayList<>();
        String inputXml = "<request><partner>320582467223232</partner><sign></sign><timestamp>20170704000513</timestamp>" +
                "<operid>01</operid><password></password><kfsdm></kfsdm>" +
                "<params><patid>"+patid+"</patid>" +  	 //病人id
                "<czje>"+czje+"</czje>" +				 //充值金额
                "<czlx>"+czlx+"</czlx>" +				 //1 自助机现金，4 软 POS 戒扫码付
                "<cardno>"+cardno+"</cardno>" +			 //卡号
                "<cardtype>"+cardtype+"</cardtype>" +	 //卡类型：1、磁卡 2、保障卡 3、IC卡	
                "<czyh>"+czyh+"</czyh>" +				 //操作员号
                "<zzjjylsh>"+zzjjylsh+"</zzjjylsh>" +	 //自助机交易流水号,902 接口返回，非卫宁付可为空
                "<czlsh>"+czlsh+"</czlsh>" +			 //充值流水号，每次交易必须唯一
                "<tradeNo>"+tradeNo+"</tradeNo>" +		 //三方支付流水号
                "<outerOrderNo>"+outerOrderNo+"</outerOrderNo>" +				 //商户订单号（商户传给支付平台的单据号，卫宁付和 zzjjylsh 相同）
                "<innerOrderNo>"+innerOrderNo+"</innerOrderNo>" +				 //平台订单号	
                "<paytype>"+paytype+"</paytype>" +			 //支付方式（卫宁支付平台，8:支付宝 9:微信，其他支付方式如软POS，由 HIS 分配）
                "</params></request>";
        HashMap<String,String> map = webserviceRequest("http://168.168.0.23:10062/KWSService.asmx?wsdl","501",inputXml);
        LoggerService log = BeanUtil.getBean(LoggerService.class);
        HashMap<Object,Object> hisMap = new HashMap<Object,Object>();
        hisMap.put("title", "门诊充值");
        hisMap.put("requestContent", inputXml);
        hisMap.put("responseContent", map.get("outXml"));
        log.addHisLog(hisMap);
        String errCode = map.get("errCode");
        if("0".equals(errCode)){
            String outXml = map.get("outXml");
            Document document= DocumentHelper.parseText(outXml);

            Element rootElt = document.getRootElement();

            Iterator iterator = rootElt.elementIterator();

            Element codeElm = (Element) iterator.next();
            Element msgElm = (Element) iterator.next();

            errCode = codeElm.getText();
            errMsg = msgElm.getText();
           
            
            if ("0".equals(errCode)){

                Element Items = (Element) iterator.next();

                Iterator itemIterator = Items.elementIterator();
            	while (itemIterator.hasNext()){
                	
                    HashMap<Object,Object> addMap=new HashMap<>();
                    Element item = (Element) itemIterator.next();
                    //
                    Element lshEl = item.element("lsh");
                    String lsh = lshEl==null?"":lshEl.getText();
                    //
                    Element lrrqEl = item.element("lrrq");
                    String lrrq = lrrqEl==null?"":lrrqEl.getText();
                    //
                    Element yjyeEl = item.element("yjye");
                    String yjye = yjyeEl==null?"":yjyeEl.getText();
                    
                    Element kyjlshEl = item.element("kyjlsh");
                    String kyjlsh = kyjlshEl==null?"":kyjlshEl.getText();

                    Element kyjjeEl = item.element("kyjje");
                    String kyjje = kyjjeEl==null?"":kyjjeEl.getText();

                    Element kyjzffsEl = item.element("kyjzffs");
                    String kyjzffs = kyjzffsEl==null?"":kyjzffsEl.getText();

                    addMap.put("lsh",lsh);
                    addMap.put("lrrq",lrrq);
                    addMap.put("yjye",yjye);
                    addMap.put("kyjlsh",kyjlsh);
                    addMap.put("kyjje",kyjje);
                    addMap.put("kyjzffs",kyjzffs);
                    list.add(addMap);
                }
            }
        }
        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("list",list);
        resultMap.put("errCode",errCode);
        resultMap.put("errMsg",errMsg);
        return resultMap;
	}
	
	/** 获取账户日志
     * @param
     * @return
     */
    public static HashMap<Object,Object> getAccountRecord(String ksrq, String jsrq) throws DocumentException {

        List<HashMap<Object,Object>> list = null;
        String inputXml = "<request><partner>320582467223232</partner><sign></sign><timestamp>20170704000513</timestamp>" +
                "<operid>01</operid><password></password><kfsdm></kfsdm>" +
                "<params><ksrq>"+ksrq+"</ksrq>" +  //开始日期
                "<jsrq>"+jsrq+"</jsrq>" +          //结束日期
                "<czyh>"+0421+"</czyh>" +          //类别
                "</params></request>";
        HashMap<String,String> map = webserviceRequest("http://168.168.0.23:10062/KWSService.asmx?wsdl","701",inputXml);
        String errCode = map.get("errCode");
        String errMsg = map.get("errMsg");
        if("0".equals(errCode)){
            String outXml = map.get("outXml");
            Document document= DocumentHelper.parseText(outXml);

            Element rootElt = document.getRootElement();

            Iterator iterator = rootElt.elementIterator();

            Element codeElm = (Element) iterator.next();
            Element msgElm = (Element) iterator.next();

            errCode = codeElm.getText();
            errMsg = msgElm.getText();

            if ("0".equals(errCode)){
                list = new ArrayList<>();
                Element Items = (Element) iterator.next();

                Iterator itemIterator = Items.elementIterator();

                while (itemIterator.hasNext()){
                    HashMap<Object,Object> addMap=new HashMap<>();
                    Element item = (Element) itemIterator.next();

                    Element patidEl = item.element("patid");
                    String patid = patidEl==null?"":patidEl.getText();

                    Element jyjeEl = item.element("jyje");
                    String jyje = jyjeEl==null?"":jyjeEl.getText();

                    Element zflshEl = item.element("zflsh");
                    String zflsh = zflshEl==null?"":zflshEl.getText();

                    Element jyrqEl = item.element("jyrq");
                    String jyrq = jyrqEl==null?"":jyrqEl.getText();

                    Element jylxEl = item.element("jylx");
                    String jylx = jylxEl==null?"":jylxEl.getText();
                    
                    Element czyhEl = item.element("czyh");
                    String czyh = czyhEl==null?"":czyhEl.getText();
                    
                    Element tyjeEl = item.element("tyje");
                    String tyje = tyjeEl==null?null:tyjeEl.getText();
                    addMap.put("patid",patid);
                    addMap.put("jyje",jyje);
                    addMap.put("zflsh",zflsh);
                    addMap.put("jyrq",jyrq);
                    addMap.put("jylx",jylx);
                    addMap.put("czyh",czyh);
                    addMap.put("tyje",tyje);
                    list.add(addMap);
                }
            }
        }
        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("list",list);
        resultMap.put("errCode",errCode);
        resultMap.put("errMsg",errMsg);
        return resultMap;
    }

    /**
     * 住院充值
     * @return
     */
    public static HashMap<Object, Object> zyRecharge(String patid, String czje, String czlx, String cardno,
                                                     String cardtype, String czyh, String zzjjylsh, String czlsh, String tradeNo, String outerOrderNo,
                                                     String innerOrderNo, String paytype) throws Exception {
        String errMsg = "";
        List<HashMap<Object,Object>> list = new ArrayList<>();
        String inputXml = "<request><partner>320582467223232</partner><sign></sign><timestamp>20170704000513</timestamp>" +
                "<operid>01</operid><password></password><kfsdm></kfsdm>" +
                "<params><patid>"+patid+"</patid>" +  	 //病人id
                "<czje>"+czje+"</czje>" +				 //充值金额
                "<czlx>"+czlx+"</czlx>" +				 //1 自助机现金，4 软 POS 戒扫码付
                "<cardno>"+cardno+"</cardno>" +			 //卡号
                "<cardtype>"+cardtype+"</cardtype>" +	 //卡类型：1、磁卡 2、保障卡 3、IC卡
                "<czyh>"+czyh+"</czyh>" +				 //操作员号
                "<zzjjylsh>"+zzjjylsh+"</zzjjylsh>" +	 //自助机交易流水号,902 接口返回，非卫宁付可为空
                "<czlsh>"+czlsh+"</czlsh>" +			 //充值流水号，每次交易必须唯一
                "<tradeNo>"+tradeNo+"</tradeNo>" +		 //三方支付流水号
                "<outerOrderNo>"+outerOrderNo+"</outerOrderNo>" +				 //商户订单号（商户传给支付平台的单据号，卫宁付和 zzjjylsh 相同）
                "<innerOrderNo>"+innerOrderNo+"</innerOrderNo>" +				 //平台订单号
                "<paytype>"+paytype+"</paytype>" +			 //支付方式（卫宁支付平台，8:支付宝 9:微信，其他支付方式如软POS，由 HIS 分配）
                "</params></request>";
        HashMap<String,String> map = webserviceRequest("http://168.168.0.23:10062/KWSService.asmx?wsdl","501",inputXml);
        LoggerService log = BeanUtil.getBean(LoggerService.class);
        HashMap<Object,Object> hisMap = new HashMap<Object,Object>();
        hisMap.put("title", "住院充值");
        hisMap.put("requestContent", inputXml);
        hisMap.put("responseContent", map.get("outXml"));
        log.addHisLog(hisMap);
        String errCode = map.get("errCode");
        if("0".equals(errCode)){
            String outXml = map.get("outXml");
            Document document= DocumentHelper.parseText(outXml);

            Element rootElt = document.getRootElement();

            Iterator iterator = rootElt.elementIterator();

            Element codeElm = (Element) iterator.next();
            Element msgElm = (Element) iterator.next();

            errCode = codeElm.getText();
            errMsg = msgElm.getText();


            if ("0".equals(errCode)){

                Element Items = (Element) iterator.next();

                Iterator itemIterator = Items.elementIterator();
                while (itemIterator.hasNext()){

                    HashMap<Object,Object> addMap=new HashMap<>();
                    Element item = (Element) itemIterator.next();
                    //
                    Element lshEl = item.element("lsh");
                    String lsh = lshEl==null?"":lshEl.getText();
                    //
                    Element lrrqEl = item.element("lrrq");
                    String lrrq = lrrqEl==null?"":lrrqEl.getText();
                    //
                    Element yjyeEl = item.element("yjye");
                    String yjye = yjyeEl==null?"":yjyeEl.getText();

                    Element kyjlshEl = item.element("kyjlsh");
                    String kyjlsh = kyjlshEl==null?"":kyjlshEl.getText();

                    Element kyjjeEl = item.element("kyjje");
                    String kyjje = kyjjeEl==null?"":kyjjeEl.getText();

                    Element kyjzffsEl = item.element("kyjzffs");
                    String kyjzffs = kyjzffsEl==null?"":kyjzffsEl.getText();

                    addMap.put("lsh",lsh);
                    addMap.put("lrrq",lrrq);
                    addMap.put("yjye",yjye);
                    addMap.put("kyjlsh",kyjlsh);
                    addMap.put("kyjje",kyjje);
                    addMap.put("kyjzffs",kyjzffs);
                    list.add(addMap);
                }
            }
        }
        HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
        resultMap.put("list",list);
        resultMap.put("errCode",errCode);
        resultMap.put("errMsg",errMsg);
        return resultMap;
    }
}
