CustomQueryController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /*
  2. * 自定义查询
  3. */
  4. using System;
  5. using System.Web;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.Extensions.Logging;
  13. using Microsoft.Extensions.Options;
  14. using MySystem.Models;
  15. using Library;
  16. using LitJson;
  17. using MySystemLib;
  18. using System.Text.RegularExpressions;
  19. using System.Data;
  20. namespace MySystem.Areas.Admin.Controllers
  21. {
  22. [Area("Admin")]
  23. [Route("Admin/[controller]/[action]")]
  24. public class CustomQueryController : BaseController
  25. {
  26. public CustomQueryController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
  27. {
  28. OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();
  29. }
  30. #region 自定义查询列表
  31. /// <summary>
  32. /// 根据条件查询自定义查询列表
  33. /// </summary>
  34. /// <returns></returns>
  35. public IActionResult Index(CustomQuery data, string right)
  36. {
  37. ViewBag.RightInfo = RightInfo;
  38. ViewBag.right = right;
  39. return View();
  40. }
  41. #endregion
  42. #region 根据条件查询自定义查询列表
  43. /// <summary>
  44. /// 自定义查询列表
  45. /// </summary>
  46. /// <returns></returns>
  47. public JsonResult IndexData(CustomQuery data, int page = 1, int limit = 30)
  48. {
  49. Dictionary<string, string> Fields = new Dictionary<string, string>();
  50. string condition = " and Status>-1";
  51. if(SysUserName != "admin")
  52. {
  53. condition += " and CONCAT(',', AdminNames,',') like '%," + SysUserName + ",%'";
  54. }
  55. if(!string.IsNullOrEmpty(data.Title))
  56. {
  57. condition += " and Title like '%" + data.Title + "%'";
  58. }
  59. Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("CustomQuery", Fields, "Id desc", "0", page, limit, condition);
  60. List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
  61. foreach (Dictionary<string, object> dic in diclist)
  62. {
  63. }
  64. return Json(obj);
  65. }
  66. #endregion
  67. #region 增加自定义查询
  68. /// <summary>
  69. /// 增加或修改自定义查询信息
  70. /// </summary>
  71. /// <returns></returns>
  72. public IActionResult Add(string right)
  73. {
  74. ViewBag.RightInfo = RightInfo;
  75. ViewBag.right = right;
  76. return View();
  77. }
  78. #endregion
  79. #region 增加自定义查询
  80. /// <summary>
  81. /// 增加或修改自定义查询信息
  82. /// </summary>
  83. /// <returns></returns>
  84. [HttpPost]
  85. public string Add(CustomQuery data)
  86. {
  87. Dictionary<string, object> Fields = new Dictionary<string, object>();
  88. Fields.Add("SqlContent", data.SqlContent); //sql语句
  89. Fields.Add("Title", data.Title); //标题
  90. Fields.Add("AdminNames", data.AdminNames); //后台账号
  91. Fields.Add("ExcuteFlag", data.ExcuteFlag); //是否执行
  92. Fields.Add("DatabaseConnect", data.DatabaseConnect); //数据库
  93. Fields.Add("SeoTitle", data.SeoTitle);
  94. Fields.Add("SeoKeyword", data.SeoKeyword);
  95. Fields.Add("SeoDescription", data.SeoDescription);
  96. int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("CustomQuery", Fields, 0);
  97. AddSysLog(data.Id.ToString(), "CustomQuery", "add");
  98. db.SaveChanges();
  99. return "success";
  100. }
  101. #endregion
  102. #region 修改自定义查询
  103. /// <summary>
  104. /// 增加或修改自定义查询信息
  105. /// </summary>
  106. /// <returns></returns>
  107. public IActionResult Edit(string right, int Id = 0)
  108. {
  109. ViewBag.RightInfo = RightInfo;
  110. ViewBag.right = right;
  111. CustomQuery editData = db.CustomQuery.FirstOrDefault(m => m.Id == Id) ?? new CustomQuery();
  112. ViewBag.data = editData;
  113. return View();
  114. }
  115. #endregion
  116. #region 修改自定义查询
  117. /// <summary>
  118. /// 增加或修改自定义查询信息
  119. /// </summary>
  120. /// <returns></returns>
  121. [HttpPost]
  122. public string Edit(CustomQuery data)
  123. {
  124. Dictionary<string, object> Fields = new Dictionary<string, object>();
  125. Fields.Add("SqlContent", data.SqlContent); //sql语句
  126. Fields.Add("Title", data.Title); //标题
  127. Fields.Add("AdminNames", data.AdminNames); //后台账号
  128. Fields.Add("ExcuteFlag", data.ExcuteFlag); //是否执行
  129. Fields.Add("DatabaseConnect", data.DatabaseConnect); //数据库
  130. Fields.Add("SeoTitle", data.SeoTitle);
  131. Fields.Add("SeoKeyword", data.SeoKeyword);
  132. Fields.Add("SeoDescription", data.SeoDescription);
  133. new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("CustomQuery", Fields, data.Id);
  134. AddSysLog(data.Id.ToString(), "CustomQuery", "update");
  135. db.SaveChanges();
  136. return "success";
  137. }
  138. #endregion
  139. #region 删除自定义查询信息
  140. /// <summary>
  141. /// 删除自定义查询信息
  142. /// </summary>
  143. /// <returns></returns>
  144. public string Delete(string Id)
  145. {
  146. string[] idlist = Id.Split(new char[] { ',' });
  147. AddSysLog(Id, "CustomQuery", "del");
  148. foreach (string subid in idlist)
  149. {
  150. int id = int.Parse(subid);
  151. Dictionary<string, object> Fields = new Dictionary<string, object>();
  152. Fields.Add("Status", -1);
  153. new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("CustomQuery", Fields, id);
  154. }
  155. db.SaveChanges();
  156. return "success";
  157. }
  158. #endregion
  159. #region 开启
  160. /// <summary>
  161. /// 开启
  162. /// </summary>
  163. /// <returns></returns>
  164. public string Open(string Id)
  165. {
  166. string[] idlist = Id.Split(new char[] { ',' });
  167. AddSysLog(Id, "CustomQuery", "open");
  168. foreach (string subid in idlist)
  169. {
  170. int id = int.Parse(subid);
  171. Dictionary<string, object> Fields = new Dictionary<string, object>();
  172. Fields.Add("Status", 1);
  173. new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("CustomQuery", Fields, id);
  174. }
  175. db.SaveChanges();
  176. return "success";
  177. }
  178. #endregion
  179. #region 关闭
  180. /// <summary>
  181. /// 关闭
  182. /// </summary>
  183. /// <returns></returns>
  184. public string Close(string Id)
  185. {
  186. string[] idlist = Id.Split(new char[] { ',' });
  187. AddSysLog(Id, "CustomQuery", "close");
  188. foreach (string subid in idlist)
  189. {
  190. int id = int.Parse(subid);
  191. Dictionary<string, object> Fields = new Dictionary<string, object>();
  192. Fields.Add("Status", 0);
  193. new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("CustomQuery", Fields, id);
  194. }
  195. db.SaveChanges();
  196. return "success";
  197. }
  198. #endregion
  199. #region 排序
  200. /// <summary>
  201. /// 排序
  202. /// </summary>
  203. /// <param name="Id"></param>
  204. public string Sort(int Id, int Sort)
  205. {
  206. new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Sort("CustomQuery", Sort, Id);
  207. AddSysLog(Id.ToString(), "CustomQuery", "sort");
  208. return "success";
  209. }
  210. #endregion
  211. #region 导入数据
  212. /// <summary>
  213. /// 导入数据
  214. /// </summary>
  215. /// <param name="ExcelData"></param>
  216. public string Import(string ExcelData)
  217. {
  218. ExcelData = HttpUtility.UrlDecode(ExcelData);
  219. JsonData list = JsonMapper.ToObject(ExcelData);
  220. for (int i = 1; i < list.Count; i++)
  221. {
  222. JsonData dr = list[i];
  223. db.CustomQuery.Add(new CustomQuery()
  224. {
  225. CreateDate = DateTime.Now,
  226. UpdateDate = DateTime.Now,
  227. });
  228. db.SaveChanges();
  229. }
  230. AddSysLog("0", "CustomQuery", "Import");
  231. return "success";
  232. }
  233. #endregion
  234. #region 导出Excel
  235. /// <summary>
  236. /// 导出Excel
  237. /// </summary>
  238. /// <returns></returns>
  239. public JsonResult ExportExcel(CustomQuery data)
  240. {
  241. Dictionary<string, string> Fields = new Dictionary<string, string>();
  242. Fields.Add("Title", "1"); //标题
  243. string condition = " and Status>-1";
  244. Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("CustomQuery", Fields, "Id desc", "0", 1, 20000, condition, "", false);
  245. List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
  246. foreach (Dictionary<string, object> dic in diclist)
  247. {
  248. }
  249. Dictionary<string, object> result = new Dictionary<string, object>();
  250. result.Add("Status", "1");
  251. result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
  252. result.Add("Obj", diclist);
  253. Dictionary<string, object> ReturnFields = new Dictionary<string, object>();
  254. result.Add("Fields", ReturnFields);
  255. AddSysLog("0", "CustomQuery", "ExportExcel");
  256. return Json(result);
  257. }
  258. #endregion
  259. #region 自定义提交
  260. /// <summary>
  261. /// 自定义提交
  262. /// </summary>
  263. /// <returns></returns>
  264. public IActionResult Confirm(string right, int Id)
  265. {
  266. ViewBag.RightInfo = RightInfo;
  267. ViewBag.right = right;
  268. ViewBag.Id = Id.ToString();
  269. CustomQuery item = db.CustomQuery.FirstOrDefault(m => m.Id == Id) ?? new CustomQuery();
  270. if(SysUserName != "admin")
  271. {
  272. string checkString = "," + item.AdminNames + ",";
  273. if(!checkString.Contains("," + SysUserName + ","))
  274. {
  275. return Content("无权限");
  276. }
  277. }
  278. Dictionary<string, string> query = new Dictionary<string, string>();
  279. string sql = item.SqlContent;
  280. MatchCollection mc = Regex.Matches(sql, @"\$\{.*?\}\$");
  281. foreach(Match m in mc)
  282. {
  283. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  284. string fieldName = fieldData[0];
  285. string Title = fieldData[1];
  286. if(!query.ContainsKey(fieldName))
  287. {
  288. query.Add(fieldName, Title);
  289. }
  290. }
  291. List<CustomQuerySub> subItems = db.CustomQuerySub.Where(m => m.ParentId == Id).ToList();
  292. foreach(CustomQuerySub sub in subItems)
  293. {
  294. sql = sub.SqlContent;
  295. mc = Regex.Matches(sql, @"\$\{.*?\}\$");
  296. foreach(Match m in mc)
  297. {
  298. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  299. string fieldName = fieldData[0];
  300. string Title = fieldData[1];
  301. if(!query.ContainsKey(fieldName))
  302. {
  303. query.Add(fieldName, Title);
  304. }
  305. }
  306. }
  307. ViewBag.query = query;
  308. return View();
  309. }
  310. #endregion
  311. #region 自定义提交
  312. /// <summary>
  313. /// 自定义提交
  314. /// </summary>
  315. /// <returns></returns>
  316. [HttpPost]
  317. public string Confirm(int Id)
  318. {
  319. var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
  320. CustomQuery item = db.CustomQuery.FirstOrDefault(m => m.Id == Id) ?? new CustomQuery();
  321. string ConnectStr = "";
  322. Dictionary<string, string> dicVals = new Dictionary<string, string>();
  323. List<CustomQuerySub> subItems = db.CustomQuerySub.Where(m => m.ParentId == Id).ToList();
  324. foreach(CustomQuerySub sub in subItems)
  325. {
  326. ConnectStr = sub.DatabaseConnect;
  327. if(!string.IsNullOrEmpty(ConnectStr))
  328. {
  329. ConnectStr = GetConnectStr(sub.DatabaseConnect);
  330. }
  331. else
  332. {
  333. if(item.ExcuteFlag == 2)
  334. {
  335. ConnectStr = MysqlConn.RedisConnStr;
  336. }
  337. else
  338. {
  339. ConnectStr = MysqlConn.ReadSqlConnStr;
  340. }
  341. }
  342. string sqlstr = sub.SqlContent;
  343. MatchCollection mcsub = Regex.Matches(sqlstr, @"\$\{.*?\}\$");
  344. foreach(Match m in mcsub)
  345. {
  346. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  347. string fieldName = fieldData[0];
  348. sqlstr = sqlstr.Replace(m.Value, Request.Query[fieldName].ToString());
  349. }
  350. mcsub = Regex.Matches(sqlstr, @"\#\{.*?\}\#");
  351. foreach(Match m in mcsub)
  352. {
  353. string fieldName = m.Value.Replace("#{", "").Replace("}#", "");
  354. if(dicVals.ContainsKey(fieldName))
  355. {
  356. sqlstr = sqlstr.Replace(m.Value, dicVals[fieldName]);
  357. }
  358. }
  359. DataTable dtsub = CustomerSqlConn.dtable(sqlstr, ConnectStr);
  360. if(dtsub.Rows.Count > 0)
  361. {
  362. if(dtsub.Rows.Count > 1)
  363. {
  364. string val = "";
  365. foreach(DataRow dr in dtsub.Rows)
  366. {
  367. val += dr[0].ToString() + ",";
  368. }
  369. val = val.TrimEnd(',');
  370. dicVals.Add(sub.Alias + "." + dtsub.Columns[0].ColumnName, val);
  371. }
  372. else
  373. {
  374. DataRow dr = dtsub.Rows[0];
  375. foreach(DataColumn dc in dtsub.Columns)
  376. {
  377. dicVals.Add(sub.Alias + "." + dc.ColumnName, dr[dc.ColumnName].ToString());
  378. }
  379. }
  380. }
  381. }
  382. ConnectStr = item.DatabaseConnect;
  383. if(!string.IsNullOrEmpty(ConnectStr))
  384. {
  385. ConnectStr = GetConnectStr(item.DatabaseConnect);
  386. }
  387. else
  388. {
  389. if(item.ExcuteFlag == 2)
  390. {
  391. ConnectStr = MysqlConn.RedisConnStr;
  392. }
  393. else
  394. {
  395. ConnectStr = MysqlConn.ReadSqlConnStr;
  396. }
  397. }
  398. string sql = item.SqlContent;
  399. MatchCollection mc = Regex.Matches(sql, @"\$\{.*?\}\$");
  400. foreach(Match m in mc)
  401. {
  402. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  403. string fieldName = fieldData[0];
  404. sql = sql.Replace(m.Value, Request.Form[fieldName].ToString());
  405. }
  406. mc = Regex.Matches(sql, @"\$\replace{.*?\}\$");
  407. foreach(Match m in mc)
  408. {
  409. string[] fieldData = m.Value.Replace("$replace{", "").Replace("}$", "").Split('|');
  410. string str = fieldData[0];
  411. string oldStr = fieldData[1];
  412. string newStr = fieldData[2];
  413. str = str.Replace(oldStr, newStr);
  414. sql = sql.Replace(m.Value, str);
  415. }
  416. if(item.ExcuteFlag == 1)
  417. {
  418. string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + sql + "\",\"FileName\":\"执行\",\"MaxCount\":\"50\",\"ConnectStr\":\"" + ConnectStr + "\"}";
  419. RedisDbconn.Instance.AddList("ExportQueue", SendData);
  420. }
  421. else if(item.ExcuteFlag == 2)
  422. {
  423. string redisCommand = sql;
  424. string[] redisCommandList = redisCommand.Split(' ');
  425. string kind = redisCommandList[0];
  426. string key = redisCommandList[1];
  427. string val = redisCommandList[2];
  428. if(kind == "lpush")
  429. {
  430. new CustomRedisDbconn(ConnectStr).AddList(key, val);
  431. }
  432. else if(kind == "set")
  433. {
  434. new CustomRedisDbconn(ConnectStr).Set(key, val);
  435. }
  436. else if(kind == "set")
  437. {
  438. new CustomRedisDbconn(ConnectStr).AddInt(key, int.Parse(val));
  439. }
  440. else if(kind == "set")
  441. {
  442. new CustomRedisDbconn(ConnectStr).AddNumber(key, decimal.Parse(val));
  443. }
  444. }
  445. return "success";
  446. }
  447. #endregion
  448. #region 获取链接数据库字符串
  449. public string GetConnectStr(string key)
  450. {
  451. return Library.ConfigurationManager.AppSettings[key].ToString();
  452. }
  453. #endregion
  454. }
  455. }