using BLL.Interfaces;
using MDL.Models;
using System.Text.Json;
using System.Xml.Linq;

namespace BLL.Services
{
    public class LogisticsParserService : ILogisticsParser
    {
        public Dictionary<string, string> ParseLogisticsMessage(LogisticsRequest request)
        {
            var result = new Dictionary<string, string>();
            
            if (string.IsNullOrEmpty(request.LogisticsInterface))
            {
                return result;
            }
            
            var logisticsInterface = request.LogisticsInterface.Trim();
            var requestType = request.RequestType?.Trim() ?? string.Empty;
            
            // 根据请求类型进行定制化解析
            switch (requestType.ToLower())
            {
                case "json":
                    result = ParseJsonMessage(logisticsInterface);
                    break;
                case "xml":
                    result = ParseXmlMessage(logisticsInterface);
                    break;
                case "edi":
                    result = ParseEdiMessage(logisticsInterface);
                    break;
                case "csv":
                    result = ParseCsvMessage(logisticsInterface);
                    break;
                case "label-replace":
                    result = ParseLabelReplaceMessage(logisticsInterface);
                    break;
                default:
                    // 自动检测格式
                    result = AutoDetectAndParse(logisticsInterface);
                    break;
            }
            
            // 添加请求元数据
            result["RequestId"] = request.Id ?? Guid.NewGuid().ToString();
            result["RequestType"] = requestType;
            result["Timestamp"] = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
            
            return result;
        }
        
        public bool ValidateLogisticsMessage(string logisticsInterface, string requestType)
        {
            if (string.IsNullOrEmpty(logisticsInterface))
            {
                return false;
            }
            
            try
            {
                switch (requestType.ToLower())
                {
                    case "json":
                        JsonDocument.Parse(logisticsInterface);
                        return true;
                    case "xml":
                        XDocument.Parse(logisticsInterface);
                        return true;
                    case "csv":
                        return logisticsInterface.Contains(',');
                    case "edi":
                        return logisticsInterface.Contains('~') || logisticsInterface.Contains('|');
                    case "label-replace":
                        // 验证是否为有效的LabelReplaceMessage JSON格式
                        try
                        {
                            var message = JsonSerializer.Deserialize<LabelReplaceMessage>(logisticsInterface);
                            return message != null && !string.IsNullOrEmpty(message.NeutralWaybillNumber);
                        }
                        catch
                        {
                            return false;
                        }
                    default:
                        // 尝试自动检测
                        try
                        {
                            JsonDocument.Parse(logisticsInterface);
                            return true;
                        }
                        catch {}
                        
                        try
                        {
                            XDocument.Parse(logisticsInterface);
                            return true;
                        }
                        catch {}
                        
                        return logisticsInterface.Contains(',') || logisticsInterface.Contains('~') || logisticsInterface.Contains('|');
                }
            }
            catch
            {
                return false;
            }
        }
        
        private Dictionary<string, string> ParseJsonMessage(string jsonContent)
        {
            var result = new Dictionary<string, string>();
            
            try
            {
                var jsonDoc = JsonDocument.Parse(jsonContent);
                var root = jsonDoc.RootElement;
                
                ParseJsonElement(root, "", result);
            }
            catch (Exception ex)
            {
                result["ParseError"] = ex.Message;
            }
            
            return result;
        }
        
        private void ParseJsonElement(JsonElement element, string prefix, Dictionary<string, string> result)
        {
            switch (element.ValueKind)
            {
                case JsonValueKind.Object:
                    foreach (var property in element.EnumerateObject())
                    {
                        var newPrefix = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}.{property.Name}";
                        ParseJsonElement(property.Value, newPrefix, result);
                    }
                    break;
                case JsonValueKind.Array:
                    int index = 0;
                    foreach (var item in element.EnumerateArray())
                    {
                        var newPrefix = $"{prefix}[{index}]";
                        ParseJsonElement(item, newPrefix, result);
                        index++;
                    }
                    break;
                case JsonValueKind.String:
                    result[prefix] = element.GetString()!;
                    break;
                case JsonValueKind.Number:
                    result[prefix] = element.GetRawText();
                    break;
                case JsonValueKind.True:
                    result[prefix] = "true";
                    break;
                case JsonValueKind.False:
                    result[prefix] = "false";
                    break;
                case JsonValueKind.Null:
                    result[prefix] = "null";
                    break;
            }
        }
        
        private Dictionary<string, string> ParseXmlMessage(string xmlContent)
        {
            var result = new Dictionary<string, string>();
            
            try
            {
                var xDoc = XDocument.Parse(xmlContent);
                var root = xDoc.Root;
                
                if (root != null)
                {
                    ParseXmlNode(root, "", result);
                }
            }
            catch (Exception ex)
            {
                result["ParseError"] = ex.Message;
            }
            
            return result;
        }
        
        private void ParseXmlNode(XElement node, string prefix, Dictionary<string, string> result)
        {
            // 处理属性
            foreach (var attr in node.Attributes())
            {
                var key = string.IsNullOrEmpty(prefix) ? $"{node.Name.LocalName}.@{attr.Name.LocalName}" : $"{prefix}.{node.Name.LocalName}.@{attr.Name.LocalName}";
                result[key] = attr.Value;
            }
            
            // 处理子元素
            var children = node.Elements().ToList();
            if (children.Any())
            {
                // 检查是否有同名元素
                var elementGroups = children.GroupBy(e => e.Name.LocalName);
                
                foreach (var group in elementGroups)
                {
                    var elementName = group.Key;
                    var elements = group.ToList();
                    
                    if (elements.Count == 1)
                    {
                        var newPrefix = string.IsNullOrEmpty(prefix) ? elementName : $"{prefix}.{elementName}";
                        ParseXmlNode(elements[0], newPrefix, result);
                    }
                    else
                    {
                        // 处理数组情况
                        for (int i = 0; i < elements.Count; i++)
                        {
                            var newPrefix = string.IsNullOrEmpty(prefix) ? $"{elementName}[{i}]" : $"{prefix}.{elementName}[{i}]";
                            ParseXmlNode(elements[i], newPrefix, result);
                        }
                    }
                }
            }
            else if (!string.IsNullOrEmpty(node.Value))
            {
                // 处理文本内容
                var key = string.IsNullOrEmpty(prefix) ? node.Name.LocalName : prefix;
                result[key] = node.Value.Trim();
            }
        }
        
        private Dictionary<string, string> ParseEdiMessage(string ediContent)
        {
            var result = new Dictionary<string, string>();
            
            try
            {
                // 简单的EDI解析示例（根据实际EDI标准调整）
                var segments = ediContent.Split('~', StringSplitOptions.RemoveEmptyEntries);
                
                for (int i = 0; i < segments.Length; i++)
                {
                    var segment = segments[i].Trim();
                    if (string.IsNullOrEmpty(segment)) continue;
                    
                    var fields = segment.Split('|');
                    if (fields.Length > 0)
                    {
                        var segmentType = fields[0];
                        result[$"Segment[{i}].Type"] = segmentType;
                        
                        for (int j = 1; j < fields.Length; j++)
                        {
                            result[$"Segment[{i}].Field[{j}]"] = fields[j];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result["ParseError"] = ex.Message;
            }
            
            return result;
        }
        
        private Dictionary<string, string> ParseCsvMessage(string csvContent)
        {
            var result = new Dictionary<string, string>();
            
            try
            {
                var lines = csvContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                if (lines.Length == 0) return result;
                
                // 解析表头
                var headers = lines[0].Split(',');
                
                // 解析数据行
                for (int rowIndex = 1; rowIndex < lines.Length; rowIndex++)
                {
                    var fields = lines[rowIndex].Split(',');
                    
                    for (int colIndex = 0; colIndex < headers.Length; colIndex++)
                    {
                        var header = headers[colIndex].Trim();
                        var value = colIndex < fields.Length ? fields[colIndex].Trim() : string.Empty;
                        
                        result[$"Row[{rowIndex-1}].{header}"] = value;
                    }
                }
            }
            catch (Exception ex)
            {
                result["ParseError"] = ex.Message;
            }
            
            return result;
        }

        private Dictionary<string, string> ParseLabelReplaceMessage(string message)
        {
            var result = new Dictionary<string, string>();
            
            try
            {
                // 尝试解析为JSON格式的LabelReplaceMessage
                var labelReplaceMessage = JsonSerializer.Deserialize<LabelReplaceMessage>(message);
                if (labelReplaceMessage != null)
                {
                    // 提取字段到字典
                    result["BillOfLadingNumber"] = labelReplaceMessage.BillOfLadingNumber ?? string.Empty;
                    result["MasterPackageNumber"] = labelReplaceMessage.MasterPackageNumber ?? string.Empty;
                    result["ReferenceNumber"] = labelReplaceMessage.ReferenceNumber ?? string.Empty;
                    result["NeutralWaybillNumber"] = labelReplaceMessage.NeutralWaybillNumber;
                    result["FinalMileTrackingNumber"] = labelReplaceMessage.FinalMileTrackingNumber ?? string.Empty;
                    result["Label"] = labelReplaceMessage.Label ?? string.Empty;
                }
            }
            catch (Exception ex)
            {
                result["ParseError"] = ex.Message;
            }
            
            return result;
        }
        
        private Dictionary<string, string> AutoDetectAndParse(string message)
        {
            var trimmedMessage = message.Trim();
            
            // 尝试JSON解析
            if (trimmedMessage.StartsWith('{') && trimmedMessage.EndsWith('}'))
            {
                return ParseJsonMessage(message);
            }
            
            // 尝试XML解析
            if (trimmedMessage.StartsWith('<') && trimmedMessage.EndsWith('>'))
            {
                return ParseXmlMessage(message);
            }
            
            // 尝试EDI解析
            if (trimmedMessage.Contains('~') || trimmedMessage.Contains('|'))
            {
                return ParseEdiMessage(message);
            }
            
            // 尝试CSV解析
            if (trimmedMessage.Contains(','))
            {
                return ParseCsvMessage(message);
            }
            
            // 默认返回原始消息
            return new Dictionary<string, string>
            {
                ["RawMessage"] = message
            };
        }
    }
}