CustomQueryController.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. string Control = "text";
  287. string Option = "";
  288. if(fieldData.Length > 2)
  289. {
  290. Control = fieldData[2];
  291. if(Control == "select")
  292. {
  293. Option = fieldData[3];
  294. }
  295. }
  296. if(!query.ContainsKey(fieldName))
  297. {
  298. query.Add(fieldName, Title + "#cut#" + Control + "#cut#" + Option);
  299. }
  300. }
  301. List<CustomQuerySub> subItems = db.CustomQuerySub.Where(m => m.ParentId == Id).ToList();
  302. foreach(CustomQuerySub sub in subItems)
  303. {
  304. sql = sub.SqlContent;
  305. mc = Regex.Matches(sql, @"\$\{.*?\}\$");
  306. foreach(Match m in mc)
  307. {
  308. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  309. string fieldName = fieldData[0];
  310. string Title = fieldData[1];
  311. string Control = "text";
  312. string Option = "";
  313. if(fieldData.Length > 2)
  314. {
  315. Control = fieldData[2];
  316. if(Control == "select")
  317. {
  318. Option = fieldData[3];
  319. }
  320. }
  321. if(!query.ContainsKey(fieldName))
  322. {
  323. query.Add(fieldName, Title + "#cut#" + Control + "#cut#" + Option);
  324. }
  325. }
  326. }
  327. ViewBag.query = query;
  328. return View();
  329. }
  330. #endregion
  331. #region 自定义提交
  332. /// <summary>
  333. /// 自定义提交
  334. /// </summary>
  335. /// <returns></returns>
  336. [HttpPost]
  337. public string Confirm(int Id)
  338. {
  339. var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
  340. CustomQuery item = db.CustomQuery.FirstOrDefault(m => m.Id == Id) ?? new CustomQuery();
  341. string ConnectStr = "";
  342. Dictionary<string, string> dicVals = new Dictionary<string, string>();
  343. List<CustomQuerySub> subItems = db.CustomQuerySub.Where(m => m.ParentId == Id).ToList();
  344. foreach(CustomQuerySub sub in subItems)
  345. {
  346. ConnectStr = sub.DatabaseConnect;
  347. if(!string.IsNullOrEmpty(ConnectStr))
  348. {
  349. ConnectStr = GetConnectStr(sub.DatabaseConnect);
  350. }
  351. else
  352. {
  353. if(item.ExcuteFlag == 2)
  354. {
  355. ConnectStr = MysqlConn.RedisConnStr;
  356. }
  357. else
  358. {
  359. ConnectStr = MysqlConn.ReadSqlConnStr;
  360. }
  361. }
  362. string sqlstr = sub.SqlContent;
  363. MatchCollection mcsub = Regex.Matches(sqlstr, @"\$\{.*?\}\$");
  364. foreach(Match m in mcsub)
  365. {
  366. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  367. string fieldName = fieldData[0];
  368. sqlstr = sqlstr.Replace(m.Value, Request.Query[fieldName].ToString());
  369. }
  370. mcsub = Regex.Matches(sqlstr, @"\#\{.*?\}\#");
  371. foreach(Match m in mcsub)
  372. {
  373. string fieldName = m.Value.Replace("#{", "").Replace("}#", "");
  374. if(dicVals.ContainsKey(fieldName))
  375. {
  376. sqlstr = sqlstr.Replace(m.Value, dicVals[fieldName]);
  377. }
  378. }
  379. DataTable dtsub = CustomerSqlConn.dtable(sqlstr, ConnectStr);
  380. if(dtsub.Rows.Count > 0)
  381. {
  382. if(dtsub.Rows.Count > 1)
  383. {
  384. string val = "";
  385. foreach(DataRow dr in dtsub.Rows)
  386. {
  387. val += dr[0].ToString() + ",";
  388. }
  389. val = val.TrimEnd(',');
  390. dicVals.Add(sub.Alias + "." + dtsub.Columns[0].ColumnName, val);
  391. }
  392. else
  393. {
  394. DataRow dr = dtsub.Rows[0];
  395. foreach(DataColumn dc in dtsub.Columns)
  396. {
  397. dicVals.Add(sub.Alias + "." + dc.ColumnName, dr[dc.ColumnName].ToString());
  398. }
  399. }
  400. }
  401. }
  402. ConnectStr = item.DatabaseConnect;
  403. if(!string.IsNullOrEmpty(ConnectStr))
  404. {
  405. ConnectStr = GetConnectStr(item.DatabaseConnect);
  406. }
  407. else
  408. {
  409. if(item.ExcuteFlag == 2)
  410. {
  411. ConnectStr = MysqlConn.RedisConnStr;
  412. }
  413. else
  414. {
  415. ConnectStr = MysqlConn.ReadSqlConnStr;
  416. }
  417. }
  418. string sql = item.SqlContent;
  419. MatchCollection mc = Regex.Matches(sql, @"\$\{.*?\}\$");
  420. foreach(Match m in mc)
  421. {
  422. string[] fieldData = m.Value.Replace("${", "").Replace("}$", "").Split('|');
  423. string fieldName = fieldData[0];
  424. sql = sql.Replace(m.Value, Request.Form[fieldName].ToString());
  425. }
  426. mc = Regex.Matches(sql, @"\$\replace{.*?\}\$");
  427. foreach(Match m in mc)
  428. {
  429. string[] fieldData = m.Value.Replace("$replace{", "").Replace("}$", "").Split('|');
  430. string str = fieldData[0];
  431. string oldStr = fieldData[1];
  432. string newStr = fieldData[2];
  433. str = str.Replace(oldStr, newStr);
  434. sql = sql.Replace(m.Value, str);
  435. }
  436. if(item.ExcuteFlag == 1)
  437. {
  438. string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + sql + "\",\"FileName\":\"执行\",\"MaxCount\":\"50\",\"ConnectStr\":\"" + ConnectStr + "\"}";
  439. RedisDbconn.Instance.AddList("ExportQueue", SendData);
  440. }
  441. else if(item.ExcuteFlag == 3)
  442. {
  443. string redisCommand = sql;
  444. string[] redisCommandList = redisCommand.Split(' ');
  445. string kind = redisCommandList[0];
  446. string key = redisCommandList[1];
  447. string val = redisCommandList[2];
  448. if(kind == "lpush")
  449. {
  450. if(val.Contains("\n"))
  451. {
  452. string[] vals = val.TrimEnd('\n').Split('\n');
  453. foreach(string sub in vals)
  454. {
  455. new CustomRedisDbconn(ConnectStr).AddList(key, sub);
  456. }
  457. }
  458. else
  459. {
  460. new CustomRedisDbconn(ConnectStr).AddList(key, val);
  461. }
  462. }
  463. else if(kind == "set")
  464. {
  465. new CustomRedisDbconn(ConnectStr).Set(key, val);
  466. }
  467. else if(kind == "addint")
  468. {
  469. new CustomRedisDbconn(ConnectStr).AddInt(key, int.Parse(val));
  470. }
  471. else if(kind == "addnum")
  472. {
  473. new CustomRedisDbconn(ConnectStr).AddNumber(key, decimal.Parse(val));
  474. }
  475. }
  476. AddSysLog("0", "CustomQuery", "Confirm");
  477. return "success";
  478. }
  479. #endregion
  480. #region 获取链接数据库字符串
  481. public string GetConnectStr(string key)
  482. {
  483. return Library.ConfigurationManager.AppSettings[key].ToString();
  484. }
  485. #endregion
  486. }
  487. }