CalculateFormula.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using JLHHJSvr.Com.Model;
  2. using JLHHJSvr.LJException;
  3. using JLHHJSvr.LJFramework.Tools;
  4. using NPOI.SS.Formula;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Linq;
  9. using System.Text.RegularExpressions;
  10. namespace JLHHJSvr.Tools
  11. {
  12. public class CalculateFormula
  13. {
  14. private HashSet<FormulaItem> _formula; // 公式
  15. private HashSet<FormulaItem> _const; // 常量
  16. public CalculateFormula()
  17. {
  18. _formula = new HashSet<FormulaItem>();
  19. _const = new HashSet<FormulaItem>();
  20. }
  21. public void AddFormulaItem(FormulaItem item)
  22. {
  23. if(!_formula.Add(item))
  24. {
  25. _formula.Remove(item);
  26. _formula.Add(item);
  27. }
  28. }
  29. public void AddConstFormulaItem(FormulaItem item)
  30. {
  31. if (!_const.Add(item))
  32. {
  33. _const.Remove(item);
  34. _const.Add(item);
  35. }
  36. }
  37. public void AddFormulaItem(string name,object value)
  38. {
  39. AddConstFormulaItem(new FormulaItem() { formula_name = name, value = value });
  40. }
  41. public void AddFormulaItem(string name, string formula)
  42. {
  43. var formulaItem = new FormulaItem() { formula_name = name, formula = formula };
  44. AddFormulaItem(formulaItem);
  45. }
  46. /// <summary>
  47. /// 主计算入口
  48. /// </summary>
  49. public void CalculateAll()
  50. {
  51. var dict = _formula.ToDictionary(f => f.formula_name, f => f);
  52. foreach (var c in _const)
  53. {
  54. dict[c.formula_name] = c;
  55. }
  56. var graph = BuildDependencyGraph(dict);
  57. var sorted = TopologicalSort(graph);
  58. foreach (var name in sorted)
  59. {
  60. var item = dict[name];
  61. item.formula = ConvertToEnglishSymbols(item.formula);
  62. // 展开
  63. string expanded = ExpandFormula(item.formula, dict);
  64. item.formula_transform = expanded;
  65. // 计算
  66. if (item.isSql) SqlCalculate(item);
  67. else Calculate(item);
  68. }
  69. }
  70. /// <summary>
  71. /// 解析依赖
  72. /// </summary>
  73. private Dictionary<string, List<string>> BuildDependencyGraph(Dictionary<string, FormulaItem> dict)
  74. {
  75. var graph = new Dictionary<string, List<string>>();
  76. foreach (var kv in dict)
  77. {
  78. var deps = new List<string>();
  79. foreach (var name in dict.Keys)
  80. {
  81. if (name == kv.Key) continue;
  82. if (Regex.IsMatch(kv.Value.formula, name))
  83. {
  84. deps.Add(name);
  85. }
  86. }
  87. graph[kv.Key] = deps;
  88. }
  89. return graph;
  90. }
  91. /// <summary>
  92. /// 拓扑排序
  93. /// </summary>
  94. private List<string> TopologicalSort(Dictionary<string, List<string>> graph)
  95. {
  96. var result = new List<string>();
  97. var visited = new Dictionary<string, int>(); // 0=未访问,1=正在访问,2=已完成
  98. foreach (var node in graph.Keys)
  99. {
  100. if (!visited.ContainsKey(node))
  101. {
  102. Dfs(node, graph, visited, result);
  103. }
  104. }
  105. return result;
  106. }
  107. private void Dfs(string node, Dictionary<string, List<string>> graph,Dictionary<string, int> visited, List<string> result)
  108. {
  109. if (visited.ContainsKey(node) && visited[node] == 1) throw new InvalidOperationException($"检测到循环依赖: {node}");
  110. if (visited.ContainsKey(node) && visited[node] == 2) return;
  111. visited[node] = 1;
  112. foreach (var dep in graph[node])
  113. {
  114. Dfs(dep, graph, visited, result);
  115. }
  116. visited[node] = 2;
  117. result.Add(node);
  118. }
  119. /// <summary>
  120. /// 展开公式,把变量替换为已计算的值
  121. /// </summary>
  122. private string ExpandFormula(string formula, Dictionary<string, FormulaItem> dict)
  123. {
  124. foreach (var kv in dict)
  125. {
  126. if (kv.Value.value != null) // 已经算过
  127. {
  128. formula = Regex.Replace(formula, $"【{kv.Key}】", kv.Value.value.ToString());
  129. }
  130. }
  131. return formula;
  132. }
  133. private string ConvertToEnglishSymbols(string input)
  134. {
  135. input = input.Replace("(", "(")
  136. .Replace(")", ")")
  137. .Replace(",", ",")
  138. .Replace("。", ".")
  139. .Replace(":", ":")
  140. .Replace(";", ";")
  141. .Replace("“", "\"")
  142. .Replace("”", "\"")
  143. .Replace("‘", "'")
  144. .Replace("’", "'");
  145. return input;
  146. }
  147. /// <summary>
  148. /// 公式计算
  149. /// </summary>
  150. /// <param name="expression"></param>
  151. /// <param name="name"></param>
  152. /// <returns></returns>
  153. private void Calculate(FormulaItem formula)
  154. {
  155. try
  156. {
  157. formula.value = LJExprParser.Parse(formula.formula).Result;
  158. }
  159. catch (Exception ex)
  160. {
  161. throw new LJCommonException($"计算{formula.formula_name}公式错误: {ex.Message}");
  162. }
  163. }
  164. /// <summary>
  165. /// Sql公式计算
  166. /// </summary>
  167. /// <param name="expression"></param>
  168. /// <param name="name"></param>
  169. /// <returns></returns>
  170. private void SqlCalculate(FormulaItem formula)
  171. {
  172. try
  173. {
  174. //cmd.CommandText = $@"{formula.formula}";
  175. //cmd.Parameters.Clear();
  176. //return cmd.ExecuteScalar();
  177. }
  178. catch (Exception ex)
  179. {
  180. throw new LJCommonException($"计算{formula.formula_name}公式错误: {ex.Message}");
  181. }
  182. }
  183. }
  184. }