package com.usky.ems.util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * XML报文构建工具类
 *
 * @author system
 * @since 2024-01-01
 */
public class XmlBuilder {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 构建身份认证请求XML
     *
     * @param buildingId 建筑ID
     * @param gatewayId  网关ID
     * @return XML字符串
     */
    public static String buildAuthRequest(String buildingId, String gatewayId) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        
        // common节点
        Element common = root.addElement("common");
        common.addElement("building_id").setText(buildingId);
        common.addElement("gateway_id").setText(gatewayId);
        common.addElement("type").setText("id_validate");
        
        // id_validate节点
        Element idValidate = root.addElement("id_validate");
        idValidate.addAttribute("operation", "request");
        
        return document.asXML();
    }

    /**
     * 构建身份认证MD5请求XML
     *
     * @param buildingId 建筑ID
     * @param gatewayId  网关ID
     * @param md5        MD5值
     * @return XML字符串
     */
    public static String buildAuthMd5Request(String buildingId, String gatewayId, String md5) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        
        // common节点
        Element common = root.addElement("common");
        common.addElement("building_id").setText(buildingId);
        common.addElement("gateway_id").setText(gatewayId);
        common.addElement("type").setText("id_validate");
        
        // id_validate节点
        Element idValidate = root.addElement("id_validate");
        idValidate.addAttribute("operation", "md5");
        idValidate.addElement("md5").setText(md5);
        
        return document.asXML();
    }

    /**
     * 构建心跳请求XML
     *
     * @param buildingId 建筑ID
     * @param gatewayId  网关ID
     * @return XML字符串
     */
    public static String buildHeartbeatRequest(String buildingId, String gatewayId) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        
        // common节点
        Element common = root.addElement("common");
        common.addElement("building_id").setText(buildingId);
        common.addElement("gateway_id").setText(gatewayId);
        common.addElement("type").setText("heart_beat");
        
        // heart_beat节点
        Element heartBeat = root.addElement("heart_beat");
        heartBeat.addAttribute("operation", "notify");
        
        return document.asXML();
    }

    /**
     * 构建能耗数据上报XML
     *
     * @param buildingId  建筑ID
     * @param gatewayId   网关ID
     * @param time        时间（yyyyMMddHHmmss格式）
     * @param energyItems 分项数据
     * @param meters      仪表数据列表
     * @return XML字符串
     */
    public static String buildEnergyDataRequest(String buildingId, String gatewayId, String time,
                                                 Map<String, Double> energyItems, List<Map<String, Object>> meters) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        
        // common节点
        Element common = root.addElement("common");
        common.addElement("building_id").setText(buildingId);
        common.addElement("gateway_id").setText(gatewayId);
        common.addElement("type").setText("energy_data");
        
        // data节点
        Element data = root.addElement("data");
        data.addAttribute("operation", "report");
        data.addElement("time").setText(time);
        
        // energy_items节点
        if (energyItems != null && !energyItems.isEmpty()) {
            Element energyItemsElement = data.addElement("energy_items");
            for (Map.Entry<String, Double> entry : energyItems.entrySet()) {
                Element item = energyItemsElement.addElement("energy_item");
                item.addAttribute("code", entry.getKey());
                item.setText(String.valueOf(entry.getValue()));
            }
        }
        
        // meters节点
        if (meters != null && !meters.isEmpty()) {
            Element metersElement = data.addElement("meters");
            metersElement.addAttribute("total", String.valueOf(meters.size()));
            
            for (Map<String, Object> meter : meters) {
                Element meterElement = metersElement.addElement("meter");
                meterElement.addAttribute("id", (String) meter.get("id"));
                meterElement.addAttribute("name", (String) meter.get("name"));
                
                // function节点
                @SuppressWarnings("unchecked")
                List<Map<String, String>> functions = (List<Map<String, String>>) meter.get("functions");
                if (functions != null) {
                    for (Map<String, String> function : functions) {
                        Element functionElement = meterElement.addElement("function");
                        functionElement.addAttribute("id", function.get("id"));
                        String error = function.get("error");
                        if (error != null && !error.isEmpty()) {
                            functionElement.addAttribute("error", error);
                        }
                        functionElement.setText(function.get("value"));
                    }
                }
            }
        }
        
        return document.asXML();
    }

    /**
     * 格式化时间为yyyyMMddHHmmss格式
     *
     * @param date 日期
     * @return 格式化后的字符串
     */
    public static String formatTime(Date date) {
        return DATE_FORMAT.format(date);
    }

    /**
     * 格式化当前时间为yyyyMMddHHmmss格式
     *
     * @return 格式化后的字符串
     */
    public static String formatCurrentTime() {
        return formatTime(new Date());
    }
}
