package com.yfd.platform.component.nettyclient;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class MyXmlUtil {

    public static String getXml(String SendCode, String ReceiveCode, String Type, String Command, String Code, String jsonstr){
        StringBuilder Xml = new StringBuilder(2000);
        Xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        Xml.append("<PatrolHost>\n");
        Xml.append("<SendCode>").append(SendCode).append("</SendCode>\n");
        Xml.append("<ReceiveCode>").append(ReceiveCode).append("</ReceiveCode>\n");
        Xml.append("<Type>").append(Type).append("</Type>\n");
        Xml.append("<Command>").append(Command).append("</Command>\n");
        Xml.append("<Code>").append(Code).append("</Code>\n");
        Xml.append("<Time>").append(DateUtil.now()).append("</Time>\n");
        Xml.append("<Items>\n");
        if (JSONUtil.isTypeJSONArray(jsonstr)) {
            JSONArray jsonArray = JSONUtil.parseArray(jsonstr);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Xml.append("<Item ");
                for (String key : jsonObject.keySet()) {
                    String value = jsonObject.getStr(key);
                    Xml.append(key).append("=\"").append(value).append("\" ");
                }
                Xml.append("/>\n");
            }
        }
        if (JSONUtil.isTypeJSONObject(jsonstr)) {
            JSONObject jsonObject = JSONUtil.parseObj(jsonstr);
            Xml.append("<Item ");
            for (String key : jsonObject.keySet()) {
                String value = jsonObject.getStr(key);
                Xml.append(key).append("=\"").append(value).append("\" ");
            }
            Xml.append("/>\n");
        }
        Xml.append("</Items>\n");
        Xml.append("</PatrolHost>");
        return Xml.toString();
    }

    /**********************************
     * 用途说明: 将xml转成Map
     * 参数说明 xml xml数据
     * 返回值说明: java.util.Map<java.lang.String,java.lang.Object>
     ***********************************/
    public static Map<String, Object> xmlToMap(String xml) throws ParserConfigurationException, IOException,
            SAXException {
        Map<String, Object> map = XmlUtil.xmlToMap(xml);
        return xmlToMap(map, xml, "Items", "Item");
    }

    /**********************************
     * 用途说明: 将xmlModel转成Map
     * 参数说明 xml xml数据
     * 返回值说明: java.util.Map<java.lang.String,java.lang.Object>
     ***********************************/
    public static Map<String, Object> xmlModelToMap(String xml) throws ParserConfigurationException, IOException,
            SAXException {
        Map<String, Object> map = new HashMap<>();
        return xmlToMap(map, xml, "Device_Model", "Item");
    }

    /**********************************
     * 用途说明: 将xml中的属性解析到map
     * 参数说明 xml xml数据
     * 返回值说明: java.util.Map<java.lang.String,java.lang.Object>
     ***********************************/
    public static Map<String, Object> xmlToMap(Map<String, Object> map, String xml, String element, String nodeName) throws ParserConfigurationException, IOException, SAXException {
        // 创建XML解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        Element itemsElement = (Element) doc.getElementsByTagName(element).item(0);
        NodeList itemNodes = itemsElement.getElementsByTagName(nodeName);

        // 存放Item数据的集合
        List<Map<String, String>> itemDataList = new ArrayList<>();

        // 遍历所有Items下的Item标签
        for (int i = 0; i < itemNodes.getLength(); i++) {
            // 获取Item
            Element itemElement = (Element) itemNodes.item(i);
            NamedNodeMap attributes = itemElement.getAttributes();

            // 存放Item中值的集合
            Map<String, String> itemData = new HashMap<>();
            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                itemData.put(attribute.getNodeName(), attribute.getNodeValue());
            }

            itemDataList.add(itemData);
        }
        map.put(element, itemDataList);
        return map;
    }

    /**********************************
     * 用途说明: 读取xml文件中的内容
     * 参数说明 filePath 文件路径
     * 返回值说明: java.lang.String
     ***********************************/
    public static String readXmlFileContent(String filePath) {
        try {
            StringBuilder xmlContent = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                xmlContent.append(line);
            }
            bufferedReader.close();
            return xmlContent.toString();
        } catch (IOException e) {
            log.error(e.getMessage());;
        }
        return "";
    }
}
