package com.jojubanking.boot.framework.common.util.xml;

import org.apache.commons.lang3.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.*;

public class XmlUtil {
//    public static void main(String[] args) {
//        Reserve8Vo vo = new Reserve8Vo();
//        System.out.println(getOpAppAppoint(vo));
//    }

    /**
     * 省份证的正则表达式^(\d{15}|\d{17}[\dx])$
     *
     * @param id 省份证号
     * @return 生日（yyyy-MM-dd）
     */
    public static String extractYearMonthDayOfIdCard(String id) {
        String year = null;
        String month = null;
        String day = null;
        //正则匹配身份证号是否是正确的，15位或者17位数字+数字/x/X
        if (id.matches("^\\d{15}|\\d{17}[\\dxX]$")) {
            year = id.substring(6, 10);
            month = id.substring(10, 12);
            day = id.substring(12, 14);
        } else {
            System.out.println("身份证号码不匹配！");
            return null;
        }
        return year + "-" + month + "-" + day;
    }

    // 获取返回的报文统一处理
//    public static Map<String, Object> map = new HashMap<String, Object>();

    public static Map<String, Object> parse(String soap) throws DocumentException {
        //map.clear();
        String soapWeb = StringEscapeUtils.unescapeXml(soap);
        soapWeb = soapWeb.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
        Document doc = DocumentHelper.parseText(soapWeb);// 报文 转成 xml
        Element root = doc.getRootElement();//获取根元素，准备递归解析这个XML树

        Map<String, Object> map = getCodeNC(root);
        return map;
    }

    // 非递归遍历所有的 节点 和 数据
    public static Map<String, Object> getCodeNC(Element root) {
        Map<String, Object> map = new HashMap<String, Object>();

        Stack a = null;
        a = new Stack<>();
        a.push(root);

        if (root.elements().size() == 0 || root.elements() == null) {
            return map;
        }
        //top 是栈顶元素
        Element top = null;
        while (!a.empty()) {
            top = (Element) a.peek();
            a.pop();

            //如果当前跟节点有子节点，找到子节点
            List<Element> list = top.elements();
            int size = top.elements().size();

            for (Element e : list) {
                //遍历每个节点
                if (e.elements().size() > 0) {
                    //对栈顶元素进行反向遍历，入栈
                    a.push((Element) e);
                }
                if (e.elements().size() == 0) {
                    map.put(e.getName(), e.getTextTrim());
                }//如果为叶子节点，那么直接把名称和值放入map
            }
        }

        return map;
    }

//    // 递归遍历所有的 节点 和 数据
//    public static Map<String, Object> getCode(Element root) {
//       // Map<String, Object> map = new HashMap<String, Object>();
//
//        if (root.elements() != null) {
//            List<Element> list = root.elements();//如果当前跟节点有子节点，找到子节点
//            for (Element e : list) {//遍历每个节点
//                if (e.elements().size() > 0) {
//                    getCode(e);//当前节点不为空的话，递归遍历子节点；
//                }
//                if (e.elements().size() == 0) {
//                    map.put(e.getName(), e.getTextTrim());
//                }//如果为叶子节点，那么直接把名称和值放入map
//            }
//        }
//        return map;
//    }
//
    public static List<Map<String, Object>> getPacsRes(String soap, String name) throws DocumentException {
        String res1 = name + "Response";
        String res2 = name + "Result";
        String soapWeb = org.apache.commons.lang.StringEscapeUtils.unescapeXml(soap);
        soapWeb = soapWeb.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
        // 字符串转xml
        Document doc = DocumentHelper.parseText(soapWeb);

        //获取根节点
        Element root = doc.getRootElement();
        Element body = root.element("Body").element(res1).element(res2).element("response");

        Element elresult = body.element("returnresult");
        Element eldata = body.element("data");

        System.out.println("根节点 为　：　" + elresult.element("returncode").getText());

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //判断返回值
        String soapcode = elresult.element("returncode").getText();
        if (soapcode.equals("1")) {
            // 获取Body下的所有子节点

            List<?> bodyChild = eldata.elements();
            for (Iterator<?> it = bodyChild.iterator(); it.hasNext(); ) {
                Map<String, Object> soapMap = new HashMap<String, Object>();
                soapMap.put("returncode", soapcode);

                Element elm1 = (Element) it.next();
                List<?> responseChild = elm1.elements();
                for (Iterator<?> it1 = responseChild.iterator(); it1.hasNext(); ) {
                    Element elm2 = (Element) it1.next();
                    soapMap.put(elm2.getName(), elm2.getTextTrim());
                }

                list.add(soapMap);
            }
        } else {
            Map<String, Object> soapMap = new HashMap<String, Object>();
            soapMap.put("returncode", soapcode);
            soapMap.put("errormsg", elresult.element("errormsg").getText());
            list.add(soapMap);
        }
        return list;
    }

    /**
     * 定时任务解析 xml
     */
    public static List<Map<String, String>> getTasks(String soap) throws DocumentException {
        String soapWeb = StringEscapeUtils.unescapeXml(soap);
        soapWeb = soapWeb.replace("<?xml version=\"1.0\"?>", "");
        Document doc = DocumentHelper.parseText(soapWeb); // 字符串转xml
        Element root = doc.getRootElement();//获取根节点
        Element body = root.element("Body"); // 获取所需节点
        Element response = body.element("queryAppRegistRecordsNewResponse");
        Element result = response.element("queryAppRegistRecordsNewResult");
        Element Response = result.element("Response");

        String Result_Code = Response.elementTextTrim("Result_Code");

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        if (Result_Code.equals("0000")) {
            Element resultData = Response.element("Result_Data");
            Element recordList = resultData.element("Record_List");
            List<Element> elements = recordList.elements();
            Iterator<Element> iterator = elements.iterator();
            while (iterator.hasNext()) {
                Element element = iterator.next();
                Map<String, String> soapMap = new HashMap<String, String>();
                soapMap.put("Result_Code", "0000");
                soapMap.put("HIS_ORDER_NO", element.elementTextTrim("HIS_ORDER_NO")); // 交易流水号
                soapMap.put("REGIST_TYPE", element.elementTextTrim("REGIST_TYPE")); // 预约单状态 1 已退费 0 正常
                soapMap.put("ALLOWREFUNDFLAG", element.elementTextTrim("ALLOWREFUNDFLAG")); // 允许退号标志  N 不允许 Y 允许
                list.add(soapMap);
            }
        } else {
            Map<String, String> soapMap = new HashMap<String, String>();
            soapMap.put("Result_Code", Result_Code);
            soapMap.put("Error_Msg", Response.elementTextTrim("Error_Msg"));
            list.add(soapMap);
        }
        return list;
    }

    /**
     * 查询解析xml
     */

    public static List<Map<String, Object>> getDeptQueryXml(String resp1, String resp2, String soap) throws DocumentException {
        String soapWeb = StringEscapeUtils.unescapeXml(soap);
        soapWeb = soapWeb.replace("<?xml version=\"1.0\"?>", "");
        Document doc = DocumentHelper.parseText(soapWeb); // 字符串转xml
        Element root = doc.getRootElement();//获取根节点
        Element body = root.element("Body"); // 获取所需节点
        Element response = body.element(resp1);
        Element result = response.element(resp2);
        Element Response = result.element("Response");

        String Result_Code = Response.elementTextTrim("Result_Code");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (Result_Code.equals("0000")) {
            Element resultData = Response.element("Result_Data");
            Element recordList = resultData.element("Record_List");
            List<Element> elements = recordList.elements();
            Iterator<Element> iterator = elements.iterator();
            while (iterator.hasNext()) {
                Element element = iterator.next();
                Map<String, Object> soapMap = new HashMap<String, Object>();
                soapMap.put("Result_Code", "0000");
                soapMap.put("DEPT_CODE", element.elementTextTrim("DEPT_CODE"));
                soapMap.put("DEPT_NAME", element.elementTextTrim("DEPT_NAME"));
                soapMap.put("IS_ONLINE", element.elementTextTrim("IS_ONLINE"));
                list.add(soapMap);
            }
        } else {
            Map<String, Object> soapMap = new HashMap<String, Object>();
            soapMap.put("Result_Code", Result_Code);
            soapMap.put("Error_Msg", Response.elementTextTrim("Error_Msg"));
            list.add(soapMap);
        }
        return list;
    }

    public static List<Map<String, Object>> getHidsQueryXml(String resp1, String resp2, String soap) throws DocumentException {
        String soapWeb = StringEscapeUtils.unescapeXml(soap);
        soapWeb = soapWeb.replace("<?xml version=\"1.0\"?>", "");
        Document doc = DocumentHelper.parseText(soapWeb); // 字符串转xml
        Element root = doc.getRootElement();//获取根节点
        Element body = root.element("Body"); // 获取所需节点
        Element response = body.element(resp1);
        Element result = response.element(resp2);
        Element Response = result.element("Response");

        String Result_Code = Response.elementTextTrim("Result_Code");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (Result_Code.equals("0000")) {
            Element resultData = Response.element("Result_Data");
            Element recordList = resultData.element("Record_List");
            List<Element> elements = recordList.elements();
            Iterator<Element> iterator = elements.iterator();
            while (iterator.hasNext()) {
                Element element = iterator.next();
                Map<String, Object> soapMap = new HashMap<String, Object>();
                soapMap.put("Result_Code", "0000");
                soapMap.put("HID", element.elementTextTrim("HID"));
                soapMap.put("DEPT_CODE", element.elementTextTrim("DEPT_CODE"));
                soapMap.put("DOCTOR_CODE", element.elementTextTrim("DOCTOR_CODE"));
                soapMap.put("DOCTOR_NAME", element.elementTextTrim("DOCTOR_NAME"));
                soapMap.put("CLINIC_DATE", element.elementTextTrim("CLINIC_DATE"));
                soapMap.put("HB_TIME", element.elementTextTrim("HB_TIME"));
                soapMap.put("CLINIC_DURATION", element.elementTextTrim("CLINIC_DURATION"));
                soapMap.put("REGISTERED_FEE", element.elementTextTrim("REGISTERED_FEE"));
                soapMap.put("PHARMACY_FEE", element.elementTextTrim("PHARMACY_FEE"));
                soapMap.put("DIAG_FEE", element.elementTextTrim("DIAG_FEE"));
                soapMap.put("IS_ONLINE", element.elementTextTrim("IS_ONLINE"));
                soapMap.put("HB_TYPE", element.elementTextTrim("HB_TYPE"));
                list.add(soapMap);
            }
        } else {
            Map<String, Object> soapMap = new HashMap<String, Object>();
            soapMap.put("Result_Code", Result_Code);
            soapMap.put("Error_Msg", Response.elementTextTrim("Error_Msg"));
            list.add(soapMap);
        }
        return list;
    }
}
