package org.jeecg.modules.stm.baosong.controller;

import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.stm.baosong.entity.BaosongTask;
import org.jeecg.modules.stm.baosong.entity.BaosongTpl;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreateXmlFile {
    private BaosongTpl baosongTpl = null;
    private BaosongTask baosongTask = null;
    private String fillUserNames = "";
    public CreateXmlFile(BaosongTpl baosongTpl, BaosongTask baosongTask,String fillUserNames) {
        this.baosongTpl = baosongTpl;
        this.baosongTask = baosongTask;
        this.fillUserNames = fillUserNames;
    }
    public void createXml (List<Map<String,Object>> dataList, String filePath) {
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            // 用于存储已经创建的节点
            Map<String, Map<Integer, Element>> pcodeRindGroupMap = new HashMap<>();
            String root = this.baosongTpl.getCode();
            Map<String,String> codeMapPcode = getParentCodeMap(dataList);

            Map<String,Map<String,Object>> codeMapObject = getParentObjectMap(dataList);
            // 创建根元素
            Comment rootComment = doc.createComment(baosongTpl.getNm());
            doc.appendChild(rootComment);
            root = root.replace("-","_");
            Element rootElement = doc.createElement(root);
            doc.appendChild(rootElement);
            createFillUser(doc,rootElement);
            for (int i = 0; i < dataList.size(); i++) {
                Map<String,Object> tmpMap = dataList.get(i);
                String pcode = tmpMap.get("pcode").toString();
                String code = tmpMap.get("code").toString();
                String content = tmpMap.get("content")==null?"":tmpMap.get("content").toString();
                String strComment = tmpMap.get("title")==null?null:tmpMap.get("title").toString();
                int rind = 1;
                if(tmpMap.get("rind")!=null) {
                    rind = Integer.valueOf(tmpMap.get("rind").toString());
                }
                String parentPcode = codeMapPcode.get(pcode);
                String currentPcode = pcode;
                Element parentElement = null;
                if(parentPcode==null||parentPcode.equals("null")) {
                    continue;
                }
                if(!parentPcode.equals(root)){
                    Map<String,Object>  pObject = codeMapObject.get(pcode);
                    String strTitle = pObject.get("title").toString();
                    parentElement = getOrCreateParentElement(doc, rootElement, parentPcode,strTitle);

                } else {
                    parentElement = rootElement;
                }
                // 获取或创建 pcode 对应的分组
                Map<Integer, Element> rindGroupMap = pcodeRindGroupMap.get(currentPcode);
                if (rindGroupMap == null) {
                    rindGroupMap = new HashMap<>();
                    pcodeRindGroupMap.put(currentPcode, rindGroupMap);
                }

                // 获取或创建 rind 分组节点
                Element rindGroupElement = rindGroupMap.get(rind);
                if (rindGroupElement == null) {
                    Map<String,Object>  pObject = codeMapObject.get(pcode);
                    String strTitle = pObject.get("title").toString();
                    Comment comment = doc.createComment(strTitle);
                    rindGroupElement = doc.createElement(currentPcode);
                    parentElement.appendChild(comment);
                    parentElement.appendChild(rindGroupElement);
                    rindGroupMap.put(rind, rindGroupElement);
                }

                if(strComment!=null) {
                    Comment comment = doc.createComment(strComment);
                    rindGroupElement.appendChild(comment);
                }
                // 创建当前节点
                Element currentElement = doc.createElement(code);
                currentElement.setTextContent(content);

                rindGroupElement.appendChild(currentElement);
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);
            System.out.println("XML 文件生成成功！");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取或创建父节点
    private static Element getOrCreateParentElement(Document doc, Element rootElement, String parentPcode,String strComment) {
        // 假设父节点是直接挂在根节点下的
        Element parentElement = (Element) rootElement.getElementsByTagName(parentPcode).item(0);
        if (parentElement == null) {
            try {
                if(strComment!=null) {
                    Comment comment = doc.createComment(strComment);
                    rootElement.appendChild(comment);
                }
                parentElement = doc.createElement(parentPcode);
                rootElement.appendChild(parentElement);
            } catch (Exception e) {
                System.out.println(parentPcode);
            }

        }
        return parentElement;
    }

    private static Map<String,String> getParentCodeMap(List<Map<String,Object>> dataList) {
        Map<String,String> retMap = new HashMap<>();
        for(Map<String,Object> tmpMap:dataList) {
            String code = tmpMap.get("code").toString();
            String pcode = tmpMap.get("pcode").toString();
            retMap.put(code,pcode);
        }
        return retMap;
    }
    private static Map<String,Map<String,Object>> getParentObjectMap(List<Map<String,Object>> dataList) {
        Map<String,Map<String,Object>> retMap = new HashMap<>();
        for(Map<String,Object> tmpMap:dataList) {
            String code = tmpMap.get("code").toString();
            retMap.put(code,tmpMap);
        }
        return retMap;
    }

    //创建填写用户、填报时间、填报电话等信息
    private  void createFillUser(Document doc, Element parentElement) {

        Element fillinDept = doc.createElement("FILLIN_DEPT");
        fillinDept.setTextContent(this.baosongTask.getRespDepart());
        parentElement.appendChild(fillinDept);

        Element fillinDate = doc.createElement("FILLIN_DATE");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = DateUtils.date2Str(this.baosongTask.getEnterDate(),sdf);
        fillinDate.setTextContent(strDate);
        parentElement.appendChild(fillinDate);

        Element fillinPerson = doc.createElement("FILLIN_PERSON");
        fillinPerson.setTextContent(this.fillUserNames);
        parentElement.appendChild(fillinPerson);

        Element telephone = doc.createElement("TELEPHONE");
        telephone.setTextContent(this.baosongTask.getEnterTel());
        parentElement.appendChild(telephone);

        Element resPerson = doc.createElement("RES_PERSON");
        resPerson.setTextContent(this.baosongTask.getRespUser());
        parentElement.appendChild(resPerson);

        Element jiaoyanwei = doc.createElement("jiaoyanwei");
        jiaoyanwei.setTextContent("0");
        parentElement.appendChild(jiaoyanwei);

        Element isempty = doc.createElement("isempty");
        isempty.setTextContent("yes");
        parentElement.appendChild(isempty);

        Element itTitle = doc.createElement("itTitle");
        itTitle.setTextContent(this.baosongTpl.getCode()+" "+ this.baosongTpl.getNm());
        parentElement.appendChild(itTitle);

        Element itVersion = doc.createElement("itVersion");
        itVersion.setTextContent(this.baosongTpl.getVersion());
        parentElement.appendChild(itVersion);

    }
}