package com.lantone.qc.trans.taizhou.util;

import com.google.common.collect.Maps;
import com.lantone.qc.pub.util.StringUtil;
import com.lantone.qc.trans.comsis.XmlUtil;
import com.lantone.qc.trans.util.http.db.DBUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: xml解析工具
 * @author: rengb
 * @time: 2020/3/28 14:23
 */
public class TzXmlUtil {

    /**
     * getText()获取当前节点的文本内容，getStringValue()获取所有子节点拼接后的文本内容
     *
     * @param xml
     * @return
     */

    public static Map<String, String> getXmlToMapForTZ(String xml) {
        Map<String, String> retMap = Maps.newLinkedHashMap();
        try {
            Document doc = DocumentHelper.parseText(XmlUtil.xmlErrorCorrection(xml));
            List<Element> emrTermElements = doc.getRootElement().element("TermList").elements("EMR-TERM");
            String ename, setnomark, text;
            for (Element emrTermElement : emrTermElements) {
                ename = emrTermElement.attributeValue("ename");
                if (StringUtil.isBlank(ename)) {
                    continue;
                }
                ename = StringUtil.removeBlank(ename);
                setnomark = emrTermElement.attributeValue("setnomark");
                setnomark = setnomark == null ? "" : setnomark;
                text = emrTermElement.getStringValue().trim();
                if (StringUtil.isBlank(retMap.get(ename))) {
                    if (StringUtil.isBlank(text)) {
                        retMap.put(ename, setnomark);
                    } else {
                        retMap.put(ename, text);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return XmlUtil.correctMapOfXml(retMap);
    }

    /**
     * getText()获取当前节点的文本内容，getStringValue()获取所有子节点拼接后的文本内容
     * 需要转义
     *
     * @param xml
     * @return
     */

    public static Map<String, String> getXmlToMapForTZWithReplace(String xml) {
        Map<String, Object> res = getReplace(xml);
        String contentReplace = (String) res.get("content");
        Map<String, String> sourceMap = TzXmlUtil.getXmlToMapForTZ(contentReplace);
        Boolean replace = (Boolean) res.get("repFlag"); // 获取是否要替换的标识
        if (replace) {
            Map<String, String> map = (Map) res.get("replaceMap");
            for (String key : sourceMap.keySet()) {
                String value = sourceMap.get(key);
                if (StringUtil.isNotBlank(value)) {
                    for (String key2 : map.keySet()) {
                        value = value.replaceAll(key2, map.get(key2));
                        sourceMap.put(key, value);
                    }
                }
            }
        }
        return sourceMap;
    }


    /**
     * @param content
     * @return
     */
    public static Map<String, Object> getReplace(String content) {
        Map<String, Object> res = new HashMap<>();
        List<String> cutWord = new ArrayList<>();
        List<String> res1 = new ArrayList<>(); // 包含/的标签</name>
        List<String> res2 = new ArrayList<>();  // 不包含/的标签<name>
        Map<String, String> replaceMap = new HashMap<>();

        String pattern = "<.*?>";
        // 按指定模式在字符串查找

        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(content);
        while (m.find()) {
            String msg = m.group();
            if (!msg.contains("=")) {
                cutWord.add(msg);
            }
        }
        // 分离<name> </name>这样的标签
        for (String str : cutWord) {
            if (str.contains("/")) {
                res1.add(str.replaceAll("/", ""));
            } else {
                res2.add(str);
            }
        }

        // 如果未找到匹配的标签，就表示是内容，先转义 < ，并记录到map中
        for (String key : res2) {
            if (!res1.contains(key)) {
                replaceMap.put("#####" + key.substring(1), key);
                content = content.replaceAll(key, "#####" + key.substring(1));
            }
        }
        res.put("content", content);
        res.put("replaceMap", replaceMap);
        // 添加是否有替换的标识
        if (replaceMap.size() > 0) {
            res.put("repFlag", true);
        } else {
            res.put("repFlag", false);
        }
        return res;
    }

    /**
     * 测试入口
     *
     * @param args
     */
    public static void main(String[] args) {

        String case_number = "547209_3";
        String mode_id = "4";
        String nodePath = "//DocObjContent";
        try {
            Connection connection = DBUtil.getConnection();
            Statement st = connection.createStatement();
            ResultSet rs = null;
            //执行查询
            String sql = "select mode_id, origin_text from qc_model_mapping where case_number='" + case_number + "' and mode_id='" + mode_id + "' order by id";
            rs = st.executeQuery(sql);
            //遍历
            while (rs.next()) {
                String context = rs.getString("origin_text");
                //                Map<String, String> sourceMap = CxXmlUtil.firstLevelNodeValue(nodePath, context);
                Map<String, String> sourceMap = TzXmlUtil.getXmlToMapForTZ(context);
                for (String key : sourceMap.keySet()) {
                    System.out.println("\"" + key + "=\",");
                }
                break;
            }
            //进行资源释放
            DBUtil.release(connection, st, rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}