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