qinjie
2023-12-19 15d15d24fbccb9b70a305b46b71453b2ab1a720e
Hydro.MapView/MapViewNetWork2Inp.cs
@@ -1,4 +1,5 @@
using Hydro.Core.Model;
using Hydro.MapView.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -7,6 +8,7 @@
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Hydro.Core.ObjectEnum;
using static Hydro.MapView.RepeaterViewModel;
@@ -854,5 +856,250 @@
        }
        public void BuildToInp(string filePath, string userCoorString = null, string sourcePath = null, bool isReplace = false)
        {
            if (sourcePath == null) sourcePath = filePath;
            string tempString = "";
            if (!isReplace)
            {
                var tempPath = Path.Combine(Directory.GetCurrentDirectory(), @"template\inp\导出模板.inp");
                if (!File.Exists(tempPath))
                {
                    //MessageBox.Show($"模板文件不存在[{tempPath}]");
                    return;
                }
                tempString = File.ReadAllText(tempPath);
            }
            else
            {
                tempString = File.ReadAllText(sourcePath);
            }
            Dictionary<string, string> dictExchange = new Dictionary<string, string>() {
                {"{junctions}","{0}" },
                {"{reservoirs}","{1}" },
                {"{tanks}","{2}" },
                {"{pipes}","{3}" },
                {"{valves}","{4}" },
                {"{pumps}","{5}" },
                {"{coor}","{6}" },
                {"{curve}","{7}" },
            };
            dictExchange.ToList().ForEach(m => tempString = tempString.Replace(m.Key, m.Value));
            StringBuilder junctionStringBuilder = new StringBuilder();
            junctionStringBuilder.AppendLine(";ID                 Elev           Demand         Pattern         Type");
            Nodes.ForEach(o =>
            {
                if (!o.Visible) return;
                if (o is JunctionViewModel j)
                    junctionStringBuilder.AppendLine(j.ToString() + $"{j.Level}\tJunction");
                else if (o is MeterViewModel m)
                    junctionStringBuilder.AppendLine(m.ToString() + $"{o.Level}\tMeter");
                else if (o is NozzleViewModel no)
                    junctionStringBuilder.AppendLine(no.ToString() + $"{o.Level}\tNozzle\t{no.FlowCoefficient}");
            });
            string junctionString = junctionStringBuilder.ToString();
            StringBuilder reservoirStringBuilder = new StringBuilder();
            reservoirStringBuilder.AppendLine(";ID                 Head           Pattern ");
            reservoirs.ForEach(o =>
            {
                if (!o.Visible) return;
                reservoirStringBuilder.AppendLine(o.ToString() + $"{o.Level}\t{o.Elev}");
            });
            string reserverString = reservoirStringBuilder.ToString();
            StringBuilder tankStringBuilder = new StringBuilder();
            tankStringBuilder.AppendLine(";ID                 Elevation      InitLevel      MinLevel       MaxLevel       Diameter       MinVol         VolCurve           Overflow");
            tanks.ForEach(o =>
            {
                if (!o.Visible) return;
                tankStringBuilder.AppendLine(o.ToString() + $"{o.Level}");
            });
            string tankString = tankStringBuilder.ToString();
            StringBuilder pipeStringBuilder = new StringBuilder();
            pipeStringBuilder.AppendLine(";ID                 Node1              Node2              Length         Diameter       Roughness      MinorLoss      Status");
            Links.ForEach(o =>
            {
                if (!o.Visible) return;
                if (o is PipeViewModel p)
                    pipeStringBuilder.AppendLine(p.ToString() + $"{p.Level}");
                else if (o is RepeaterViewModel r)
                    pipeStringBuilder.AppendLine(r.ToString());
            });
            string pipeString = pipeStringBuilder.ToString();
            StringBuilder valveStringBuilder = new StringBuilder();
            valveStringBuilder.AppendLine(";ID                 Node1              Node2              Diameter       Type   Setting        MinorLoss  ");
            valves.ForEach(o =>
            {
                if (!o.Visible) return;
                valveStringBuilder.AppendLine(o.ToString() + $"{o.Level}");
            });
            string valveString = valveStringBuilder.ToString();
            StringBuilder pumpStringBuilder = new StringBuilder();
            pumpStringBuilder.AppendLine(";ID                 Node1              Node2              Diameter       Type   Setting        MinorLoss  ");
            pumps.ForEach(o =>
            {
                if (!o.Visible) return;
                pumpStringBuilder.AppendLine(o.ToString() + $"{o.Level}");
            });
            string pumpString = pumpStringBuilder.ToString();
            StringBuilder curveStringBuilder = new StringBuilder();
            //pumps.ForEach(o =>
            //{
            //    if (!o.Visible || !o.Datasets.ContainsKey("流量扬程曲线")) return;
            //    curveStringBuilder.AppendLine(o.Datasets["流量扬程曲线"].ToString());
            //});
            if (dict_dataset != null)
                foreach (var kp in dict_dataset)
                {
                    curveStringBuilder.AppendLine(kp.Value.ToString());
                }
            string curveString = curveStringBuilder.ToString();
            StringBuilder coorStringBuilder = new StringBuilder();
            if (userCoorString == null)
            {
                coorStringBuilder.AppendLine(";Node               X-Coord              Y-Coord");
                Nodes.ForEach(o => coorStringBuilder.AppendLine(o.ToCoorString()));
            }
            else
            {
                coorStringBuilder.Append(userCoorString);
            }
            string coorString = coorStringBuilder.ToString();
            string output = "";
            StringBuilder emitterStringBuilder = new StringBuilder();
            emitterStringBuilder.AppendLine(";Junction        \tCoefficient");
            Nodes.ForEach(o => emitterStringBuilder.Append(o.ToEmitterString()));
            string emitterString = emitterStringBuilder.ToString();
            StringBuilder statusStringBuilder = new StringBuilder();
            statusStringBuilder.AppendLine(";ID              \tStatus/Setting\r\n");
            Links.ForEach(o => statusStringBuilder.Append(o.ToStatusString()));
            string statusString = statusStringBuilder.ToString();
            output = tempString;
            output = replaceContent(output, "JUNCTIONS", junctionString);
            output = replaceContent(output, "RESERVOIRS", reserverString);
            output = replaceContent(output, "TANKS", tankString);
            output = replaceContent(output, "PIPES", pipeString);
            output = replaceContent(output, "VALVES", valveString);
            output = replaceContent(output, "PUMPS", pumpString);
            output = replaceContent(output, "CURVES", curveString);
            output = replaceContent(output, "COORDINATES", coorString);
            output = replaceContent(output, "EMITTERS", emitterString);
            output = replaceContent(output, "STATUS", statusString);
            string backupFolderPath = Path.Combine(Path.GetDirectoryName(filePath), "bk");
            if (!Directory.Exists(backupFolderPath))
            {
                Directory.CreateDirectory(backupFolderPath);
            }
            string backupFileName = $"{Path.GetFileNameWithoutExtension(filePath)}_{DateTime.Now:yyyyMMddHHmmss}{Path.GetExtension(filePath)}";
            string backupFilePath = Path.Combine(backupFolderPath, backupFileName);
            if (File.Exists(filePath)) File.Copy(filePath, backupFilePath, true);
            // 检查文件是否存在
            try
            {
                Global.ClearFileReadOnly(filePath);
                File.WriteAllText(filePath, output);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //MessageBox.Show($"保存成功!");
        }
        private string replaceContent(string text, string content, string replaceString)
        {
            string str = replaceString;
            string replacedText = ReplaceCoordinatesSection(text, content, str);
            return replacedText;
            //Console.WriteLine(replacedText);
        }
        public static string ReplaceCoordinatesSection(string text, string content, string str)
        {
            string pattern = $@"(\[{content}\]).*?(\[|$)";
            string replacedText = Regex.Replace(text, pattern, match =>
            {
                string section = match.Groups[2].Value.Trim();
                if (!string.IsNullOrEmpty(section))
                {
                    return $"{match.Groups[1].Value}\n{str}\n[";
                }
                else
                {
                    return $"{match.Groups[1].Value}\n{str}\n[";
                }
            }, RegexOptions.Singleline);
            return replacedText;
        }
    }
}