using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NavisworksTransport.Core.Models;

namespace NavisworksTransport.Core.Services
{
    /// <summary>
    /// 时标数据导出器 - 支持JSON和CSV格式
    /// </summary>
    public class TimeTagExporter
    {
        /// <summary>
        /// 导出配置为JSON格式
        /// </summary>
        public string ExportToJson(TimeTagProfile profile, PathRoute route)
        {
            if (profile == null) throw new ArgumentNullException(nameof(profile));
            if (route == null) throw new ArgumentNullException(nameof(route));

            var sb = new StringBuilder();
            sb.AppendLine("{");
            sb.AppendLine($"  \"profile\": {"{"}");
            sb.AppendLine($"    \"id\": \"{profile.Id}\",");
            sb.AppendLine($"    \"name\": \"{EscapeJson(profile.Name)}\",");
            sb.AppendLine($"    \"routeId\": \"{profile.RouteId}\",");
            sb.AppendLine($"    \"routeName\": \"{EscapeJson(route.Name)}\",");
            sb.AppendLine($"    \"defaultSpeed\": {profile.DefaultSpeed:F3},");
            sb.AppendLine($"    \"turnSpeedRatio\": {profile.TurnSpeedRatio:F2},");
            sb.AppendLine($"    \"totalDistance\": {route.TotalLength:F3},");
            sb.AppendLine($"    \"totalTime\": {profile.TotalTime:F3},");
            sb.AppendLine($"    \"eventCount\": {profile.Events?.Count ?? 0},");
            sb.AppendLine("    \"events\": [");

            if (profile.Events != null && profile.Events.Count > 0)
            {
                var events = profile.Events.OrderBy(e => e.Distance).ToList();
                for (int i = 0; i < events.Count; i++)
                {
                    var evt = events[i];
                    sb.AppendLine("      {");
                    sb.AppendLine($"        \"id\": \"{evt.Id}\",");
                    sb.AppendLine($"        \"sortOrder\": {evt.SortOrder},");
                    sb.AppendLine($"        \"name\": \"{EscapeJson(evt.Name)}\",");
                    sb.AppendLine($"        \"type\": \"{evt.Type}\",");
                    sb.AppendLine($"        \"distance\": {evt.Distance:F3},");
                    sb.AppendLine($"        \"waitTime\": {evt.WaitTime:F2},");
                    sb.AppendLine($"        \"actionTime\": {evt.ActionTime:F2},");
                    sb.AppendLine($"        \"cumulativeTime\": {evt.CumulativeTime:F3},");
                    sb.AppendLine($"        \"pointId\": \"{evt.PointId ?? ""}\"");
                    sb.Append("      }");
                    if (i < events.Count - 1) sb.Append(",");
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    ]");
            sb.AppendLine("  },");
            sb.AppendLine("  \"route\": {");
            sb.AppendLine($"    \"id\": \"{route.Id}\",");
            sb.AppendLine($"    \"name\": \"{EscapeJson(route.Name)}\",");
            sb.AppendLine($"    \"type\": \"{route.PathType}\",");
            sb.AppendLine($"    \"totalLength\": {route.TotalLength:F3},");
            sb.AppendLine($"    \"pointCount\": {route.Points?.Count ?? 0}");
            sb.AppendLine("  },");
            sb.AppendLine($"  \"exportTime\": \"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\",");
            sb.AppendLine($"  \"version\": \"1.0\"");
            sb.AppendLine("}");

            return sb.ToString();
        }

        /// <summary>
        /// 导出配置为CSV格式
        /// </summary>
        public string ExportToCsv(TimeTagProfile profile)
        {
            if (profile == null) throw new ArgumentNullException(nameof(profile));

            var sb = new StringBuilder();
            
            // 头部信息
            sb.AppendLine($"# Time Tag Profile: {profile.Name}");
            sb.AppendLine($"# Route ID: {profile.RouteId}");
            sb.AppendLine($"# Default Speed: {profile.DefaultSpeed:F3} m/s");
            sb.AppendLine($"# Turn Speed Ratio: {profile.TurnSpeedRatio:P0}");
            sb.AppendLine($"# Total Time: {profile.TotalTime:F3} s");
            sb.AppendLine($"# Export Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine();
            
            // CSV表头
            sb.AppendLine("序号,名称,类型,距离(m),等待时间(s),动作时间(s),累计时间(s),说明");
            
            // 数据行
            if (profile.Events != null)
            {
                foreach (var evt in profile.Events.OrderBy(e => e.Distance))
                {
                    string description = GetEventDescription(evt);
                    sb.AppendLine($"{evt.SortOrder},{EscapeCsv(evt.Name)},{evt.Type},{evt.Distance:F2},{evt.WaitTime:F2},{evt.ActionTime:F2},{evt.CumulativeTime:F3},{EscapeCsv(description)}");
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// 导出到文件
        /// </summary>
        public void ExportToFile(TimeTagProfile profile, PathRoute route, string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentException("文件路径不能为空", nameof(filePath));

            string extension = Path.GetExtension(filePath).ToLower();
            string content;

            switch (extension)
            {
                case ".json":
                    content = ExportToJson(profile, route);
                    break;
                case ".csv":
                    content = ExportToCsv(profile);
                    break;
                default:
                    throw new NotSupportedException($"不支持的文件格式: {extension}");
            }

            File.WriteAllText(filePath, content, Encoding.UTF8);
        }

        /// <summary>
        /// 批量导出多个配置
        /// </summary>
        public string ExportMultipleToJson(List<TimeTagProfile> profiles, PathRoute route)
        {
            if (profiles == null || profiles.Count == 0)
                return "[]";

            var sb = new StringBuilder();
            sb.AppendLine("{");
            sb.AppendLine($"  \"route\": \"{EscapeJson(route.Name)}\",");
            sb.AppendLine($"  \"exportTime\": \"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\",");
            sb.AppendLine("  \"profiles\": [");

            for (int i = 0; i < profiles.Count; i++)
            {
                var profile = profiles[i];
                sb.AppendLine("    {");
                sb.AppendLine($"      \"id\": \"{profile.Id}\",");
                sb.AppendLine($"      \"name\": \"{EscapeJson(profile.Name)}\",");
                sb.AppendLine($"      \"defaultSpeed\": {profile.DefaultSpeed:F3},");
                sb.AppendLine($"      \"turnSpeedRatio\": {profile.TurnSpeedRatio:F2},");
                sb.AppendLine($"      \"totalTime\": {profile.TotalTime:F3},");
                sb.AppendLine($"      \"eventCount\": {profile.Events?.Count ?? 0}");
                sb.Append("    }");
                if (i < profiles.Count - 1) sb.Append(",");
                sb.AppendLine();
            }

            sb.AppendLine("  ]");
            sb.AppendLine("}");

            return sb.ToString();
        }

        /// <summary>
        /// 转义JSON字符串
        /// </summary>
        private string EscapeJson(string str)
        {
            if (string.IsNullOrEmpty(str)) return "";
            return str.Replace("\\", "\\\\")
                     .Replace("\"", "\\\"")
                     .Replace("\n", "\\n")
                     .Replace("\r", "\\r")
                     .Replace("\t", "\\t");
        }

        /// <summary>
        /// 转义CSV字符串
        /// </summary>
        private string EscapeCsv(string str)
        {
            if (string.IsNullOrEmpty(str)) return "";
            if (str.Contains(",") || str.Contains("\"") || str.Contains("\n"))
            {
                return "\"" + str.Replace("\"", "\"\"") + "\"";
            }
            return str;
        }

        /// <summary>
        /// 获取事件说明
        /// </summary>
        private string GetEventDescription(TimeTagEvent evt)
        {
            switch (evt.Type)
            {
                case EventType.Start:
                    return "路径起点";
                case EventType.End:
                    return "路径终点";
                case EventType.Turn:
                    return "转弯减速点";
                case EventType.Wait:
                    return "等待点";
                case EventType.Load:
                    return "装载点";
                case EventType.Unload:
                    return "卸载点";
                case EventType.Pass:
                    return "途经点";
                default:
                    return "";
            }
        }
    }
}
