MacStatusTotalDal.cs 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using Cksoft.Unity;
  4. using DllEapEntity;
  5. using DllEapEntity.Dtos;
  6. using DllEapEntity.Enums;
  7. using DllEapEntity.OFILM;
  8. using DllHsms;
  9. using Microsoft.Extensions.Configuration;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Threading.Tasks;
  16. namespace DllEapDal.OFILM
  17. {
  18. /// <summary>
  19. /// WEB版机台状态看板数据处理
  20. /// </summary>
  21. public class MacStatusTotalDal
  22. {
  23. string timeFormat = "yyyy-MM-dd HH:mm:ss";
  24. private IEnumerable<StandardStatus> standardStatuses;
  25. private IEnumerable<Machine> machines;
  26. private IDatabase CurrDb = null;
  27. private readonly IConfiguration configuration;
  28. private string svidFilter = " and a.AlarmCode<>'SVID'";
  29. public MacStatusTotalDal()
  30. {
  31. }
  32. public MacStatusTotalDal(IDatabase db)
  33. {
  34. CurrDb = db;
  35. }
  36. public MacStatusTotalDal(IDatabase db, IConfiguration configuration)
  37. {
  38. CurrDb = db;
  39. this.configuration = configuration;
  40. }
  41. public MacStatusTotalDal(IDatabase db, IConfiguration configuration,
  42. IEnumerable<StandardStatus> standardStatuses, IEnumerable<Machine> machines)
  43. {
  44. CurrDb = db;
  45. this.configuration = configuration;
  46. this.machines = machines;
  47. this.standardStatuses = standardStatuses;
  48. }
  49. /// <summary>
  50. /// 获取所有机台的状态
  51. /// </summary>
  52. /// <param name="filter"></param>
  53. /// <param name="errorinfo"></param>
  54. /// <returns></returns>
  55. public IEnumerable<MacStatusForDashboardDto> Get(string filter, string date, string type, ref string errorinfo)
  56. {
  57. var dateNow = DateTime.Now;
  58. DateTime dateStart;
  59. DateTime dateEnd;
  60. EnumShift enumShift = EnumShift.Day;
  61. if (type == "1")
  62. {
  63. enumShift = EnumShift.Day;
  64. }
  65. else if (type == "2")
  66. {
  67. enumShift = EnumShift.Night;
  68. }
  69. else
  70. {
  71. enumShift = EnumShift.Full;
  72. }
  73. if (string.IsNullOrEmpty(date) || Convert.ToDateTime(date).ToString("yyyy-MM-dd") == dateNow.ToString("yyyy-MM-dd"))
  74. {
  75. if (dateNow <= new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 20, 30, 0)
  76. && dateNow > new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 8, 30, 0))
  77. {
  78. dateStart = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 8, 30, 0);
  79. }
  80. else
  81. {
  82. var yesterday = dateNow.AddDays(-1);
  83. dateStart = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, 20, 30, 0);
  84. }
  85. dateEnd = dateNow;
  86. }
  87. else
  88. {
  89. dateNow = Convert.ToDateTime(date);
  90. if (type == "1")//白班
  91. {
  92. dateStart = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 8, 30, 0);
  93. dateEnd = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 20, 30, 0);
  94. }
  95. else if (type == "2")//夜班
  96. {
  97. var tomorrow = dateNow.AddDays(1);
  98. dateStart = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 20, 30, 0);
  99. dateEnd = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, 8, 30, 0);
  100. }
  101. else//整天
  102. {
  103. var tomorrow = dateNow.AddDays(1);
  104. dateStart = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 8, 30, 0);
  105. dateEnd = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, 8, 30, 0);
  106. }
  107. }
  108. var status = new List<MacStatusForDashboardDto>();
  109. standardStatuses = CurrDb.FindListForCondition<StandardStatus>(string.Empty, ref errorinfo);
  110. if (standardStatuses == null || standardStatuses.Count() <= 0)
  111. {
  112. errorinfo = "机台标准状态为空";
  113. return null;
  114. }
  115. var idle = standardStatuses.FirstOrDefault(c => c.FCode.ToUpper() == "IDLE");
  116. var disconn = standardStatuses.FirstOrDefault(t => t.FCode.ToUpper() == "DISCONN");
  117. var sql = $@"select a.FCode maccode,c.pcode processCode,{OfilmRecipeProvider.GenRecipeString("b")} recipe,
  118. b.StatusID status,b.STime,b.ETime,b.alarmCode,
  119. ifnull(d.FName,'离线') statusName,ifnull(d.FCode,'DISCONN') statusCode,f.FName factory,e.FCode macmodel,
  120. ifnull(d.red,178) red ,ifnull(d.green,178) green,ifnull(d.blue,178) blue,
  121. ifnull(d.alpha,178) alpha,i.FName floor,h.FName line,i.Rank floorRank,
  122. h.Rank lineRank,
  123. l.fname plant,g.rank,g.UseImage
  124. from machine a
  125. left join macstatus01 b on a.FCode=b.maccode
  126. left join mactprocess c on a.id=c.macid
  127. left join standardstatus d on b.statusid=d.StatusVal
  128. left join macmodel e on a.MModeId=e.id
  129. left join factoryregion f on a.factoryId = f.id
  130. left join tprocess g on c.pcode=g.fcode
  131. left join factoryregion h on a.regionid=h.id
  132. left join factoryregion i on h.parentid=i.id
  133. left join factoryregion l on i.parentid=l.id
  134. where 1=1 and b.STime is not null {filter} order by i.Rank,h.Rank,macCode asc";
  135. var macLastHistories = new List<MacLastStatus>();
  136. var allMachines = CurrDb.FindList<MacStatusForDashboardDto>(sql);
  137. var statusNames = _getTableNames("macstatus", dateStart, dateEnd);
  138. var viewLastStausName = string.Empty;
  139. var temporaryName = string.Empty;
  140. List<MacStatusForDashboardDto> lastStatuses = new List<MacStatusForDashboardDto>(); ;
  141. // 当前日期不是选中的日期
  142. if (!(dateStart.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")
  143. || (dateStart.ToString("yyyy-MM-dd") == DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")
  144. && DateTime.Now < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 08:30")))))
  145. {
  146. // 历史数据查询历史稼动率数据表
  147. if (enumShift == EnumShift.Full)
  148. {
  149. sql = $@"select a.FCode maccode,c.pcode processCode,b.Remark recipe,
  150. b.StatusID status,b.STime,
  151. ifnull(d.FName, '离线') statusName,ifnull(d.FCode, 'DISCONN') statusCode,f.FName factory,e.FCode macmodel,
  152. ifnull(d.red, 178) red ,ifnull(d.green, 178) green,ifnull(d.blue, 178) blue,
  153. ifnull(d.alpha, 178) alpha,i.FName floor, h.FName line, i.Rank floorRank,
  154. h.Rank lineRank,l.fname plant, g.rank,g.UseImage
  155. from machine a
  156. left join maclaststatus b on a.FCode = b.maccode
  157. left join mactprocess c on a.id = c.macid
  158. left join standardstatus d on b.statusid = d.StatusVal
  159. left join macmodel e on a.MModeId = e.id
  160. left join factoryregion f on a.factoryId = f.id
  161. left join tprocess g on c.pcode = g.fcode
  162. left join factoryregion h on a.regionid = h.id
  163. left join factoryregion i on h.parentid = i.id
  164. left join factoryregion l on i.parentid = l.id
  165. where 1 = 1 and b.FDate='{dateStart.ToString("yyyy-MM-dd")}'
  166. and shift = {(int)EnumShift.Night} { filter}
  167. order by i.Rank,h.Rank,macCode asc";
  168. lastStatuses = CurrDb.FindList<MacStatusForDashboardDto>(sql).ToList();
  169. sql = $@"select sum(runrate*100)/2 as value,maccode as name from maclaststatus
  170. where fdate='{dateStart.ToString("yyyy-MM-dd 00:00:00")}'
  171. group by maccode";
  172. var historyRunrates = CurrDb.FindList<RunRateDto>(sql);
  173. if (historyRunrates.Any())
  174. {
  175. Parallel.ForEach(lastStatuses, item =>
  176. {
  177. item.RunRate = historyRunrates.FirstOrDefault(c => c.Name == item.MacCode)?.Value ?? 0;
  178. });
  179. }
  180. }
  181. else
  182. {
  183. sql = $@"select a.FCode maccode,c.pcode processCode,b.Remark recipe,
  184. b.StatusID status,b.STime,
  185. ifnull(d.FName, '离线') statusName,ifnull(d.FCode, 'DISCONN') statusCode,f.FName factory, e.FCode macmodel,
  186. ifnull(d.red, 178) red ,ifnull(d.green, 178) green,ifnull(d.blue, 178) blue,
  187. ifnull(d.alpha, 178) alpha,i.FName floor, h.FName line, i.Rank floorRank,
  188. h.Rank lineRank,l.fname plant, g.rank,g.UseImage,b.runrate*100
  189. from machine a
  190. left join maclaststatus b on a.FCode = b.maccode
  191. left join mactprocess c on a.id = c.macid
  192. left join standardstatus d on b.statusid = d.StatusVal
  193. left join macmodel e on a.MModeId = e.id
  194. left join factoryregion f on a.factoryId = f.id
  195. left join tprocess g on c.pcode = g.fcode
  196. left join factoryregion h on a.regionid = h.id
  197. left join factoryregion i on h.parentid = i.id
  198. left join factoryregion l on i.parentid = l.id
  199. where 1 = 1 and b.FDate='{dateStart.ToString("yyyy-MM-dd")}'
  200. and shift = {(int)enumShift} { filter}
  201. order by i.Rank,h.Rank,macCode asc";
  202. lastStatuses = CurrDb.FindList<MacStatusForDashboardDto>(sql).ToList();
  203. }
  204. if (!lastStatuses.Any() || lastStatuses.All(c => c.RunRate == 0))
  205. {
  206. // 查询结束时间前2个小时的状态存入临时视图,减小数据量,用新生成的视图查询最后的状态
  207. // 并关联其他表取基础信息
  208. var tempStart = dateEnd.AddHours(-2);
  209. viewLastStausName = $"v_temp_last_status_{DateTime.Now.Ticks}";
  210. var createLastStatusSql = $"CREATE OR REPLACE VIEW {viewLastStausName} AS ";
  211. createLastStatusSql += $" SELECT * FROM {statusNames.Last()} " +
  212. $"WHERE STime>'{tempStart.ToString("yyyy-MM-dd HH:mm:ss")}' " +
  213. $"AND STime<'{dateEnd.ToString("yyyy-MM-dd HH:mm:ss")}';";
  214. CurrDb.ExecuteBySql(createLastStatusSql);
  215. temporaryName = $"macstatus_last_temp_{DateTime.Now.Ticks}";
  216. // 将最后的记录放到临时表里
  217. createLastStatusSql = $@"CREATE TEMPORARY TABLE {temporaryName}
  218. select * from {viewLastStausName} where id in (select max(id) from
  219. {viewLastStausName} group by maccode);";
  220. CurrDb.ExecuteBySql(createLastStatusSql);
  221. // 查询历史数据
  222. sql = $@"select a.FCode maccode,c.pcode processCode,{OfilmRecipeProvider.GenRecipeString("b")} recipe,
  223. b.StatusID status, b.STime,b.ETime,b.alarmCode,
  224. ifnull(d.FName, '离线') statusName,ifnull(d.FCode, 'DISCONN') statusCode,f.FName factory, e.FCode macmodel,
  225. ifnull(d.red, 178) red ,ifnull(d.green, 178) green,ifnull(d.blue, 178) blue,
  226. ifnull(d.alpha, 178) alpha,i.FName floor, h.FName line, i.Rank floorRank,
  227. h.Rank lineRank,l.fname plant, g.rank,g.UseImage
  228. from machine a
  229. left join {temporaryName} b on a.FCode = b.maccode
  230. left join mactprocess c on a.id = c.macid
  231. left join standardstatus d on b.statusid = d.StatusVal
  232. left join macmodel e on a.MModeId = e.id
  233. left join factoryregion f on a.factoryId = f.id
  234. left join tprocess g on c.pcode = g.fcode
  235. left join factoryregion h on a.regionid = h.id
  236. left join factoryregion i on h.parentid = i.id
  237. left join factoryregion l on i.parentid = l.id
  238. where 1 = 1 and b.STime is not null { filter}
  239. order by i.Rank,h.Rank,macCode asc";
  240. var lastDal = new MacLastStatusDal(CurrDb);
  241. macLastHistories = lastDal.GetLastStatus(dateStart, enumShift).Result.ToList();
  242. lastStatuses = CurrDb.FindList<MacStatusForDashboardDto>(sql).ToList();
  243. }
  244. }
  245. else
  246. {
  247. // 查询最新数据
  248. sql = $@"select a.FCode maccode,c.pcode processCode,{OfilmRecipeProvider.GenRecipeString("b")} recipe,
  249. b.StatusID status, b.STime,b.ETime,b.alarmCode,
  250. ifnull(d.FName, '离线') statusName,ifnull(d.FCode, 'DISCONN') statusCode,f.FName factory, e.FCode macmodel,
  251. ifnull(d.red, 178) red ,ifnull(d.green, 178) green,ifnull(d.blue, 178) blue,
  252. ifnull(d.alpha, 178) alpha,i.FName floor, h.FName line, i.Rank floorRank,
  253. h.Rank lineRank,l.fname plant, g.rank,g.UseImage
  254. from machine a
  255. left join macstatus01 b on a.FCode = b.maccode
  256. left join mactprocess c on a.id = c.macid
  257. left join standardstatus d on b.statusid = d.StatusVal
  258. left join macmodel e on a.MModeId = e.id
  259. left join factoryregion f on a.factoryId = f.id
  260. left join tprocess g on c.pcode = g.fcode
  261. left join factoryregion h on a.regionid = h.id
  262. left join factoryregion i on h.parentid = i.id
  263. left join factoryregion l on i.parentid = l.id
  264. where 1 = 1 and b.STime is not null { filter}
  265. order by i.Rank,h.Rank,macCode asc";
  266. lastStatuses = CurrDb.FindList<MacStatusForDashboardDto>(sql).ToList();
  267. }
  268. var excepts = new List<MacStatusForDashboardDto>();
  269. if (lastStatuses.Count() < allMachines.Count())
  270. {
  271. excepts = allMachines.Where(c => lastStatuses.All(t => t.MacCode != c.MacCode)).ToList();
  272. lastStatuses.AddRange(excepts.Select(c =>
  273. {
  274. c.RunRate = 0;
  275. return c;
  276. }));
  277. }
  278. // 删除生成的视图和临时表
  279. if (!string.IsNullOrEmpty(viewLastStausName))
  280. {
  281. var dropSql = $"DROP VIEW IF EXISTS {viewLastStausName};";
  282. CurrDb.ExecuteBySql(dropSql);
  283. dropSql = $"DROP TABLE IF EXISTS {temporaryName};";
  284. CurrDb.ExecuteBySql(dropSql);
  285. }
  286. foreach (var item in lastStatuses)
  287. {
  288. var temp = item;
  289. temp.Color = new RgbColor(temp.Red.Value, temp.Green.Value, temp.Blue.Value,
  290. temp.Alpha.Value);
  291. if (temp.Status == 5 || (temp.Status == 6 && temp.AlarmCode == "SVID"))
  292. {
  293. temp.Status = idle.ID;
  294. temp.StatusCode = idle.FCode;
  295. temp.StatusName = idle.FName;
  296. temp.Color = new RgbColor(idle.Red, idle.Green, idle.Blue, idle.Alpha);
  297. }
  298. if (string.IsNullOrEmpty(temp.Recipe) || string.IsNullOrWhiteSpace(temp.Recipe)
  299. || temp.Recipe == "\0")
  300. {
  301. temp.Recipe = "暂无";
  302. }
  303. decimal timeLen = 0;
  304. if (temp.STime == null)
  305. {
  306. timeLen = 0;
  307. }
  308. else
  309. {
  310. timeLen = (decimal)(dateEnd - temp.STime.Value).TotalSeconds;
  311. timeLen = timeLen < 0 ? 0 : timeLen;
  312. if (macLastHistories.Count > 0)
  313. {
  314. var lastHistory = macLastHistories.FirstOrDefault(c => c.MacCode == temp.MacCode);
  315. if (lastHistory != null && lastHistory.StatusId == temp.Status)
  316. {
  317. timeLen = (decimal)lastHistory.Flen;
  318. }
  319. }
  320. }
  321. temp.TimeLen = timeLen;
  322. status.Add(temp);
  323. }
  324. IEnumerable<RunRateDto> runTimes = null;
  325. var totalTimeLen = (dateEnd - dateStart).TotalSeconds;
  326. if (dateStart.ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd"))
  327. {
  328. if (status.All(c => c.RunRate == 0))
  329. {
  330. if (dateStart < DateTime.Now.AddDays(-30))
  331. {
  332. var viewName = $"V_MacStatus_Dashboard_{DateTime.Now.Ticks}";
  333. var createSql = $"CREATE TEMPORARY TABLE {viewName} ";
  334. for (int i = 0; i < statusNames.Count(); i++)
  335. {
  336. createSql += $@"select sum(tt.flen) as Value,tt.maccode as Name from (
  337. select sum(flen) flen,maccode from {statusNames.ElementAt(i)} where stime>'{dateStart.ToString(timeFormat)}' and stime<'{dateEnd.ToString(timeFormat)}' and statusid=4
  338. group by maccode
  339. union all
  340. select time_to_sec(timediff('{dateEnd.ToString(timeFormat)}',stime)) as flen,maccode from {statusNames.ElementAt(i)} where
  341. statusid=4 and etime='0001-01-01 00:00:00' and flen=0 and stime>'{dateStart.ToString(timeFormat)}' and stime<'{dateEnd.ToString(timeFormat)}'
  342. union all
  343. select time_to_sec(timediff(etime, '{dateStart.ToString(timeFormat)}')) as flen,
  344. maccode from
  345. {statusNames.ElementAt(i)} where statusid=4 and stime<='{dateStart.ToString(timeFormat)}' and etime>'{dateStart.ToString(timeFormat)}'
  346. ) tt
  347. left join machine a on tt.maccode=a.fcode
  348. left join macstatus01 b on a.FCode=b.maccode
  349. left join mactprocess c on a.id=c.macid
  350. left join standardstatus d on b.statusid=d.StatusVal
  351. left join macmodel e on a.MModeId=e.id
  352. left join factoryregion f on a.factoryId = f.id
  353. left join tprocess g on c.pcode=g.fcode
  354. left join factoryregion h on a.regionid=h.id
  355. left join factoryregion i on h.parentid=i.id
  356. left join factoryregion l on i.parentid=l.id
  357. where 1=1 {filter} and h.FName not like '%试产%' group by tt.maccode";
  358. }
  359. createSql += " union all ";
  360. createSql = createSql.Substring(0, createSql.Length - 11);
  361. CurrDb.ExecuteBySql(createSql);
  362. sql = $"select sum(value) value,name from {viewName} group by name";
  363. runTimes = CurrDb.FindList<RunRateDto>(sql);
  364. sql = $"DROP TABLE IF EXISTS {viewName}";
  365. CurrDb.ExecuteBySql(sql);
  366. }
  367. else
  368. {
  369. runTimes = FindMacRunRates(dateStart, dateEnd, filter);
  370. }
  371. status = AppendMacRunRate(status, runTimes, totalTimeLen).ToList();
  372. }
  373. }
  374. else
  375. {
  376. runTimes = FindMacRunRates(dateStart, dateEnd, filter);
  377. status = AppendMacRunRate(status, runTimes, totalTimeLen).ToList();
  378. }
  379. return status;
  380. }
  381. /// <summary>
  382. /// 加上稼动率
  383. /// </summary>
  384. /// <param name="status"></param>
  385. /// <param name="runTimes"></param>
  386. /// <param name="totalTimeLen"></param>
  387. /// <returns></returns>
  388. private IEnumerable<MacStatusForDashboardDto> AppendMacRunRate(IEnumerable<MacStatusForDashboardDto> status,
  389. IEnumerable<RunRateDto> runTimes, double totalTimeLen)
  390. {
  391. Parallel.ForEach(status, item =>
  392. {
  393. var runTime = runTimes.FirstOrDefault(c => c.Name == item.MacCode);
  394. if (runTime == null)
  395. {
  396. item.RunRate = 0;
  397. }
  398. else
  399. {
  400. item.RunRate = runTime.Value / totalTimeLen * 100;
  401. }
  402. });
  403. return status;
  404. }
  405. /// <summary>
  406. /// 查询稼动率
  407. /// </summary>
  408. /// <param name="dateStart"></param>
  409. /// <param name="dateEnd"></param>
  410. /// <param name="filter"></param>
  411. /// <returns></returns>
  412. private IEnumerable<RunRateDto> FindMacRunRates(DateTime dateStart, DateTime dateEnd, string filter)
  413. {
  414. var sql = $@"select sum(tt.flen) as Value,tt.maccode as Name from (
  415. select sum(flen) flen,maccode from macstatus where stime>'{dateStart.ToString(timeFormat)}' and stime<'{dateEnd.ToString(timeFormat)}' and statusid=4
  416. group by maccode
  417. union all
  418. select time_to_sec(timediff('{dateEnd.ToString(timeFormat)}',stime)) as flen,maccode from macstatus where
  419. statusid=4 and etime='0001-01-01 00:00:00' and flen=0 and stime>'{dateStart.ToString(timeFormat)}' and stime<'{dateEnd.ToString(timeFormat)}'
  420. union all
  421. select time_to_sec(timediff(etime, '{dateStart.ToString(timeFormat)}')) as flen,
  422. maccode from
  423. macstatus where statusid=4 and stime<='{dateStart.ToString(timeFormat)}' and etime>'{dateStart.ToString(timeFormat)}'
  424. ) tt
  425. left join machine a on tt.maccode=a.fcode
  426. left join macstatus01 b on a.FCode=b.maccode
  427. left join mactprocess c on a.id=c.macid
  428. left join standardstatus d on b.statusid=d.StatusVal
  429. left join macmodel e on a.MModeId=e.id
  430. left join factoryregion f on a.factoryId = f.id
  431. left join tprocess g on c.pcode=g.fcode
  432. left join factoryregion h on a.regionid=h.id
  433. left join factoryregion i on h.parentid=i.id
  434. left join factoryregion l on i.parentid=l.id
  435. where 1=1 {filter} and h.FName not like '%试产%' group by tt.maccode";
  436. return CurrDb.FindList<RunRateDto>(sql);
  437. }
  438. /// <summary>
  439. /// 获取机台状态统计数据
  440. /// </summary>
  441. /// <param name="filter"></param>
  442. /// <param name="errorinfo"></param>
  443. /// <returns></returns>
  444. public MacStatusTotalInfo GetTotalInfo(string filter, string recipeName, string date, string type, ref string errorinfo)
  445. {
  446. var datas = this.Get(filter, date, type, ref errorinfo).Where(c => !string.IsNullOrEmpty(c.ProcessCode));
  447. if (!string.IsNullOrEmpty(recipeName))
  448. {
  449. datas = datas.Where(c => c.Recipe.Contains(recipeName));
  450. }
  451. if (datas == null || datas.Count() <= 0)
  452. {
  453. return null;
  454. }
  455. var factory = datas.FirstOrDefault(c => !string.IsNullOrEmpty(c.Factory)).Factory;
  456. var plant = datas.FirstOrDefault(c => !string.IsNullOrEmpty(c.Plant)).Plant;
  457. var total = datas.Count(); // 机台总数量
  458. var statusGroups = datas.Where(c => !string.IsNullOrEmpty(c.StatusCode)).GroupBy(c => c.StatusName);
  459. IList<Status> dic = null;
  460. if (statusGroups != null && statusGroups.Count() > 0)
  461. {
  462. dic = new List<Status>();
  463. foreach (var item in statusGroups)
  464. {
  465. var standard = standardStatuses.FirstOrDefault(s => s.FName == item.Key);
  466. var temp = new Status
  467. {
  468. StatusCode = standard.FCode,
  469. StatusName = standard.FName,
  470. Count = item.Count(),
  471. Color = new RgbColor(standard.Red, standard.Green, standard.Blue)
  472. };
  473. dic.Add(temp);
  474. }
  475. }
  476. var model = new MacStatusTotalInfo();
  477. model.StatusCount = dic;
  478. model.Total = total;
  479. model.Factory = factory;
  480. model.Plant = plant;
  481. var lineGroups = datas.GroupBy(c => new { c.Floor, c.FloorRank, c.Line, c.LineRank })
  482. .OrderBy(c => c.Key.FloorRank).ThenBy(c => c.Key.LineRank);
  483. var lines = new List<Line>();
  484. foreach (var item in lineGroups)
  485. {
  486. string recipe = null;
  487. var modelDic = new Dictionary<string, IEnumerable<MacStatusForDashboardDto>>();
  488. var pcodeGroups = item.GroupBy(c => new { c.ProcessCode, c.Rank }).OrderBy(c => c.Key.Rank);
  489. if (pcodeGroups != null && pcodeGroups.Count() > 0)
  490. {
  491. foreach (var group in pcodeGroups)
  492. {
  493. modelDic.Add(group.Key.ProcessCode.ToLower(), group.AsEnumerable());
  494. }
  495. }
  496. lines.Add(new Line
  497. {
  498. Recipe = recipe,
  499. FloorName = item.Key.Floor,
  500. LineName = item.Key.Line,
  501. ModelMachines = modelDic
  502. });
  503. }
  504. model.Lines = lines;
  505. var processRates = this.GetRunRates(datas);
  506. var chartDto = new ChartDto2
  507. {
  508. text = "各个工序稼动率",
  509. legend = new string[] { "稼动率" },
  510. xdata = processRates.Select(c => c.Name).ToArray(),
  511. ydata = processRates.Select(c => c.Value).ToArray()
  512. };
  513. model.ProcessRunRate = chartDto;
  514. return model;
  515. }
  516. /// <summary>
  517. /// 获取各个工序稼动率
  518. /// </summary>
  519. /// <param name="filter"></param>
  520. /// <param name="take"></param>
  521. /// <returns></returns>
  522. public ChartDto2 GetProcessRunRate(string filter, string recipe, DateTime dateStart, DateTime dateEnd, ref string errorinfo)
  523. {
  524. var dto = this.GetRunRates(filter, recipe, dateStart, dateEnd, ref errorinfo);
  525. var chartDto = new ChartDto2
  526. {
  527. text = "各个工序稼动率",
  528. legend = new string[] { "稼动率" },
  529. xdata = dto.Select(c => c.Name).ToArray(),
  530. ydata = dto.Select(c => c.Value).ToArray()
  531. //ydata = new double[] { 0.9, 0.1, 0.5, 1.3 }
  532. };
  533. return chartDto;
  534. }
  535. public ChartDto2 GetProcessRunRate(string filter, string date, string type, string recipe, ref string errorinfo)
  536. {
  537. var dto = this.GetRunRates2(filter, date, type, recipe, ref errorinfo);
  538. var chartDto = new ChartDto2
  539. {
  540. text = "各个工序稼动率",
  541. legend = new string[] { "稼动率" },
  542. xdata = dto.Select(c => c.Name).ToArray(),
  543. ydata = dto.Select(c => c.Value).ToArray()
  544. //ydata = new double[] { 0.9, 0.1, 0.5, 1.3 }
  545. };
  546. return chartDto;
  547. }
  548. private IEnumerable<RunRateDto> GetRunRates(string filter, string recipe, DateTime dateStart,
  549. DateTime dateEnd, ref string errorinfo)
  550. {
  551. var regex = new Regex($"and b.statusId in (.*\\))");
  552. var statusFilter = filter;
  553. var match = regex.Match(statusFilter);
  554. if (match != null && !string.IsNullOrEmpty(match.Value))
  555. {
  556. statusFilter = statusFilter.Replace(match.Value, "");
  557. }
  558. var recipeFilter = "";
  559. if (!string.IsNullOrEmpty(recipe))
  560. {
  561. recipeFilter += $" and b.remark like '%{recipe}%'";
  562. }
  563. var machines = GetDisconnMacs(dateStart, statusFilter, ref errorinfo);
  564. var macFilter = string.Empty;
  565. if (machines != null && machines.Count() > 0)
  566. {
  567. macFilter = $" and a.FCode in ({string.Join(",", machines.Select(c => $"'{c.FCode}'"))})";
  568. }
  569. string sql = "";
  570. if (dateStart.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
  571. {
  572. sql = $@"select sum(flen) as TimeLen,c.pcode as ProcessCode from
  573. (select sum(flen) flen,b.maccode from macstatus b
  574. where b.statusid=4 and b.stime>=STR_TO_DATE('{dateStart.ToString("yyyy-MM-dd HH:mm:ss")}', '%Y-%m-%d %H:%i:%s') and
  575. b.etime<=STR_TO_DATE( '{dateEnd.ToString("yyyy-MM-dd HH:mm:ss")}', '%Y-%m-%d %H:%i:%s') {recipeFilter} group by maccode
  576. union all
  577. select time_to_sec(sum(timediff('{dateEnd.ToString(timeFormat)}',stime))) as flen,maccode from macstatus where
  578. statusid=4 and etime='0001-01-01 00:00:00' and flen=0 and stime>'{dateStart.ToString(timeFormat)}' group by maccode
  579. union all
  580. select time_to_sec(sum(timediff(etime, '{dateStart.ToString(timeFormat)}'))) as flen,
  581. maccode from macstatus where statusid=4 and stime<='{dateStart.ToString(timeFormat)}' and etime>'{dateStart.ToString(timeFormat)}' group by maccode
  582. ) as t
  583. left join machine a on t.maccode=a.fcode
  584. left join mactprocess c on a.id=c.macid
  585. left join tprocess g on c.pcode=g.FCode
  586. left join factoryregion h on a.regionid=h.id
  587. left join factoryregion i on h.parentid=i.id
  588. left join factoryregion l on i.parentid=l.id
  589. where 1=1 and h.FName not like '%试产%' {statusFilter} {macFilter}
  590. group by c.pcode";
  591. }
  592. else
  593. {
  594. sql = $@"select sum(flen) as TimeLen,c.pcode as ProcessCode from (select b.maccode,sum(flen) flen from macstatus b
  595. where b.statusid=4 and b.stime>=STR_TO_DATE('{dateStart.ToString("yyyy-MM-dd HH:mm:ss")}', '%Y-%m-%d %H:%i:%s') and
  596. b.etime<=STR_TO_DATE( '{dateEnd.ToString("yyyy-MM-dd HH:mm:ss")}', '%Y-%m-%d %H:%i:%s') {recipeFilter} group by maccode
  597. union all
  598. select time_to_sec(sum(timediff('{dateEnd.ToString(timeFormat)}',stime))) as flen,maccode from macstatus where
  599. statusid=4 and etime='0001-01-01 00:00:00' and flen=0 and stime>'{dateStart.ToString(timeFormat)}' and stime<'{dateEnd.ToString(timeFormat)}' group by maccode
  600. union all
  601. select time_to_sec(sum(timediff(etime, '{dateStart.ToString(timeFormat)}'))) as flen,
  602. maccode from macstatus where statusid=4 and stime<='{dateStart.ToString(timeFormat)}' and etime>'{dateStart.ToString(timeFormat)}' group by maccode
  603. ) as t
  604. left join machine a on t.maccode=a.fcode
  605. left join mactprocess c on a.id=c.macid
  606. left join tprocess g on c.pcode=g.FCode
  607. left join factoryregion h on a.regionid=h.id
  608. left join factoryregion i on h.parentid=i.id
  609. left join factoryregion l on i.parentid=l.id
  610. where 1=1 and h.FName not like '%试产%' {statusFilter} {macFilter}
  611. group by c.pcode";
  612. }
  613. var runTimes = CurrDb.FindList<RunTime>(sql);
  614. var rates = new List<RunRateDto>();
  615. var currTimeLen = (dateEnd - dateStart).TotalSeconds;
  616. var codes = CurrDb.FindListForCondition<TProcess>($" and a.ShowChart=1", ref errorinfo).OrderBy(c => c.Rank)
  617. .Select(c => c.FCode);
  618. //var macRunrates =
  619. //foreach (var item in runTimes)
  620. //{
  621. //}
  622. foreach (var item in codes)
  623. {
  624. var count = machines.Count(c => c.PCode == item);
  625. var runTime = runTimes.FirstOrDefault(c => c.ProcessCode == item);
  626. double rate = 0;
  627. if (runTime != null && count != 0)
  628. {
  629. rate = Convert.ToDouble(runTime.TimeLen) / Convert.ToDouble(count) / currTimeLen;
  630. }
  631. rates.Add(new RunRateDto
  632. {
  633. Name = item,
  634. Value = rate
  635. });
  636. }
  637. return rates;
  638. }
  639. private IEnumerable<RunRateDto> GetRunRates2(string filter, string date, string type, string recipe, ref string errorinfo)
  640. {
  641. var rates = new List<RunRateDto>();
  642. var codes = CurrDb.FindListForCondition<TProcess>($" and a.ShowChart=1", ref errorinfo).OrderBy(c => c.Rank)
  643. .Select(c => c.FCode);
  644. if (!string.IsNullOrEmpty(recipe))
  645. {
  646. filter += $" and b.remark like '%{recipe}%'";
  647. }
  648. var macStatuses = this.Get(filter, date, type, ref errorinfo);
  649. // var machines = GetDisconnMacs(Convert.ToDateTime(date), filter, ref errorinfo);
  650. if (macStatuses != null && macStatuses.Count() > 0)
  651. {
  652. foreach (var item in codes)
  653. {
  654. var count = macStatuses.Where(c => c.UseImage == item && c.Status != 1 && c.Status != 204906).Count();
  655. double rate = 0;
  656. if (count > 0)
  657. {
  658. //var runTime = runTimes.FirstOrDefault(c => c.ProcessCode == item);
  659. rate = macStatuses.Where(c => c.UseImage == item && c.Status != 1 && c.Status != 204906).Sum(t => t.RunRate) / count / 100;
  660. }
  661. else
  662. {
  663. rate = 0;
  664. }
  665. rates.Add(new RunRateDto
  666. {
  667. Name = item,
  668. Value = rate
  669. });
  670. }
  671. }
  672. return rates;
  673. }
  674. /// <summary>
  675. /// 根据机台状态计算工序汇总的稼动率
  676. /// </summary>
  677. /// <param name="macStatuses"></param>
  678. /// <returns></returns>
  679. private IEnumerable<RunRateDto> GetRunRates(IEnumerable<MacStatusForDashboardDto> macStatuses)
  680. {
  681. string errorinfo = string.Empty;
  682. var rates = new List<RunRateDto>();
  683. var codes = CurrDb.FindListForCondition<TProcess>($" and a.ShowChart=1", ref errorinfo).OrderBy(c => c.Rank)
  684. .Select(c => c.FCode);
  685. if (macStatuses != null && macStatuses.Count() > 0)
  686. {
  687. foreach (var item in codes)
  688. {
  689. var count = macStatuses.Where(c => c.UseImage == item && c.Status != 1 && c.Status != 204906).Count();
  690. double rate = 0;
  691. if (count > 0)
  692. {
  693. rate = macStatuses.Where(c => c.UseImage == item && c.Status != 1 && c.Status != 204906).Sum(t => t.RunRate) / count / 100;
  694. }
  695. else
  696. {
  697. rate = 0;
  698. }
  699. rates.Add(new RunRateDto
  700. {
  701. Name = item,
  702. Value = rate
  703. });
  704. }
  705. }
  706. return rates;
  707. }
  708. /// <summary>
  709. /// 获取未断线及关机的机台
  710. /// </summary>
  711. /// <returns></returns>
  712. public IEnumerable<Machine> GetDisconnMacs(DateTime dateStart, string filter, ref string errorinfo)
  713. {
  714. var sql = $"SELECT maccode FROM eap.macstatus01 where stime<'{dateStart.ToString("yyyy-MM-dd HH:mm:ss")}' " +
  715. $"and etime='0001-01-01 00:00:00' and (StatusID=1 or StatusID=204906)";
  716. var macs = CurrDb.FindListForCondition<Machine>($" and a.FCode in ({sql}) ", ref errorinfo);
  717. return macs;
  718. }
  719. public MacStatusForDashboardDetailDto GetDetail(string maccode, string starttime, string endtime)
  720. {
  721. string errorinfo = string.Empty;
  722. var st = Convert.ToDateTime(starttime);
  723. string startMonthTime = Convert.ToDateTime(starttime).ToString("yyyy-MM-") + "01 00:00";
  724. string endMonthTime = Convert.ToDateTime(startMonthTime).AddMonths(1).ToString("yyyy-MM-01 00:00:00");
  725. double timediff = Convert.ToDateTime(endtime).Subtract(Convert.ToDateTime(starttime)).TotalHours;
  726. MacStatusForDashboardDetailDto macStatusForDashboardDetailDto = new MacStatusForDashboardDetailDto();
  727. string sqlstr = $" and a.FCode='{maccode}'";
  728. MacStatusForDashboardDto entity = Get(sqlstr, "", "", ref errorinfo)?.FirstOrDefault();//运行状态
  729. //var sql = $@" CALL GetTotalInfoDeatil ('{maccode}','{starttime}','{endtime}') ";
  730. #region sql
  731. var statusNames = _getTableNames("macstatus", st, st.AddDays(1));
  732. var countmstNames = _getTableNames("maccountmst", st, st.AddDays(1));
  733. var countDetailNames = _getTableNames("maccountdetail", st, st.AddDays(1));
  734. var viewName = $"V_MacStatus_Detail_{DateTime.Now.Ticks}";
  735. var createSql = $"CREATE OR REPLACE VIEW {viewName} AS ";
  736. for (int i = 0; i < statusNames.Count(); i++)
  737. {
  738. createSql += $@" select (SELECT
  739. COUNT(*)
  740. FROM
  741. {statusNames.ElementAt(i)} as A
  742. WHERE
  743. MacCode = '{maccode}'
  744. AND STime > '{starttime}'
  745. AND STime < '{endtime}'
  746. AND StatusID=6 AND AlarmCode<>'SVID') AlarmCount
  747. ,(SELECT
  748. ifnull(ROUND(SUM(FLen)/60),0)
  749. FROM
  750. macstatus
  751. WHERE
  752. MacCode = '{maccode}'
  753. AND STime > '{starttime}'
  754. AND STime < '{endtime}'
  755. AND StatusID=4) RunTime
  756. ,(SELECT ifnull(sum(c.FCount),0)
  757. FROM {countDetailNames.ElementAt(i)} as C
  758. LEFT JOIN {countmstNames.ElementAt(i)} as A ON A.ID=C.MstID
  759. LEFT JOIN machine as B on A.MacID=b.ID
  760. WHERE B.FCode='{maccode}'
  761. AND A.EDate>'{starttime}'
  762. AND A.EDate < '{endtime}'
  763. AND C.ParamCode='{StandardCode.SVID_FinishUnit}'
  764. AND C.TypeID=0) TodayCount
  765. ,( SELECT ifnull(sum(c.FCount),0)
  766. FROM {countDetailNames.ElementAt(i)} as C
  767. LEFT JOIN {countmstNames.ElementAt(i)} as A ON A.ID=C.MstID
  768. LEFT JOIN machine as B on A.MacID=b.ID
  769. WHERE B.FCode='{maccode}'
  770. AND A.SDate>'{startMonthTime}'
  771. AND A.SDate<'{endMonthTime}'
  772. AND C.ParamCode='{StandardCode.SVID_FinishUnit}'
  773. AND C.TypeID=0) MonthCount
  774. ";
  775. createSql += " union all ";
  776. }
  777. createSql = createSql.Substring(0, createSql.Length - 11);
  778. CurrDb.ExecuteBySql(createSql);
  779. var sql = $"select sum(AlarmCount) AlarmCount,sum(RunTime) RunTime," +
  780. $"sum(TodayCount) TodayCount,sum(MonthCount) MonthCount from {viewName} ";
  781. #endregion
  782. var status = CurrDb.FindList<MacStatusForDashboardDetailDto>(sql).FirstOrDefault();
  783. status.RunTime = string.IsNullOrEmpty(status.RunTime) ? "0" : status.RunTime;
  784. sql = $"DROP VIEW IF EXISTS {viewName}";
  785. CurrDb.ExecuteBySql(sql);
  786. // 获取小于StartTime的最后一条状态,如果该状态结束时间大于StartTime,
  787. // 将该状态的结束时间-StartTime的时长计入对应状态
  788. var first = CurrDb.FindListForCondition<MacStatus>($" and a.maccode='{maccode}' and a.stime<'{starttime}'" +
  789. $" and a.statusid=4 order by a.id desc limit 0,1", ref errorinfo)
  790. .FirstOrDefault();
  791. if (first != null && first.ETime > Convert.ToDateTime(starttime))
  792. {
  793. status.RunTime = (Convert.ToInt32(status.RunTime) + Math.Round((first.ETime - Convert.ToDateTime(starttime)).TotalMinutes)).ToString();
  794. }
  795. status.RunRate = Math.Round((Convert.ToDouble(status.RunTime) / timediff * 100), 2).ToString();
  796. status.RunRate = (!string.IsNullOrEmpty(status.RunRate)) ? status.RunRate : "0.00";
  797. status.AlarmCount = string.IsNullOrEmpty(status.AlarmCount) ? "0" : status.AlarmCount;
  798. status.TodayCount = string.IsNullOrEmpty(status.TodayCount) ? "0" : status.TodayCount;
  799. status.MonthCount = Math.Round((Convert.ToDouble(status.TodayCount) / timediff), 2).ToString();
  800. status.Color = entity?.Color;
  801. macStatusForDashboardDetailDto = status;
  802. macStatusForDashboardDetailDto.Recipe = entity?.Recipe;//机种
  803. macStatusForDashboardDetailDto.StatusName = entity?.StatusName;//当前状态
  804. macStatusForDashboardDetailDto.StatusCode = entity?.StatusCode;
  805. macStatusForDashboardDetailDto.Factory = entity?.Factory;
  806. macStatusForDashboardDetailDto.RegionName = entity?.RegionName;
  807. return macStatusForDashboardDetailDto;
  808. }
  809. /// <summary>
  810. /// 获取报警信息
  811. /// </summary>
  812. /// <param name="filter"></param>
  813. /// <param name="starttime"></param>
  814. /// <param name="endtime"></param>
  815. /// <returns></returns>
  816. public IOrderedEnumerable<MacStatusForAnalysis> GetDetailForAnalysis(string maccode, string starttime, string endtime)
  817. {
  818. string errorinfo = string.Empty;
  819. string st = Convert.ToDateTime(starttime).ToString("yyyy-MM-dd") + " 00:00:00";
  820. string endtt = Convert.ToDateTime(st).AddHours(24).ToString();
  821. var tbNames = this._getTableNames("macstatus", Convert.ToDateTime(st), Convert.ToDateTime(endtt));
  822. var alarms = new List<MacStatusForAnalysis>();
  823. string sql = string.Empty;
  824. var viewName = $"v_temp_alarm_{DateTime.Now.Ticks}";
  825. for (int i = 0; i < tbNames.Count(); i++)
  826. {
  827. sql += $@"SELECT count(*) AlarmCount,AlarmCode,AlarmDescribe
  828. FROM {tbNames.ElementAt(i)} as A
  829. where A.MacCode = '{maccode}'
  830. AND A.STime > '{starttime}'
  831. AND A.STime < '{endtime}'
  832. AND StatusID=6
  833. AND a.AlarmCode <> 'SVID'
  834. GROUP BY A.AlarmCode ,AlarmDescribe ";
  835. sql += " union all ";
  836. }
  837. sql = sql.Substring(0, sql.Length - 11);
  838. var createSql = $"CREATE OR REPLACE VIEW AS {sql}";
  839. CurrDb.ExecuteBySql(createSql);
  840. sql = "select * from " + viewName;
  841. var dtos = CurrDb.FindList<MacStatusForAnalysis>(sql).OrderByDescending(c => c.AlarmCount);
  842. createSql = "DROP VIEW IF EXISTS " + viewName;
  843. CurrDb.ExecuteBySql(createSql);
  844. return dtos;
  845. }
  846. /// <summary>
  847. /// 稼动详情饼图数据
  848. /// </summary>
  849. /// <param name="maccode"></param>
  850. /// <returns></returns>
  851. public IEnumerable<RunRateDto> GetRunRatesDetail(string maccode, string startTime, string endTime)
  852. {
  853. string errorinfo = string.Empty;
  854. var standards = CurrDb.FindListForCondition<StandardStatus>(string.Empty, ref errorinfo);
  855. var disconn = standards.FirstOrDefault(c => c.FCode.ToUpper() == "DISCONN");
  856. var idle = standards.FirstOrDefault(c => c.FCode.ToUpper() == "IDLE");
  857. string st = startTime;
  858. string endtt = endTime;
  859. var createSql = string.Empty;
  860. var statusNames = this._getTableNames("macstatus", Convert.ToDateTime(st), Convert.ToDateTime(endtt));
  861. var viewName = $"V_Status_Mac_{DateTime.Now.Ticks}";
  862. createSql += $"CREATE OR REPLACE VIEW {viewName} AS ";
  863. for (int i = 0; i < statusNames.Count(); i++)
  864. {
  865. createSql += $@"SELECT
  866. SUM(FLen) AS value,StatusID,B.FCode AS Code,B.FName as Name
  867. FROM
  868. {statusNames.ElementAt(i)} as A
  869. left join standardstatus as B on A.StatusID = B.StatusVal
  870. WHERE
  871. A.MacCode = '{maccode}'
  872. AND A.STime >= '{startTime}'
  873. AND A.ETime < '{endTime}'
  874. AND (A.Alarmcode is null or a.alarmcode != 'SVID')
  875. GROUP BY StatusID,B.FName,B.FCode ";
  876. createSql += " union all ";
  877. }
  878. createSql = createSql.Substring(0, createSql.Length - 11);
  879. CurrDb.ExecuteBySql(createSql);
  880. var sql = $"select sum(value) value,statusID,Code,Name from {viewName} " +
  881. $"group by statusID,Code,Name";
  882. IList<RunRateDto> runRateDtos = CurrDb.FindList<RunRateDto>(sql).ToList();
  883. var dropSql = $"DROP VIEW IF EXISTS {viewName}";
  884. CurrDb.ExecuteBySql(dropSql);
  885. Parallel.ForEach(runRateDtos, item =>
  886. {
  887. item.Value = item.Value / 60;
  888. });
  889. // 获取小于StartTime的最后一条状态,如果该状态结束时间大于StartTime,
  890. // 将该状态的结束时间-StartTime的时长计入对应状态
  891. var statusSql = new MacStatus().GetSelectSql();
  892. var first = CurrDb.FindList<MacStatus>($"{statusSql.Replace("MacStatus", statusNames.First())} where 1=1 and a.maccode='{maccode}' and a.stime<'{startTime}'" +
  893. $" order by a.id desc limit 0,1")
  894. .FirstOrDefault();
  895. if (first != null && first.ETime > Convert.ToDateTime(startTime))
  896. {
  897. if (first.StatusID == 6 && first.AlarmCode == "SVID")
  898. {
  899. first.StatusID = 3;
  900. first.FCode = idle.FCode;
  901. first.StatusFName = idle.FName;
  902. }
  903. if (runRateDtos.Any(t => t.Code == first.FCode))
  904. {
  905. runRateDtos.FirstOrDefault(c => c.Code == first.FCode).Value += (first.ETime - Convert.ToDateTime(startTime)).TotalMinutes;
  906. }
  907. else
  908. {
  909. runRateDtos.Add(new RunRateDto
  910. {
  911. Code = first.FCode,
  912. Name = first.StatusFName,
  913. Value = (first.ETime - Convert.ToDateTime(startTime)).TotalMinutes,
  914. });
  915. }
  916. }
  917. var last = CurrDb.FindList<MacStatus>($" {statusSql.Replace("MacStatus", statusNames.Last())} where 1=1 and a.maccode='{maccode}' and a.stime<='{endTime}'" +
  918. $"and a.stime>='{startTime}' " +
  919. $" order by a.id desc limit 0,1").FirstOrDefault();
  920. if (last != null && (last.ETime.ToString("yyyy-MM-dd HH:mm:ss") == "0001-01-01 00:00:00"
  921. || last.ETime > Convert.ToDateTime(endTime)))
  922. {
  923. if (last.StatusID == 6 && last.AlarmCode == "SVID")
  924. {
  925. last.StatusID = 3;
  926. last.FCode = idle.FCode;
  927. last.StatusFName = idle.FName;
  928. }
  929. if (runRateDtos.Any(t => t.Code == last.FCode))
  930. {
  931. runRateDtos.FirstOrDefault(c => c.Code == last.FCode).Value += (Convert.ToDateTime(endTime) - last.STime).TotalMinutes;
  932. }
  933. else
  934. {
  935. runRateDtos.Add(new RunRateDto
  936. {
  937. Code = last.FCode,
  938. Name = last.StatusFName,
  939. Value = Math.Round((Convert.ToDateTime(endTime) - last.STime).TotalMinutes, 2)
  940. });
  941. }
  942. }
  943. if (first != null && first.ETime.ToString("yyyy-MM-dd HH:mm:ss") == "0001-01-01 00:00:00" && runRateDtos.Count == 0)
  944. {
  945. //if (first.FCode != idle.FCode)
  946. //{
  947. runRateDtos.Add(new RunRateDto
  948. {
  949. Code = first.FCode,
  950. Name = first.StatusFName,
  951. Value = Math.Round((Convert.ToDateTime(endTime) - Convert.ToDateTime(startTime)).TotalMinutes, 2),
  952. // Color = new RgbColor(disconn.Red, disconn.Green, disconn.Blue)
  953. });
  954. // }
  955. //else
  956. //{
  957. // runRateDtos.FirstOrDefault().Value += Math.Round((Convert.ToDateTime(endTime) - Convert.ToDateTime(startTime)).TotalMinutes, 2);
  958. //}
  959. }
  960. var totalMinutes = runRateDtos.Sum(c => c.Value);
  961. var dayTimeSpan = (Convert.ToDateTime(endtt) - Convert.ToDateTime(st)).TotalMinutes;
  962. if (totalMinutes != dayTimeSpan)
  963. {
  964. // 当总时间与状态的时间和不等时,判断该时间段内状态,如果状态只有一个,
  965. // 将差值加到该状态下,如果有多个,优先加到稼动时间上,其次闲置,再次时间最长的状态
  966. if (runRateDtos.Count == 1)
  967. {
  968. runRateDtos.First().Value += dayTimeSpan - totalMinutes;
  969. }
  970. else
  971. {
  972. var totalRunTime = runRateDtos.Where(c => c.Code == "RUN").Sum(c => c.Value);
  973. var totalIdleTime = runRateDtos.Where(c => c.Code == "IDLE").Sum(c => c.Value);
  974. if (runRateDtos.FirstOrDefault(c => c.Code == "IDLE") != null && totalIdleTime > 0)
  975. {
  976. runRateDtos.FirstOrDefault(c => c.Code == "IDLE").Value += (dayTimeSpan - totalMinutes);
  977. }
  978. else if (runRateDtos.FirstOrDefault(c => c.Code == "RUN") != null && totalRunTime > 0)
  979. {
  980. runRateDtos.FirstOrDefault(c => c.Code == "RUN").Value += (dayTimeSpan - totalMinutes);
  981. }
  982. else
  983. {
  984. var maxItem = runRateDtos.FirstOrDefault(t => t.Value == runRateDtos.Max(c => c.Value));
  985. if (maxItem != null)
  986. {
  987. maxItem.Value += (dayTimeSpan - totalMinutes);
  988. }
  989. }
  990. }
  991. //if (runRateDtos.FirstOrDefault(c => c.Code == "IDLE") == null)
  992. //{
  993. // runRateDtos.Add(new RunRateDto
  994. // {
  995. // Code = "IDLE",
  996. // Color = new RgbColor(idle.Red, idle.Green, idle.Blue),
  997. // Name = idle.FName,
  998. // Value = Math.Round(dayTimeSpan - totalMinutes, 2)
  999. // });
  1000. //}
  1001. //else
  1002. //{
  1003. // runRateDtos.FirstOrDefault(c => c.Code == idle.FCode).Value += Math.Round(dayTimeSpan - totalMinutes, 2);
  1004. //}
  1005. }
  1006. // var next = CurrDb.FindListForCondition<MacStatus>($" and a.maccode='{maccode}' and a.eTime>''")
  1007. if (runRateDtos.Count() == 0)
  1008. {
  1009. //return new List<RunRateDto>()
  1010. //{
  1011. // new RunRateDto()
  1012. // {
  1013. // Code=disconn.FCode,
  1014. // Name=disconn.FName,
  1015. // Value=Math.Round((Convert.ToDateTime(endTime)-Convert.ToDateTime(startTime)).TotalMinutes,2),
  1016. // Color=new RgbColor(disconn.Red,disconn.Green,disconn.Blue)
  1017. // }
  1018. //};
  1019. return null;
  1020. }
  1021. else
  1022. {
  1023. Parallel.ForEach<RunRateDto>(runRateDtos, item =>
  1024. {
  1025. var stand = standards.FirstOrDefault(c => c.FCode.ToUpper() == item.Code.ToUpper());
  1026. // if(stand.FCode=="")
  1027. item.Color = new RgbColor(stand.Red, stand.Green, stand.Blue);
  1028. item.Value = Math.Round(item.Value, 2);
  1029. });
  1030. runRateDtos = runRateDtos.Where(c => c.Value > 0).ToList();
  1031. return runRateDtos;
  1032. }
  1033. }
  1034. /// <summary>
  1035. /// 获取机种产量详情白夜班信息
  1036. /// </summary>
  1037. /// <param name="filter"></param>
  1038. /// <param name="starttime"></param>
  1039. /// <param name="endtime"></param>
  1040. /// <returns></returns>
  1041. public IEnumerable<DayCount> GetDetailForCountDay(string maccode, string startTime)
  1042. {
  1043. string errorinfo = string.Empty;
  1044. DateTime st = Convert.ToDateTime(Convert.ToDateTime(startTime).ToString("yyyy-MM-dd") + " 00:30");
  1045. DateTime yestertodayShiftStart = st.AddHours(-16);//昨天白班开始
  1046. DateTime yestertodayShiftEnd = st.AddHours(-4);//昨天白班结束
  1047. DateTime yestertodayNightStart = yestertodayShiftEnd;//昨天夜班开始
  1048. DateTime yestertodayNightEnd = st.AddHours(8);//昨天夜班结束
  1049. DateTime TodayShiftStart = yestertodayNightEnd;//今天白班开始
  1050. DateTime TodayShiftEnd = TodayShiftStart.AddHours(12);//今天白班结束
  1051. DateTime TodayNightStart = TodayShiftEnd;//今天夜班开始
  1052. DateTime TodayNightEnd = TodayNightStart.AddHours(12);//今天夜班结束
  1053. string FinishUnit = DllHsms.StandardCode.SVID_FinishUnit;
  1054. string toDay = st.ToString("yyyy-MM-dd");
  1055. string ysday = st.AddDays(-1).ToString("yyyy-MM-dd");
  1056. IEnumerable<DayCount> dtos = null;
  1057. #region
  1058. if (yestertodayNightStart < DateTime.Now.AddDays(-30))
  1059. {
  1060. var createSql = string.Empty;
  1061. var tbDetailsNames = this._getTableNames("maccountdetail", st, st.AddDays(1));
  1062. var tbMstNames = this._getTableNames("maccountmst", st, st.AddDays(1));
  1063. var viewName = $"V_Output_Day_{DateTime.Now.Ticks}";
  1064. createSql += $"CREATE OR REPLACE VIEW {viewName} AS ";
  1065. for (int i = 0; i < tbMstNames.Count(); i++)
  1066. {
  1067. createSql += $@"SELECT
  1068. IFNULL(sum( a.FCount ),0) Count,
  1069. '{ysday}' DAY,
  1070. '{yestertodayShiftStart}' DayDate,
  1071. '白班' class
  1072. FROM
  1073. {tbDetailsNames.ElementAt(i)} a
  1074. LEFT JOIN {tbMstNames.ElementAt(i)} b ON a.mstid = b.id
  1075. LEFT JOIN machine c ON b.macid = c.id
  1076. WHERE
  1077. a.typeID = 0
  1078. AND a.ParamCode = '{FinishUnit}'
  1079. AND c.FCode = '{maccode}'
  1080. AND b.EDate BETWEEN '{yestertodayShiftStart.ToString(timeFormat)}'
  1081. AND '{yestertodayShiftEnd.ToString(timeFormat)}'
  1082. UNION ALL
  1083. SELECT
  1084. IFNULL(sum( a.FCount ),0) Count,
  1085. '{ysday}' DAY,
  1086. '{yestertodayNightStart}' DayDate,
  1087. '夜班' class
  1088. FROM
  1089. {tbDetailsNames.ElementAt(i)} a
  1090. LEFT JOIN {tbMstNames.ElementAt(i)} b ON a.mstid = b.id
  1091. LEFT JOIN machine c ON b.macid = c.id
  1092. WHERE
  1093. a.typeID = 0
  1094. AND a.ParamCode = '{FinishUnit}'
  1095. AND c.FCode = '{maccode}'
  1096. AND b.EDate BETWEEN '{yestertodayNightStart.ToString(timeFormat) }'
  1097. AND '{yestertodayNightEnd.ToString(timeFormat)}' UNION ALL
  1098. SELECT
  1099. IFNULL(sum( a.FCount ),0) Count,
  1100. '{toDay}' DAY,
  1101. '{TodayShiftStart}' DayDate,
  1102. '白班' class
  1103. FROM
  1104. {tbDetailsNames.ElementAt(i)} a
  1105. LEFT JOIN {tbMstNames.ElementAt(i)} b ON a.mstid = b.id
  1106. LEFT JOIN machine c ON b.macid = c.id
  1107. WHERE
  1108. a.typeID = 0
  1109. AND a.ParamCode = '{FinishUnit}'
  1110. AND c.FCode = '{maccode}'
  1111. AND b.EDate BETWEEN '{TodayShiftStart.ToString(timeFormat) }'
  1112. AND '{TodayShiftEnd.ToString(timeFormat)}' UNION ALL
  1113. SELECT
  1114. IFNULL(sum( a.FCount ),0) Count,
  1115. '{toDay}' DAY,
  1116. '{TodayNightStart}' DayDate,
  1117. '夜班' class
  1118. FROM
  1119. {tbDetailsNames.ElementAt(i)} a
  1120. LEFT JOIN {tbMstNames.ElementAt(i)} b ON a.mstid = b.id
  1121. LEFT JOIN machine c ON b.macid = c.id
  1122. WHERE
  1123. a.typeID = 0
  1124. AND a.ParamCode = '{FinishUnit}'
  1125. AND c.FCode = '{maccode}'
  1126. AND b.EDate BETWEEN '{TodayNightStart.ToString(timeFormat)}'
  1127. AND '{TodayNightEnd.ToString(timeFormat)}' ";
  1128. createSql += " union all ";
  1129. }
  1130. createSql = createSql.Substring(0, createSql.Length - 11);
  1131. CurrDb.ExecuteBySql(createSql);
  1132. var sql = $"select sum(count) count,day,class,dayDate EDate from {viewName} " +
  1133. $"group by daydate,day,class";
  1134. dtos = CurrDb.FindList<DayCount>(sql).OrderBy(c => c.EDate);
  1135. var dropSql = $"DROP VIEW IF EXISTS {viewName}";
  1136. CurrDb.ExecuteBySql(dropSql);
  1137. }
  1138. else
  1139. {
  1140. var sql = $@"SELECT
  1141. IFNULL(sum( a.FCount ),0) Count,
  1142. '{ysday}' DAY,
  1143. '{yestertodayShiftStart}' DayDate,
  1144. '白班' class
  1145. FROM
  1146. maccountdetail a
  1147. LEFT JOIN maccountmst b ON a.mstid = b.id
  1148. LEFT JOIN machine c ON b.macid = c.id
  1149. WHERE
  1150. a.typeID = 0
  1151. AND a.ParamCode = '{FinishUnit}'
  1152. AND c.FCode = '{maccode}'
  1153. AND b.EDate BETWEEN '{yestertodayShiftStart.ToString(timeFormat)}'
  1154. AND '{yestertodayShiftEnd.ToString(timeFormat)}'
  1155. UNION ALL
  1156. SELECT
  1157. IFNULL(sum( a.FCount ),0) Count,
  1158. '{ysday}' DAY,
  1159. '{yestertodayNightStart}' DayDate,
  1160. '夜班' class
  1161. FROM
  1162. maccountdetail a
  1163. LEFT JOIN maccountmst b ON a.mstid = b.id
  1164. LEFT JOIN machine c ON b.macid = c.id
  1165. WHERE
  1166. a.typeID = 0
  1167. AND a.ParamCode = '{FinishUnit}'
  1168. AND c.FCode = '{maccode}'
  1169. AND b.EDate BETWEEN '{yestertodayNightStart.ToString(timeFormat) }'
  1170. AND '{yestertodayNightEnd.ToString(timeFormat)}' UNION ALL
  1171. SELECT
  1172. IFNULL(sum( a.FCount ),0) Count,
  1173. '{toDay}' DAY,
  1174. '{TodayShiftStart}' DayDate,
  1175. '白班' class
  1176. FROM
  1177. maccountdetail a
  1178. LEFT JOIN maccountmst b ON a.mstid = b.id
  1179. LEFT JOIN machine c ON b.macid = c.id
  1180. WHERE
  1181. a.typeID = 0
  1182. AND a.ParamCode = '{FinishUnit}'
  1183. AND c.FCode = '{maccode}'
  1184. AND b.EDate BETWEEN '{TodayShiftStart.ToString(timeFormat) }'
  1185. AND '{TodayShiftEnd.ToString(timeFormat)}' UNION ALL
  1186. SELECT
  1187. IFNULL(sum( a.FCount ),0) Count,
  1188. '{toDay}' DAY,
  1189. '{TodayNightStart}' DayDate,
  1190. '夜班' class
  1191. FROM
  1192. maccountdetail a
  1193. LEFT JOIN maccountmst b ON a.mstid = b.id
  1194. LEFT JOIN machine c ON b.macid = c.id
  1195. WHERE
  1196. a.typeID = 0
  1197. AND a.ParamCode = '{FinishUnit}'
  1198. AND c.FCode = '{maccode}'
  1199. AND b.EDate BETWEEN '{TodayNightStart.ToString(timeFormat)}'
  1200. AND '{TodayNightEnd.ToString(timeFormat)}' ";
  1201. dtos = CurrDb.FindList<DayCount>(sql).OrderBy(c => c.EDate);
  1202. }
  1203. #endregion
  1204. return dtos;
  1205. }
  1206. /// <summary>
  1207. /// 获取机种产量详情信息
  1208. /// </summary>
  1209. /// <param name="filter"></param>
  1210. /// <param name="starttime"></param>
  1211. /// <param name="endtime"></param>
  1212. /// <returns></returns>
  1213. public IEnumerable<HourCount> GetDetailForCountHour(string maccode, string startTime)
  1214. {
  1215. var sql = string.Empty;
  1216. var dateStart = Convert.ToDateTime(startTime);
  1217. DateTime st = Convert.ToDateTime(Convert.ToDateTime(startTime).ToString("yyyy-MM-dd HH:mm"));
  1218. IList<HourCount> dtos = null;
  1219. // 当月数据
  1220. if ((DateTime.Now - dateStart).TotalDays < 30)
  1221. {
  1222. sql = $@"(SELECT
  1223. IFNULL( sum( a.FCount ),0) Count, DAY(b.edate) DAY,HOUR(b.EDate) Hour
  1224. FROM
  1225. maccountdetail a
  1226. LEFT JOIN maccountmst b ON a.mstid = b.id
  1227. LEFT JOIN eap.machine c ON b.macid = c.id
  1228. WHERE
  1229. a.typeID = 0
  1230. AND a.ParamCode = 'S00026'
  1231. AND c.FCode = '{maccode}'
  1232. AND b.EDate BETWEEN '{st.ToString(timeFormat)}'
  1233. AND '{st.AddHours(24).ToString(timeFormat)}'
  1234. GROUP BY DAY(b.Edate),HOUR(b.EDate))";
  1235. dtos = CurrDb.FindList<HourCount>(sql).ToList();
  1236. }
  1237. else // 历史数据
  1238. {
  1239. var countMsts = this._getTableNames("maccountmst", st, st.AddDays(1));
  1240. var countDetails = this._getTableNames("maccountdetail", st, st.AddDays(1));
  1241. var viewName = $"V_Output_{DateTime.Now.Ticks}";
  1242. var createSql = $"CREATE TEMPORARY TABLE {viewName} ";
  1243. for (int i = 0; i < countMsts.Count(); i++)
  1244. {
  1245. createSql += $@" (SELECT
  1246. IFNULL( sum( a.FCount ),0) Count, DAY(b.edate) DAY,HOUR(b.EDate) Hour
  1247. FROM
  1248. {countDetails.ElementAt(i)} a
  1249. LEFT JOIN {countMsts.ElementAt(i)} b ON a.mstid = b.id
  1250. LEFT JOIN eap.machine c ON b.macid = c.id
  1251. WHERE
  1252. a.typeID = 0
  1253. AND a.ParamCode = 'S00026'
  1254. AND c.FCode = '{maccode}'
  1255. AND b.EDate BETWEEN '{st.ToString(timeFormat)}'
  1256. AND '{st.AddHours(24).ToString(timeFormat)}'
  1257. GROUP BY DAY(b.Edate),HOUR(b.EDate))";
  1258. createSql += " union all ";
  1259. }
  1260. createSql = createSql.Substring(0, createSql.Length - 11);
  1261. CurrDb.ExecuteBySql(createSql);
  1262. sql = $"select sum(Count) count,DAY,HOUR from {viewName} group by DAY,HOUR ";
  1263. dtos = CurrDb.FindList<HourCount>(sql).ToList();
  1264. sql = $"DROP TABLE IF EXISTS {viewName}";
  1265. CurrDb.ExecuteBySql(sql);
  1266. }
  1267. var hours = 24;
  1268. if (st.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
  1269. {
  1270. hours = Convert.ToInt32(Math.Ceiling((DateTime.Now.AddMinutes(30) - st).TotalHours));
  1271. }
  1272. var newDtos = new List<HourCount>();
  1273. for (int i = 0; i < hours; i++)
  1274. {
  1275. var hour = st.AddHours(i).Hour;
  1276. var day = st.AddHours(i).Day;
  1277. if (!dtos.Any(c => c.Hour == hour && c.Day == day))
  1278. {
  1279. newDtos.Add(new HourCount
  1280. {
  1281. Hour = hour,
  1282. Day = day,
  1283. Count = "0"
  1284. });
  1285. }
  1286. else
  1287. {
  1288. newDtos.Add(new HourCount
  1289. {
  1290. Hour = hour,
  1291. Day = day,
  1292. Count = dtos.FirstOrDefault(c => c.Day == day && c.Hour == hour).Count
  1293. });
  1294. }
  1295. }
  1296. return newDtos;
  1297. }
  1298. /// <summary>
  1299. /// 获取机台时间段内运行历史
  1300. /// </summary>
  1301. /// <param name="macCode"></param>
  1302. /// <param name="startTime"></param>
  1303. /// <param name="endTime"></param>
  1304. /// <param name="errorinfo"></param>
  1305. /// <returns></returns>
  1306. public IEnumerable<RunHistroyDto> GetRunHistory(string macCode, DateTime startTime, DateTime endTime, ref string errorinfo)
  1307. {
  1308. var standards = CurrDb.FindListForCondition<StandardStatus>(string.Empty, ref errorinfo);
  1309. var disconn = standards.FirstOrDefault(t => t.FCode.ToUpper() == "DISCONN");
  1310. var idle = standards.FirstOrDefault(t => t.FCode == "IDLE");
  1311. var dateFormatter = "yyyy-MM-dd H:mm:ss";
  1312. var runHistories = new List<RunHistroyDto>();
  1313. var sql = new MacStatus().GetSelectSql();
  1314. var tbNames = this._getTableNames("MacStatus", startTime, startTime.AddDays(1));
  1315. var statuses = new List<MacStatus>();
  1316. foreach (var item in tbNames)
  1317. {
  1318. var tempSql = sql.Replace("MacStatus", item);
  1319. tempSql += $" where 1=1 and a.macCode='{macCode}' " +
  1320. $"and a.stime>='{startTime.ToString(timeFormat)}' and " +
  1321. $"a.stime<='{endTime.ToString(timeFormat)}' and a.etime<>'0001-01-01 00:00:00'";
  1322. var partStatuses = CurrDb.FindList<MacStatus>(tempSql).ToList();
  1323. statuses.AddRange(partStatuses);
  1324. }
  1325. //var statuses = CurrDb.FindListForCondition<MacStatus>($" and a.macCode='{macCode}' " +
  1326. // $"and a.stime>='{startTime.ToString(timeFormat)}' and " +
  1327. // $"a.stime<='{endTime.ToString(timeFormat)}' and a.etime<>'0001-01-01 00:00:00' ", ref errorinfo)
  1328. // .ToList();
  1329. //var lastStatus = CurrDb.FindListForCondition<MacStatus>($" and a.macCode='{macCode}' and a.stime<'{startTime.ToString(timeFormat)}' " +
  1330. // $"order by id desc limit 0,1", ref errorinfo).FirstOrDefault();
  1331. sql = sql.Replace("MacStatus", tbNames.Last());
  1332. sql += $" where a.macCode='{macCode}' and a.stime<'{startTime.ToString(timeFormat)}' " +
  1333. $"order by id desc limit 0,1";
  1334. var lastStatus = CurrDb.FindList<MacStatus>(sql).FirstOrDefault();
  1335. if (lastStatus != null)
  1336. {
  1337. statuses.Insert(0, lastStatus);
  1338. }
  1339. var currState = CurrDb.FindListForCondition<MacStatus>($" and a.macCode='{macCode}' and a.etime='0001-01-01 00:00:00' order by a.stime desc limit 0,1",
  1340. ref errorinfo).FirstOrDefault();
  1341. if (currState != null)
  1342. {
  1343. statuses.Add(currState);
  1344. }
  1345. // 当前时间段内没数据,查询开始时间的前的最后一条数据
  1346. if (statuses == null || statuses.Count() <= 0)
  1347. {
  1348. var status = disconn.FCode.ToUpper();
  1349. var statusName = disconn.FName;
  1350. var timeLen = (endTime - startTime).TotalMinutes;
  1351. var history = new RunHistroyDto
  1352. {
  1353. StartTime = startTime.ToString(dateFormatter),
  1354. EndTime = endTime.ToString(dateFormatter),
  1355. Start = startTime.Hour * 100 + startTime.Minute,
  1356. End = endTime.Hour * 100 + endTime.Minute,
  1357. MacCode = macCode.ToUpper(),
  1358. Status = status,
  1359. StatusName = statusName,
  1360. TimeLen = timeLen,
  1361. Duration = AppendDuration(endTime - startTime),
  1362. Color = new RgbColor(disconn.Red, disconn.Green, disconn.Blue),
  1363. AlarmCode = string.Empty
  1364. };
  1365. runHistories.Add(history);
  1366. }
  1367. else
  1368. {
  1369. statuses = statuses.OrderBy(c => c.ID).ToList();
  1370. foreach (var item in statuses)
  1371. {
  1372. var end = Convert.ToDouble(endTime.Hour * 100 + endTime.Minute);
  1373. var endStr = endTime.ToString("HH:mm:ss");
  1374. var startStr = startTime.ToString("HH:mm:ss");
  1375. var dateStart = startTime.ToString(dateFormatter);
  1376. var dateEnd = endTime.ToString(dateFormatter);
  1377. var start = 0d;
  1378. var minutes = 0d;
  1379. var duration = string.Empty;
  1380. if (item.STime < startTime && item.ETime > endTime)
  1381. {
  1382. start = 0;
  1383. end = Convert.ToDouble(AppendTime(endTime.Hour, endTime.Minute, endTime.Second));
  1384. dateEnd = endTime.ToString(dateFormatter);
  1385. minutes = (endTime - startTime).TotalMinutes;
  1386. duration = AppendDuration(endTime - startTime);
  1387. }
  1388. if (item.ETime.ToString(timeFormat) != "0001-01-01 00:00:00")
  1389. {
  1390. end = Convert.ToDouble(AppendTime(item.ETime.Hour, item.ETime.Minute, item.ETime.Second));
  1391. endStr = item.ETime.ToString("HH:mm:ss");
  1392. dateEnd = item.ETime.ToString(dateFormatter);
  1393. minutes = (item.ETime - item.STime).TotalMinutes;
  1394. duration = AppendDuration(item.ETime - item.STime);
  1395. if (item.STime < startTime)
  1396. {
  1397. minutes = (item.ETime - startTime).TotalMinutes;
  1398. duration = AppendDuration(item.ETime - startTime);
  1399. }
  1400. }
  1401. else
  1402. {
  1403. minutes = (endTime - item.STime).TotalMinutes;
  1404. duration = AppendDuration(endTime - item.STime);
  1405. if (item.STime < startTime)
  1406. {
  1407. minutes = (endTime - startTime).TotalMinutes;
  1408. duration = AppendDuration(endTime - startTime);
  1409. }
  1410. item.ETime = endTime;
  1411. }
  1412. start = Convert.ToDouble(AppendTime(item.STime.Hour, item.STime.Minute, item.STime.Second));
  1413. startStr = item.STime.ToString("HH:mm:ss");
  1414. dateStart = item.STime.ToString(dateFormatter);
  1415. if (item.STime < startTime)
  1416. {
  1417. start = 0;
  1418. startStr = startTime.ToString("HH:mm:ss");
  1419. dateStart = startTime.ToString(dateFormatter);
  1420. }
  1421. // 获取列表最后一条记录,判断当前状态是否与其一样,一样就加上当前状态的持续时间
  1422. var lastHistory = runHistories.LastOrDefault();
  1423. if (item.StatusID == 6 && item.AlarmCode == "SVID")
  1424. {
  1425. item.StatusID = 3;
  1426. item.StatusFName = idle.FName;
  1427. }
  1428. var currStandard = standards.FirstOrDefault(c => c.StatusVal == item.StatusID);
  1429. if (lastHistory != null && lastHistory.StatusID == item.StatusID)
  1430. {
  1431. lastHistory.Duration = AppendDuration(item.ETime - Convert.ToDateTime(lastHistory.StartTime));
  1432. lastHistory.End = end;
  1433. lastHistory.TimeLen += minutes;
  1434. lastHistory.EndString = endStr;
  1435. lastHistory.EndTime = dateEnd;
  1436. lastHistory.AlarmCode = item.AlarmCode;
  1437. }
  1438. else
  1439. {
  1440. runHistories.Add(new RunHistroyDto
  1441. {
  1442. MacCode = macCode,
  1443. Start = start,
  1444. End = end,
  1445. Status = item.FCode,
  1446. StatusName = item.StatusFName,
  1447. TimeLen = minutes,
  1448. StartString = startStr,
  1449. EndString = endStr,
  1450. StartTime = dateStart,
  1451. EndTime = dateEnd,
  1452. Duration = duration,
  1453. StatusID = item.StatusID,
  1454. Color = new RgbColor(currStandard.Red, currStandard.Green, currStandard.Blue),
  1455. AlarmCode = item.AlarmCode
  1456. });
  1457. }
  1458. }
  1459. }
  1460. return runHistories;
  1461. }
  1462. /// <summary>
  1463. /// 根据日期获取表名
  1464. /// </summary>
  1465. /// <param name="tableName"></param>
  1466. /// <param name="startTime"></param>
  1467. /// <returns></returns>
  1468. private IEnumerable<string> _getTableNames(string tableName, DateTime startTime, DateTime endTime)
  1469. {
  1470. var newNames = new List<string>();
  1471. var now = DateTime.Now;
  1472. if (now.AddMonths(-1) <= startTime)
  1473. {
  1474. newNames.Add(tableName);
  1475. return newNames;
  1476. }
  1477. var months = ((endTime.Year - startTime.Year) * 12) + endTime.Month - startTime.Month + 1;
  1478. if (months == 1)
  1479. {
  1480. if (endTime.Year == now.Year && endTime.Month == now.Month)
  1481. {
  1482. newNames.Add(tableName);
  1483. }
  1484. else
  1485. {
  1486. newNames.Add($"eap{endTime.Year}.{tableName}{endTime.ToString("MM")}");
  1487. }
  1488. }
  1489. else
  1490. {
  1491. for (int i = 0; i < months; i++)
  1492. {
  1493. var currDate = startTime.AddMonths(i);
  1494. if (currDate.Month == now.Month)
  1495. {
  1496. newNames.Add(tableName);
  1497. }
  1498. else
  1499. {
  1500. newNames.Add($"eap{currDate.Year}.{tableName}{currDate.ToString("MM")}");
  1501. }
  1502. }
  1503. }
  1504. return newNames;
  1505. }
  1506. /// <summary>
  1507. /// 拼接时间字符串
  1508. /// </summary>
  1509. /// <param name="hour">小时</param>
  1510. /// <param name="minute">分钟</param>
  1511. /// <returns></returns>
  1512. private string AppendTime(int hour, int minute, int second)
  1513. {
  1514. var sb = new StringBuilder();
  1515. if (hour > 0)
  1516. {
  1517. sb.Append(hour);
  1518. }
  1519. double minutes = minute + ((double)second / 60);
  1520. if (minutes < 10)
  1521. {
  1522. sb.Append("0");
  1523. }
  1524. sb.Append(minutes.ToString("f2"));
  1525. return sb.ToString();
  1526. }
  1527. private string AppendDuration(TimeSpan timeSpan)
  1528. {
  1529. var days = timeSpan.Days;
  1530. var hours = 0;
  1531. if (days > 0)
  1532. {
  1533. hours = days * 24;
  1534. }
  1535. hours += timeSpan.Hours;
  1536. var hourPart = hours + "小时";
  1537. var minutePart = timeSpan.Minutes + "分";
  1538. var secondPart = timeSpan.Seconds + "秒";
  1539. if (timeSpan.TotalSeconds < 60)
  1540. return secondPart;
  1541. else if (timeSpan.TotalSeconds < 3600)
  1542. {
  1543. return minutePart + secondPart;
  1544. }
  1545. else
  1546. {
  1547. return hourPart + minutePart + secondPart;
  1548. }
  1549. }
  1550. /// <summary>
  1551. /// 获取报警明细
  1552. /// </summary>
  1553. /// <param name="start"></param>
  1554. /// <param name="end"></param>
  1555. /// <param name="filter"></param>
  1556. /// <param name="sort"></param>
  1557. /// <param name="order"></param>
  1558. /// <param name="errorinfo"></param>
  1559. /// <returns></returns>
  1560. public IEnumerable<MacStatus> GetAlarmDetail(int start, int length, string filter, string sort, string order, out int total, ref string errorinfo)
  1561. {
  1562. var sql = $"select count(1) from macstatus a where 1=1 and statusid={MacStatusVal.Error} " +
  1563. $"and AlarmCode<>'SVID' " +
  1564. $"{filter} ";
  1565. total = Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  1566. return CurrDb.FindListForCondition<MacStatus>($" and a.statusid={MacStatusVal.Error} and AlarmCode<>'SVID' {filter} " +
  1567. $" order by {sort} {order} limit {start - 1},{length}", ref errorinfo);
  1568. }
  1569. //public IEnumerable<MacStatus> GetAlarmDetail(int start, int end, string filter, string sort, string order)
  1570. //{
  1571. // string sql = string.Format($"SELECT * FROM (SELECT a.*,ROW_NUMBER() OVER(ORDER BY a.{sort} {order}) AS RowNum FROM macstatus AS a "
  1572. // + $"WHERE 1=1 {filter}) AS t WHERE "
  1573. // + $"t.RowNum>={start} AND t.RowNum<{end}");
  1574. // return CurrDb.FindList<MacStatus>(sql);
  1575. //}
  1576. public int GetCount(string filter)
  1577. {
  1578. string sql = string.Format($"SELECT COUNT(1) FROM macstatus a WHERE 1=1 {filter}");
  1579. return Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  1580. }
  1581. /// <summary>
  1582. /// 获取当天和前一天的白班及晚班报警数量
  1583. /// </summary>
  1584. /// <param name="startTime"></param>
  1585. /// <param name="macCode"></param>
  1586. /// <returns></returns>
  1587. public IEnumerable<DayCount> GetAlarmCountByShift(DateTime startTime, string macCode)
  1588. {
  1589. string errorinfo = string.Empty;
  1590. DateTime st = Convert.ToDateTime(Convert.ToDateTime(startTime).ToString("yyyy-MM-dd") + " 00:30");
  1591. DateTime yestertodayShiftStart = st.AddHours(-16);//昨天白班开始
  1592. DateTime yestertodayShiftEnd = st.AddHours(-4);//昨天白班结束
  1593. DateTime yestertodayNightStart = yestertodayShiftEnd;//昨天夜班开始
  1594. DateTime yestertodayNightEnd = st.AddHours(8);//昨天夜班结束
  1595. DateTime TodayShiftStart = yestertodayNightEnd;//今天白班开始
  1596. DateTime TodayShiftEnd = TodayShiftStart.AddHours(12);//今天白班结束
  1597. DateTime TodayNightStart = TodayShiftEnd;//今天夜班开始
  1598. DateTime TodayNightEnd = TodayNightStart.AddHours(12);//今天夜班结束
  1599. string toDay = st.ToString("yyyy-MM-dd");
  1600. string ysday = st.AddDays(-1).ToString("yyyy-MM-dd");
  1601. #region
  1602. var viewName = $"V_Mac_Alarm_Detail_{DateTime.Now.Ticks}";
  1603. var statusNames = _getTableNames("macstatus", yestertodayShiftStart, TodayNightEnd);
  1604. // string sql = $@" call GetDeatilForDayCount ('{maccode}','{DllHsms.StandardCode.SVID_FinishUnit}','{startTime}')";
  1605. string sql = $@"select count(1) count,'{ysday}' day,'白班' class from macstatus a
  1606. where a.statusid=6 {svidFilter} and a.maccode='{macCode}' and a.STime>'{yestertodayShiftStart.ToString(timeFormat)}' and a.sTime<='{yestertodayShiftEnd.ToString(timeFormat)}'
  1607. union all
  1608. select count(1) count,'{ysday}' day,'夜班' class from macstatus a
  1609. where a.statusid=6 {svidFilter} and a.maccode='{macCode}' and a.STime>'{yestertodayNightStart.ToString(timeFormat)}' and a.sTime<='{yestertodayNightEnd.ToString(timeFormat)}'
  1610. union all
  1611. select count(1) count,'{toDay}' day,'白班' class from macstatus a
  1612. where a.statusid=6 {svidFilter} and a.maccode='{macCode}' and a.STime>'{TodayShiftStart.ToString(timeFormat)}' and a.sTime<='{TodayShiftEnd.ToString(timeFormat)}'
  1613. union all
  1614. select count(1) count,'{toDay}' day,'夜班' class from macstatus a
  1615. where a.statusid=6 {svidFilter} and a.maccode='{macCode}' and a.STime>'{TodayNightStart.ToString(timeFormat)}' and a.sTime<='{TodayNightEnd.ToString(timeFormat)}'
  1616. ";
  1617. #endregion
  1618. return CurrDb.FindList<DayCount>(sql);
  1619. }
  1620. public MacDto GetDetail(List<string> maccodes, string Time)
  1621. {
  1622. string errorinfo = string.Empty;
  1623. string startTime = GetStartTime(Convert.ToDateTime(Time));
  1624. string FinishUnit = DllHsms.StandardCode.SVID_FinishUnit;
  1625. DateTime e = Convert.ToDateTime(Time);
  1626. DateTime s = Convert.ToDateTime(startTime);
  1627. double se = 1;
  1628. se = e.Subtract(s).TotalMinutes;// 时间差 分钟
  1629. StringBuilder sb = new StringBuilder();
  1630. sb.Append(" ( ");
  1631. for (int i = 0; i < maccodes.Count; i++)
  1632. {
  1633. //主要判断是否是最后一个条件
  1634. if (maccodes.Count - 1 == i)
  1635. {
  1636. sb.Append(" '" + maccodes[i] + "' ");
  1637. }
  1638. else
  1639. {
  1640. sb.Append(" '" + maccodes[i] + "'" + " ,");
  1641. }
  1642. }
  1643. sb.Append(" )");
  1644. StringBuilder sbs = new StringBuilder();
  1645. sbs.Append(" ( ");
  1646. for (int i = 0; i < maccodes.Count; i++)
  1647. {
  1648. //主要判断是否是最后一个条件
  1649. if (maccodes.Count - 1 == i)
  1650. {
  1651. sbs.Append(" '" + maccodes[i].Replace("0", "") + "' ");
  1652. }
  1653. else
  1654. {
  1655. sbs.Append(" '" + maccodes[i].Replace("0", "") + "'" + " ,");
  1656. }
  1657. }
  1658. sbs.Append(" )");
  1659. List<MacInfoShowLineDto> dtos = new List<MacInfoShowLineDto>();
  1660. #region
  1661. //产量
  1662. string sql = $@" SELECT
  1663. IFNULL(sum( a.FCount ),0) Count,c.FCode MacCode
  1664. FROM
  1665. maccountdetail a
  1666. LEFT JOIN maccountmst b ON a.mstid = b.id
  1667. LEFT JOIN machine c ON b.macid = c.id
  1668. WHERE
  1669. a.typeID = 0
  1670. AND a.ParamCode = '{FinishUnit}'
  1671. AND c.FCode in {sb.ToString()}
  1672. AND b.EDate BETWEEN '{startTime}'
  1673. AND '{Time}'
  1674. GROUP BY c.FCode
  1675. ";
  1676. var count = CurrDb.FindList<MacInfoShowLineDto>(sql);
  1677. //稼动率,故障率,功能开启
  1678. string sqlrate = $@"SELECT
  1679. a.FCode MacCode,a.IsControl,f.PCode,c.FCode statusName,
  1680. {OfilmRecipeProvider.GenRecipeString("m")} recipe,
  1681. IFNULL( ROUND( tt.RUN / 60 / {se} * 100, 1 ), 0 ) runRate,
  1682. IFNULL( ROUND( tt.ERROR / 60 / {se} * 100, 1 ), 0 ) errorRate
  1683. FROM
  1684. Machine a
  1685. LEFT JOIN (
  1686. -- SELECT
  1687. -- a.MacCode,
  1688. -- sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1689. -- sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1690. -- FROM
  1691. -- macstatus a
  1692. -- WHERE
  1693. -- StatusID IN ( 4, 6 )
  1694. -- AND a.RecTime > '2021-06-01 08:30'
  1695. -- AND a.MacCode IN ( 'DA00027', 'WB00151', 'WB00152', 'WB00153', 'WB00154', 'WB00155', 'WB00156', 'LHA0029', 'AA00058' )
  1696. -- GROUP BY
  1697. -- a.MacCode
  1698. SELECT
  1699. sum( t.RUN ) AS RUN,
  1700. sum( t.ERROR ) AS ERROR,
  1701. t.maccode
  1702. FROM
  1703. (
  1704. SELECT
  1705. sum( CASE StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1706. sum( CASE StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR,
  1707. maccode
  1708. FROM
  1709. macstatus
  1710. WHERE
  1711. stime > '{startTime}'
  1712. AND StatusID IN ( 4, 6 )
  1713. AND MacCode IN {sb.ToString()}
  1714. GROUP BY
  1715. maccode
  1716. UNION ALL
  1717. SELECT
  1718. sum( CASE StatusID WHEN 4 THEN ifnull( time_to_sec(timediff('{Time}',stime)), 0 ) ELSE 0 END ) RUN,
  1719. sum( CASE StatusID WHEN 6 THEN ifnull( time_to_sec(timediff('{Time}',stime)), 0 ) ELSE 0 END ) ERROR,
  1720. maccode
  1721. FROM
  1722. macstatus
  1723. WHERE
  1724. StatusID IN ( 4, 6 )
  1725. AND MacCode IN {sb.ToString()}
  1726. AND etime = '0001-01-01 00:00:00'
  1727. AND flen = 0
  1728. AND stime > '{startTime}'
  1729. AND stime <= '{Time}'
  1730. GROUP BY
  1731. maccode
  1732. UNION ALL
  1733. SELECT
  1734. sum( CASE StatusID WHEN 4 THEN ifnull( time_to_sec(timediff(etime, '{startTime}')), 0 ) ELSE 0 END ) RUN,
  1735. sum( CASE StatusID WHEN 6 THEN ifnull( time_to_sec(timediff(etime, '{startTime}')), 0 ) ELSE 0 END ) ERROR,
  1736. maccode
  1737. FROM
  1738. macstatus
  1739. WHERE
  1740. StatusID IN ( 4, 6 )
  1741. AND MacCode IN {sb.ToString()}
  1742. AND stime <= '{startTime}' AND etime > '{startTime}'
  1743. GROUP BY
  1744. maccode
  1745. ) t
  1746. GROUP BY
  1747. t.maccode
  1748. ) tt ON tt.MacCode = a.FCode
  1749. LEFT OUTER JOIN macstatus01 m ON a.fcode = m.maccode
  1750. LEFT JOIN standardstatus c on m.StatusID=c.id
  1751. LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1752. LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1753. WHERE
  1754. 1 = 1
  1755. AND a.FCode in {sb.ToString()}";
  1756. var rate = CurrDb.FindList<MacInfoShowLineDto>(sqlrate);
  1757. //报警top1、报警top2、报警top3
  1758. string sqlalarmcode = $@"SELECT NAME,
  1759. description,mcacode,
  1760. sum( count ) AS AlarmCount
  1761. FROM
  1762. (
  1763. SELECT NAME
  1764. ,
  1765. description,
  1766. t.count,
  1767. t.mcacode
  1768. FROM
  1769. (
  1770. SELECT
  1771. AlarmCode AS NAME,
  1772. AlarmDesc AS description,
  1773. mcacode,
  1774. SUM( 1 ) AS count
  1775. FROM
  1776. McaEventStatisticByDay a
  1777. WHERE
  1778. 1 = 1
  1779. AND AlarmCode != ''
  1780. AND a.startTime >= '{startTime}'
  1781. AND a.startTime <= '{Time}'
  1782. GROUP BY
  1783. alarmcode,
  1784. alarmdesc,
  1785. mcacode
  1786. ) t
  1787. LEFT JOIN Machine b ON t.mcacode = b.FCode
  1788. WHERE
  1789. 1 = 1
  1790. AND b.FCode in {sb.ToString()}
  1791. ) aa
  1792. GROUP BY
  1793. NAME,
  1794. description ,mcacode
  1795. ORDER BY
  1796. mcacode,sum( count ) DESC
  1797. ";
  1798. var alarm = CurrDb.FindList<MacAlarm>(sqlalarmcode);
  1799. //MTBA
  1800. string sqlmtba = $@"SELECT
  1801. a.FCode AS MacCode,
  1802. a.FName AS MacName,
  1803. d.FCode AS ModelCode,
  1804. me.EventCode,
  1805. me.timelen AS TimeSpan,
  1806. me.count AS Count
  1807. FROM
  1808. (
  1809. SELECT
  1810. sum( timespan ) AS timelen,
  1811. count( 1 ) AS count,
  1812. mcacode,
  1813. eventcode
  1814. FROM
  1815. mcaeventstatisticbyday e
  1816. WHERE
  1817. StartTime >= '{startTime}'
  1818. AND StartTime < '{Time}'
  1819. and McaCode IN {sb.ToString()}
  1820. GROUP BY
  1821. mcacode,
  1822. eventcode
  1823. ) me
  1824. INNER JOIN machine a ON a.FCode = me.McaCode
  1825. INNER JOIN macmodel d ON d.ID = a.MModeID
  1826. ORDER BY
  1827. me.count DESC";
  1828. var mtbaList = CurrDb.FindList<MacMTBAEntity>(sqlmtba);
  1829. IEnumerable<MacInfoShowLineDto> shujian = null;
  1830. IEnumerable<FixedPersonPost> fix = null;
  1831. IEnumerable<MacInfoShowLineDto> falResult = null;
  1832. using (IDatabase db = DbFactory.Base("ccmrpt"))
  1833. {
  1834. string sqlFal = $@" SELECT
  1835. to_char(CREATED,'yyyy-mm-dd hh24:mi:ss') AS FalTime,
  1836. EQUIPMENT_ID AS MacCode
  1837. FROM
  1838. ccmrpt.CCMMES_IPQC_PROTUCT_TEST_V t
  1839. WHERE
  1840. CREATED > to_date( '{startTime}', 'yyyy-mm-dd hh24:mi:ss' )
  1841. AND FIRST_TYPE='首件'
  1842. AND EQUIPMENT_ID IN {sb.ToString()} ";
  1843. shujian = db.FindList<MacInfoShowLineDto>(sqlFal);
  1844. string sqlFix = $@"SELECT
  1845. max( work_num) as WorkNm,max(Name) as Name,EQUIPMENT_ID as MacCode
  1846. FROM
  1847. ccmrpt.EES_EQUIPMENT_OPER_LOG_v
  1848. WHERE EQUIPMENT_ID IN {sb.ToString()}
  1849. GROUP BY EQUIPMENT_ID";
  1850. fix = db.FindList<FixedPersonPost>(sqlFix);
  1851. }
  1852. using (IDatabase db = DbFactory.Base("CCMQIS"))
  1853. {
  1854. string sqlFal = $@" select inspection_conclusion as FalResult,equipment_no as MacCode from ofg_qis.MFG_INSPECTION_REPORT_VIEW
  1855. where CREATED_TIME > '{startTime}'
  1856. ";
  1857. //AND equipment_no IN { sbs.ToString()}
  1858. falResult = db.FindList<MacInfoShowLineDto>(sqlFal);
  1859. }
  1860. dtos = count.ToList();
  1861. foreach (MacInfoShowLineDto item in dtos)
  1862. {
  1863. item.IsControl = rate.Where(l => l.MacCode == item.MacCode).Select(c => c.IsControl).FirstOrDefault();
  1864. item.RunRate = rate.Where(l => l.MacCode == item.MacCode).Select(c => c.RunRate).FirstOrDefault();
  1865. item.ErrorRate = rate.Where(l => l.MacCode == item.MacCode).Select(c => c.ErrorRate).FirstOrDefault();
  1866. item.Recipe = rate.Where(l => l.MacCode == item.MacCode).Select(c => c.Recipe).FirstOrDefault();
  1867. item.PCode = rate.Where(l => l.MacCode == item.MacCode).Select(c => c.PCode).FirstOrDefault();
  1868. item.StatusName = rate.Where(l => l.MacCode == item.MacCode).Select(c => c.StatusName).FirstOrDefault();
  1869. item.MacAlarms = alarm.Where(l => l.Mcacode == item.MacCode).Take(3).ToList();
  1870. item.FalTime = shujian.Where(l => l.MacCode == item.MacCode).Select(c => c.FalTime).FirstOrDefault();
  1871. item.FalResult = falResult != null && falResult.Any() ? falResult.Where(l => l.MacCode == item.MacCode.Replace("0", "")).Select(c => c.FalResult).FirstOrDefault() : "No";
  1872. item.FixedPersonPosts = fix.Where(l => l.MacCode == item.MacCode).FirstOrDefault();
  1873. //MTBA
  1874. var macMtbaList = mtbaList.Where(m => m.MacCode == item.MacCode).ToList();
  1875. var runList = macMtbaList.Any() ? macMtbaList.Where(m => m.EventCode == "C00012").ToList() : null;
  1876. var alarmList = macMtbaList.Any() ? macMtbaList.Where(m => m.EventCode == "C00007").ToList() : null;
  1877. var runTimeSpan = runList != null && runList.Any() ? runList.Sum(m => m.TimeSpan) : 0;
  1878. var alarmCount = alarmList != null && alarmList.Any() ? alarmList.Sum(m => m.Count) : 1;
  1879. item.MTBA = (runTimeSpan / alarmCount / 60).ToString("f2");
  1880. }
  1881. List<MacInfoShowLineDto> dtoss = new List<MacInfoShowLineDto>();
  1882. dtoss.AddRange(dtos.Where(l => l.MacCode.StartsWith("DA")));
  1883. dtoss.AddRange(dtos.Where(l => l.MacCode.StartsWith("WB")));
  1884. dtoss.AddRange(dtos.Where(l => l.MacCode.StartsWith("LHA")));
  1885. dtoss.AddRange(dtos.Where(l => l.MacCode.StartsWith("AA")));
  1886. MacDto macDto = new MacDto();
  1887. macDto.macInfoShowLineDtos = dtoss;
  1888. macDto.TotalCount = dtoss.Where(l => l.MacCode.StartsWith("DA")).Sum(c => c.Count);
  1889. macDto.OutCount = dtoss.Where(l => l.MacCode.StartsWith("AA")).Sum(c => c.Count);
  1890. macDto.Recipe = dtoss.Select(c => c.Recipe).FirstOrDefault();
  1891. #endregion
  1892. return macDto;
  1893. }
  1894. /// <summary>
  1895. /// 根据当前时间获取班别开始时间
  1896. /// </summary>
  1897. /// <param name="now"></param>
  1898. /// <returns></returns>
  1899. private static string GetStartTime(DateTime now)
  1900. {
  1901. try
  1902. {
  1903. //DateTime now = DateTime.Now;
  1904. string starttime = "";
  1905. //00:00 08:30 20:30 23:59
  1906. DateTime nowstr = Convert.ToDateTime(now.ToString("HH:mm"));
  1907. DateTime dt1 = Convert.ToDateTime("00:00");
  1908. DateTime dt2 = Convert.ToDateTime("08:30");
  1909. DateTime dt3 = Convert.ToDateTime("20:30");
  1910. DateTime dt4 = Convert.ToDateTime("23:59");
  1911. if (DateTime.Compare(nowstr, dt1) > 0 && DateTime.Compare(nowstr, dt2) < 0)
  1912. {
  1913. starttime = now.AddDays(-1).ToString("yyyy-MM-dd") + " 20:30";
  1914. }
  1915. else if (DateTime.Compare(nowstr, dt2) > 0 && DateTime.Compare(nowstr, dt3) < 0)
  1916. {
  1917. starttime = now.ToString("yyyy-MM-dd") + " 08:30";
  1918. }
  1919. else if (DateTime.Compare(nowstr, dt3) > 0 && DateTime.Compare(nowstr, dt4) < 0)
  1920. {
  1921. starttime = now.ToString("yyyy-MM-dd") + " 20:30";
  1922. }
  1923. return starttime;
  1924. }
  1925. catch (Exception xe)
  1926. {
  1927. return "";
  1928. }
  1929. }
  1930. /// <summary>
  1931. /// 获取每个机台的最后一个
  1932. /// </summary>
  1933. /// <returns></returns>
  1934. public async Task StoreLastStatus()
  1935. {
  1936. }
  1937. /// <summary>
  1938. /// 删除查询时创建的临时视图
  1939. /// </summary>
  1940. /// <returns></returns>
  1941. public async Task ClearTempViews()
  1942. {
  1943. using (IDatabase db = DbFactory.Base("eapslave"))
  1944. {
  1945. var viewPrefixs = new string[] {
  1946. "v_temp_last_status_",
  1947. "V_MacStatus_Detail_",
  1948. "v_temp_alarm_",
  1949. "V_Status_Mac_",
  1950. "V_Output_Day_"
  1951. };
  1952. var ticks = DateTime.Now.AddMinutes(-5).Ticks;
  1953. foreach (var item in viewPrefixs)
  1954. {
  1955. var sql = $@"select TABLE_NAME from INFORMATION_SCHEMA.VIEWS where TABLE_NAME like
  1956. '%{item}%' and TABLE_SCHEMA='eap' ";
  1957. var views = await db.FindListAsync<string>(sql, null);
  1958. if (views != null && views.Count() > 0)
  1959. {
  1960. foreach (var viewName in views)
  1961. {
  1962. var viewTicks = Convert.ToInt64(viewName.Split('_').Last());
  1963. if (viewTicks < ticks)
  1964. {
  1965. var drop = $"DROP VIEW IF EXISTS {viewName};";
  1966. db.ExecuteBySql(drop);
  1967. }
  1968. }
  1969. }
  1970. }
  1971. }
  1972. }
  1973. }
  1974. }