McaEventStatisticByDayDal.cs 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  1. using System;
  2. using System.Collections.Generic;
  3. using Cksoft.Data;
  4. using DllEapEntity;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using DllEapEntity.Dtos;
  8. using Cksoft.Data.Repository;
  9. using Cksoft.Unity;
  10. using System.Collections.Concurrent;
  11. using DllEapEntity.Mes;
  12. using DllHsms;
  13. using Cksoft.Unity.Log4NetConfig;
  14. using DllAmbiguity;
  15. namespace DllEapDal
  16. {
  17. public class McaEventStatisticByDayDal
  18. {
  19. public IDatabase CurrDb;
  20. public McaEventStatisticByDayDal(IDatabase db)
  21. {
  22. this.CurrDb = db;
  23. }
  24. #region 页面数据分析相关
  25. public IEnumerable<McaEventStatisticByDay> GetStatisticDetails(string filter, string subFilter)
  26. {
  27. string sql = $@"select t.id,t.eventcode,t.alarmcode,t.alarmdesc,t.mcacode,t.starttime,t.endtime,t.TimeSpan,
  28. f.FCode as Manufacturer,b.FName as McaName,e.FName as MacModelName,e.FCode as MacModel,c.PCode,d.FName as PName,g.FName as Factory,b.RegionId
  29. from (
  30. select year(a.starttime) as year,MONTH(a.StartTime) as month,DAY(a.StartTime) as day,
  31. a.Id,a.EventCode,a.AlarmCode,a.AlarmDesc,a.McaCode,
  32. a.StartTime,a.EndTime,a.TimeSpan
  33. from McaEventStatisticByDay a
  34. where 1=1 {filter}
  35. ) t
  36. left join Machine b on t.McaCode=b.FCode
  37. left join MacTProcess c on b.id=c.MacID
  38. left join TProcess d on c.PCode=d.FCode
  39. left join MacModel e on b.MModeId=e.id
  40. left join Supplier f on e.SupplierId=f.id
  41. left join FactoryRegion g on b.FactoryId=g.id
  42. where 1=1 and b.isanalysis<>-1 {subFilter}";
  43. return CurrDb.FindList<McaEventStatisticByDay>(sql);
  44. }
  45. public IEnumerable<McaEventStatisticByDay> GetStatisticDetailsForDisplay(string filter)
  46. {
  47. string sql = @"select SUBSTRING(CONVERT(varchar(50),StartTime,24),0,3) hour,
  48. a.Id,f.FCode as Manufacturer,a.EventCode,a.AlarmCode,a.AlarmDesc,a.McaCode,b.FName as McaName,
  49. e.FName as MacModelName,a.StartTime,a.EndTime,a.TimeSpan,a.IsInProducing,a.IsHandled,
  50. e.FCode as MacModel,c.PCode,d.FName as PName from McaEventStatisticByDay a
  51. left join Machine b on a.McaCode=b.FCode
  52. left join MacTProcess c on b.id=c.MacID
  53. left join TProcess d on c.PCode=d.FCode
  54. left join MacModel e on b.MModeId=e.id
  55. left join Supplier f on e.SupplierId=f.id "
  56. + $" where 1=1 and b.isanalysis<>-1 {filter}";
  57. return CurrDb.FindList<McaEventStatisticByDay>(sql);
  58. }
  59. /// <summary>
  60. /// 机台某一时间段报警统计(柱状图)
  61. /// </summary>
  62. /// <param name="startTime"></param>
  63. /// <param name="endTime"></param>
  64. /// <returns></returns>
  65. public ChartDto CreateCategory(string filter, string subFilter, int take = 10)
  66. {
  67. //var dto = GetAlarmAnalysis(filter, subFilter, "name", "asc").OrderByDescending(c => c.count).Take(take).OrderBy(c => c.maccode);
  68. var dto = GetAlarmAnalysis(filter, subFilter, "name", "asc").OrderByDescending(c => c.count).Take(take);
  69. var chartDto = new ChartDto
  70. {
  71. text = "机台报警统计",
  72. legend = new string[] { "报警次数" },
  73. xdata = dto.Select(c => c.name).ToArray(),
  74. ydata = dto.Select(c => (float)c.count).ToArray()
  75. };
  76. return chartDto;
  77. }
  78. /// <summary>
  79. /// 机台报警次数分析
  80. /// </summary>
  81. /// <param name="startTime"></param>
  82. /// <param name="endTime"></param>
  83. /// <returns></returns>
  84. public IEnumerable<AnalysisDto> GetAlarmAnalysis(string mainFilter, string subFilter, string sort = "name", string order = "asc", int take = 10)
  85. {
  86. if (string.IsNullOrEmpty(sort) || sort == "null")
  87. sort = "name";
  88. if (string.IsNullOrEmpty(order) || order == "null")
  89. order = "asc";
  90. string sql = $@"
  91. SELECT Name,SUM(count) count,macname,maccode,macnumber,macmodel,PCode,PName,PName,regionId,FactoryName,FloorName,PlantName,RegionName
  92. FROM(
  93. select a.name as name,count as count,b.FName as macname,a.name as maccode,machinenumber.MacNumber as macnumber,e.FCode as macmodel,
  94. c.PCode,d.FName as PName,b.regionId,g.FName FactoryName,
  95. i.FName FloorName,j.FName PlantName,concat(g.FName,'/',i.FName,'/',h.FName) as RegionName from
  96. (select ac.McaCode as name,AlarmCode,sum(1) as count from McaEventStatisticByDay ac
  97. where 1=1 {mainFilter}
  98. group by mcacode,AlarmCode ) a
  99. left join Machine b on a.name=b.FCode
  100. left join MacTProcess c on b.id=c.MacId
  101. left join TProcess d on c.Pcode=d.FCode
  102. left join MacModel e on b.MModeId= e.id
  103. INNER JOIN mtbacode p on p.MModeID=e.id and p.alarmcode=a.AlarmCode
  104. left join Supplier f on e.SupplierID=f.id
  105. left join FactoryRegion g on b.factoryId=g.id
  106. left join FactoryRegion h on b.regionId=h.id
  107. left join FactoryRegion i on h.parentid=i.id
  108. left join FactoryRegion j on i.parentid=j.id
  109. LEFT JOIN machinenumber on b.ID=machinenumber.MacId
  110. where 1=1 {subFilter} order by count desc
  111. )t
  112. GROUP BY t.Name,macname,maccode,macnumber,macmodel,PCode,PName,PName,regionId,FactoryName,FloorName,PlantName,RegionName
  113. ORDER BY SUM(count) desc";
  114. //var dtos = CurrDb.FindList<AnalysisDto>(sql).OrderByDescending(c => c.count).Take(take).OrderBy(c => c.maccode);
  115. var dtos = CurrDb.FindList<AnalysisDto>(sql).OrderByDescending(c => c.count).Take(take);
  116. //if (dtos != null && dtos.Count() > 0)
  117. //{
  118. // var regionDal = new FactoryRegionDal(CurrDb);
  119. // string errorinfo = string.Empty;
  120. // var allRegions = regionDal.Get(1, 10000, "ID", "asc", string.Empty, errorinfo);
  121. // foreach (var item in dtos)
  122. // {
  123. // item.RegionName = regionDal.GetFullRegionName(item.RegionId, allRegions);
  124. // }
  125. //}
  126. return dtos;
  127. }
  128. public ChartDto2 CreateMtbaCategory(DateTime startTime, DateTime endTime, string tablename, string subFilter, string sub, int take = 10)
  129. {
  130. var dto = GetMtbaAnalysis(startTime, endTime, tablename, subFilter, sub, "name", "asc").OrderByDescending(c => c.count).Take(10);
  131. //var chartDto = new ChartDto
  132. //{
  133. // text = "",
  134. // legend = new string[] { "设备MTBA top10" },
  135. // xdata = dto.Select(c => c.name).ToArray(),
  136. // ydata = dto.Select(c => (float)c.count).ToArray()
  137. //};
  138. var chartDto2 = new ChartDto2();
  139. List<string> vs = new List<string>();
  140. vs.Add("汇总");
  141. //chartDto2.legend = new string[] { "汇总", "故障", "非故障" };
  142. chartDto2.xdata = dto.Select(c => c.name).ToArray();
  143. List<Series> Seriess = new List<Series>();
  144. Series series = new Series();
  145. ItemStyle itemStyle = new ItemStyle();
  146. Normal normal = new Normal();
  147. Label label = new Label();
  148. label.show = true;
  149. normal.label = label;
  150. itemStyle.normal = normal;
  151. series.itemStyle = itemStyle;
  152. series.name = "汇总";
  153. series.type = "bar";
  154. series.data = dto.Select(c => (float)c.count).ToArray();
  155. Seriess.Add(series);
  156. if (string.IsNullOrEmpty(sub) || sub.Contains("1"))
  157. {
  158. vs.Add("故障");
  159. series = new Series();
  160. series.itemStyle = itemStyle;
  161. series.name = "故障";
  162. series.type = "bar";
  163. series.data = dto.Select(c => (float)c.countOne).ToArray();
  164. Seriess.Add(series);
  165. }
  166. if (string.IsNullOrEmpty(sub) || sub.Contains("2"))
  167. {
  168. vs.Add("非故障");
  169. series = new Series();
  170. series.itemStyle = itemStyle;
  171. series.name = "非故障";
  172. series.type = "bar";
  173. series.data = dto.Select(c => (float)c.countTwo).ToArray();
  174. Seriess.Add(series);
  175. }
  176. chartDto2.legend = vs.ToArray();
  177. chartDto2.series = Seriess;
  178. return chartDto2;
  179. }
  180. public IEnumerable<AnalysisDto> GetMtbaAnalysis(DateTime startTime, DateTime endTime, string tablename, string subFilter, string sub, string sort = "name", string order = "asc", int take = 10)
  181. {
  182. if (string.IsNullOrEmpty(sort) || sort == "null")
  183. sort = "name";
  184. if (string.IsNullOrEmpty(order) || order == "null")
  185. order = "asc";
  186. #region
  187. //string sql = $@"SELECT
  188. // c.fcode name,
  189. // c.timespan / c.count / 60 count,
  190. // timespan
  191. // FROM
  192. // (
  193. // SELECT
  194. // a.FCode,
  195. // ifnull( b.timespan, '0' ) timespan,
  196. // ifnull( b.count, '0' ) count
  197. // FROM
  198. // machine a
  199. // LEFT JOIN (
  200. // SELECT
  201. // mcacode,
  202. // sum( CASE WHEN ( EventCode = 'C00007' ) THEN 1 ELSE 0 END ) AS count,
  203. // sum( CASE WHEN EventCode = 'C00012' THEN timespan ELSE 0 END ) AS timespan
  204. // FROM
  205. // mcaeventstatisticbyday
  206. // WHERE
  207. // starttime >= '{startTime.ToString("yyyy-MM-dd HH:mm:ss")}' and starttime < '{endTime.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}'
  208. // GROUP BY
  209. // mcacode
  210. // ) b ON a.fcode = b.mcacode
  211. // inner JOIN factoryregion i ON i.Id=a.FactoryId
  212. // INNER JOIN factoryregion j ON j.Id=a.RegionId
  213. // INNER JOIN factoryregion k ON k.Id=j.ParentId
  214. // INNER JOIN factoryregion l ON l.id=k.ParentId
  215. // where 1=1 {subFilter}
  216. // ) c
  217. // ORDER BY
  218. // c.timespan / c.count DESC
  219. // LIMIT 10 ";
  220. #endregion
  221. #region
  222. // string sql = $@"SELECT
  223. // c.fcode NAME,
  224. //sum( c.timespan) /(case when sum( c.count)=0 then 1 else sum( c.count) end) / 60 count,
  225. //SUM(c.count) allcount,
  226. //SUM(TimeSpan) TimeSpan,
  227. //sum( CASE WHEN faulttype=1 THEN Count WHEN faulttype='' THEN Count WHEN faulttype IS NULL THEN Count ELSE 0 END ) CountOne,
  228. //sum( CASE faulttype WHEN 2 THEN Count ELSE 0 END ) CountTwo
  229. //FROM
  230. // (
  231. // SELECT
  232. // a.FCode,
  233. // ifnull( b.timespan, '0' ) timespan,
  234. // ifnull( b.count, '0' ) count
  235. // ,p.faulttype
  236. // FROM
  237. // machine a
  238. // LEFT JOIN (
  239. // SELECT
  240. // mcacode,AlarmCode
  241. // ,sum( CASE WHEN ( EventCode = 'C00007' ) THEN 1 ELSE 0 END ) AS count
  242. // ,sum( CASE WHEN EventCode = 'C00012' THEN timespan ELSE 0 END ) AS timespan
  243. // FROM
  244. // mcaeventstatisticbyday
  245. // WHERE
  246. // starttime >= '{startTime.ToString("yyyy-MM-dd HH:mm:ss")}'
  247. // AND starttime < '{endTime.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}'
  248. // GROUP BY
  249. // mcacode ,AlarmCode
  250. // ) b ON a.fcode = b.mcacode
  251. // LEFT JOIN mtbacode p on p.MModeID = a.MModeID and b.AlarmCode = p.AlarmCode
  252. // INNER JOIN factoryregion i ON i.Id = a.FactoryId
  253. // INNER JOIN factoryregion j ON j.Id = a.RegionId
  254. // INNER JOIN factoryregion k ON k.Id = j.ParentId
  255. // INNER JOIN factoryregion l ON l.id = k.ParentId
  256. // WHERE
  257. // 1 = 1 {subFilter} {sub}
  258. // ) c
  259. // GROUP BY FCode
  260. //ORDER BY
  261. // sum( c.timespan) /(case when sum( c.count)=0 then 1 else sum( c.count) end) / 60 DESC
  262. // LIMIT 10";
  263. #endregion
  264. string sql = $@"
  265. select
  266. a.FCode NAME
  267. ,b.timespan /(case when b.count=0 then 1 else b.count end) / 60 count
  268. ,b.timespan /(case when b.CountOne=0 then 1 else b.CountOne end) / 60 CountOne
  269. ,b.timespan /(case when b.CountTwo=0 then 1 else b.CountTwo end) / 60 CountTwo
  270. ,b.timespan
  271. from
  272. machine a
  273. INNER JOIN(SELECT
  274. maccode MacCode,
  275. sum( CASE WHEN ( EventCode = 'C00007' ) THEN count ELSE 0 END ) AS count,
  276. sum( CASE WHEN ( EventCode = 'C00007' ) THEN CountOne ELSE 0 END ) AS CountOne,
  277. sum( CASE WHEN ( EventCode = 'C00007' ) THEN CountTwo ELSE 0 END ) AS CountTwo,
  278. sum( CASE WHEN EventCode = 'C00012' THEN timespan ELSE 0 END ) AS timespan
  279. FROM
  280. {tablename}
  281. GROUP BY
  282. maccode) b on a.FCode=b.MacCode
  283. LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  284. INNER JOIN factoryregion i ON i.Id = a.FactoryId
  285. INNER JOIN factoryregion j ON j.Id = a.RegionId
  286. INNER JOIN factoryregion k ON k.Id = j.ParentId
  287. INNER JOIN factoryregion l ON l.id = k.ParentId
  288. ORDER BY b.timespan /(case when b.count=0 then 1 else b.count end) / 60 DESC limit 10;
  289. ";
  290. var dtos = CurrDb.FindList<AnalysisDto>(sql).OrderByDescending(c => c.count).Take(take).OrderBy(c => c.maccode);
  291. //foreach (var item in dtos)
  292. //{
  293. // if (item.countOne == 0)
  294. // {
  295. // item.countOne = 1;
  296. // }
  297. // if (item.countTwo == 0)
  298. // {
  299. // item.countTwo = 1;
  300. // }
  301. // //if (item.allcount == 0)
  302. // //{
  303. // // item.count = item.TimeSpan / 60;
  304. // //}
  305. // item.countOne = item.TimeSpan / item.countOne / 60;
  306. // item.countTwo = item.TimeSpan / item.countTwo / 60;
  307. //}
  308. return dtos;
  309. }
  310. /// <summary>
  311. /// 报警代码分析
  312. /// </summary>
  313. /// <param name="startTime"></param>
  314. /// <param name="endTime"></param>
  315. /// <param name="macModel"></param>
  316. /// <param name="pCode"></param>
  317. /// <returns></returns>
  318. public IEnumerable<AnalysisDto> GetAlarmCodeAnalysis(string filter, string subFilter, int pageSize, int pageIndex, out int total, string sort = "count", string order = "desc")
  319. {
  320. if (string.IsNullOrEmpty(sort) || sort == "null")
  321. sort = "count";
  322. if (string.IsNullOrEmpty(order) || order == "null")
  323. order = "desc";
  324. string sql = $@"select name,chalarm,description,sum(count) as count from (
  325. select name,p.chalarm,description,t.count,t.mcacode from (
  326. select AlarmCode as name,AlarmDesc as description,mcacode,SUM(1) as count
  327. from McaEventStatisticByDay a
  328. where 1=1 {filter} group by alarmcode,alarmdesc,
  329. mcacode) t
  330. left join Machine b on t.mcacode=b.FCode
  331. left join MacTProcess c on b.id=c.MacId
  332. left join TProcess d on c.Pcode=d.FCode
  333. left join MacModel e on b.MModeId= e.id
  334. INNER JOIN mtbacode p on p.MModeID=e.id and p.alarmcode=t.name
  335. left join Supplier f on e.Supplierid=f.id
  336. left join FactoryRegion g on b.factoryId=g.id
  337. left join FactoryRegion h on b.regionId=h.id
  338. left join FactoryRegion i on h.parentid=i.id
  339. left join FactoryRegion j on i.parentid=j.id
  340. where 1=1 {subFilter}) aa group by name,chalarm,description
  341. order by {sort} {order} limit {(pageIndex - 1) * pageSize},{pageSize}";
  342. var dtos = CurrDb.FindList<AnalysisDto>(sql);
  343. sql = $@"select count(1) from (select name,description,sum(count) as count from (
  344. select name,description,t.count,t.mcacode from (
  345. select AlarmCode as name,AlarmDesc as description,mcacode,SUM(1) as count
  346. from McaEventStatisticByDay a
  347. where 1=1 {filter} group by alarmcode,alarmdesc,
  348. mcacode) t
  349. left join Machine b on t.mcacode=b.FCode
  350. left join MacTProcess c on b.id=c.MacId
  351. left join TProcess d on c.Pcode=d.FCode
  352. left join MacModel e on b.MModeId= e.id
  353. INNER JOIN mtbacode p on p.MModeID=e.id and p.alarmcode=t.name
  354. left join Supplier f on e.Supplierid=f.id
  355. left join FactoryRegion g on b.factoryId=g.id
  356. left join FactoryRegion h on b.regionId=h.id
  357. left join FactoryRegion i on h.parentid=i.id
  358. left join FactoryRegion j on i.parentid=j.id
  359. where 1=1 {subFilter}) aa group by name,description) temp";
  360. total = Convert.ToInt32(CurrDb.FindObject(sql) ?? "0");
  361. return dtos;
  362. }
  363. public IEnumerable<DllEapEntity.OFILM.PostbondviewDto> GetLHADataAnalysis(string filter, string subFilter, int pageSize, int pageIndex, out int total, string sort = "time", string order = "asc")
  364. {
  365. if (string.IsNullOrEmpty(sort) || sort == "null")
  366. sort = "time";
  367. if (string.IsNullOrEmpty(order) || order == "null")
  368. order = "asc";
  369. string sql = $@"SELECT
  370. {OfilmRecipeProvider.GenRecipeString("b")} recipe,g.FCode,
  371. h.rownum,h.Time,h.MacCode,h.OffsetX,h.OffsetY,h.OffsetT,diff_X,diff_Y,diff_T
  372. FROM
  373. -- (SELECT * FROM postbondview a FORCE INDEX(Time) where 1=1 {filter}) h
  374. -- postbondview p
  375. (
  376. select t1.rownum rownum, t2.rownum t2_rownum,
  377. t1.Time,t1.MacCode,
  378. t1.OffsetX ,t1.OffsetY,t1.OffsetT,
  379. (t1.OffsetX - t2.OffsetX) diff_X,
  380. (t1.OffsetY - t2.OffsetY) diff_Y,
  381. (t1.OffsetT - t2.OffsetT) diff_T
  382. from
  383. (SELECT
  384. (@rownum :=@rownum+1) as rownum,p.Time,p.OffsetX,p.OffsetY,p.OffsetT,p.MacCode
  385. FROM
  386. postbondview p FORCE INDEX(Time),(select @rownum :=0) r
  387. where 1=1 {filter}
  388. ORDER BY p.time
  389. ) t1
  390. inner JOIN
  391. (SELECT
  392. (@index :=@index+1) as rownum,p.Time,p.OffsetX,p.OffsetY,p.OffsetT,p.MacCode
  393. FROM
  394. postbondview p FORCE INDEX(Time),(select @index :=0) r
  395. where 1=1 {filter}
  396. ORDER BY p.time
  397. ) t2
  398. ON t1.rownum-1 = t2.rownum) h
  399. LEFT JOIN machine a ON a.fcode = h.maccode
  400. LEFT JOIN macstatus01 b ON a.FCode = b.maccode
  401. LEFT JOIN mactprocess c ON a.id = c.macid
  402. LEFT JOIN tprocess g ON c.pcode = g.fcode
  403. where 1=1 {subFilter}
  404. order by {sort} {order} limit {(pageIndex - 1) * pageSize},{pageSize}";
  405. var dtos = CurrDb.FindList<DllEapEntity.OFILM.PostbondviewDto>(sql);
  406. sql = $@" SELECT count(1) from postbondview p where 1=1 {filter} ";
  407. total = Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  408. // 第一行极差值为0
  409. if (dtos.Count() >= 1)
  410. {
  411. dtos.FirstOrDefault().Diff_X = "0";
  412. dtos.FirstOrDefault().Diff_Y = "0";
  413. dtos.FirstOrDefault().Diff_T = "0";
  414. }
  415. return dtos;
  416. }
  417. /// <summary>
  418. /// 根据报警代码进行统计分析
  419. /// </summary>
  420. /// <param name="startTime"></param>
  421. /// <param name="endTime"></param>
  422. /// <param name="macModel"></param>
  423. /// <param name="pCode"></param>
  424. /// <returns></returns>
  425. public ChartDto CreateAlarmCat(string filter, string subFilter, int take = 10)
  426. {
  427. int total;
  428. var dto = this.GetAlarmCodeAnalysis(filter, subFilter, 10, 1, out total).OrderByDescending(c => c.count).Take(take).OrderBy(c => c.maccode);
  429. var chartDto = new ChartDto
  430. {
  431. text = "报警统计",
  432. legend = new string[] { "报警次数" },
  433. xdata = dto.Select(c => c.name).ToArray(),
  434. ydata = dto.Select(c => (float)c.count).ToArray()
  435. };
  436. return chartDto;
  437. }
  438. /// <summary>
  439. /// 获取报警代码详情
  440. /// </summary>
  441. /// <param name="filter"></param>
  442. /// <param name="sort"></param>
  443. /// <param name="order"></param>
  444. /// <returns></returns>
  445. public IEnumerable<AlarmCode> GetAramCodeDetail(string filter, string subFilter, string sub, int start, int length, out int total, string sort = "ptime", string order = "desc")
  446. {
  447. if (string.IsNullOrEmpty(sort) || sort == "null")
  448. sort = "ptime";
  449. if (string.IsNullOrEmpty(order) || order == "null")
  450. order = "desc";
  451. string sql = $@"select tt.maccode as maccode,b.Fname as macname,tt.name as name,tt.description as description,
  452. c.Pcode,d.fname as pname,e.FCode as macmodel,tt.ptime as ptime,b.RegionId,g.FName FactoryName,
  453. i.FName FloorName,j.FName PlantName,p.chalarm
  454. from
  455. (select a.McaCode as maccode,a.AlarmCode as name,a.AlarmDesc as description,a.StartTime as ptime
  456. from McaEventStatisticByDay a FORCE INDEX(starttime) where 1=1 {filter}) tt
  457. left join machine b on tt.maccode=b.FCode
  458. left join mactprocess c on b.id=c.macid
  459. left join tprocess d on c.pcode=d.fcode
  460. inner join MacModel e on b.MModeId= e.id
  461. INNER JOIN mtbacode p on p.MModeID=e.id and p.alarmcode=tt.name
  462. left join Supplier f on e.SupplierId=f.id
  463. left join FactoryRegion g on b.factoryId = g.id
  464. left join FactoryRegion h on b.regionId=h.id
  465. left join FactoryRegion i on h.parentId = i.id
  466. left join FactoryRegion j on i.parentId = j.id
  467. where 1=1 and b.isanalysis<>-1 {subFilter} {sub} order by {sort} {order} limit {start - 1},{length}";
  468. var datas = CurrDb.FindList<AlarmCode>(sql);
  469. sql = $@"select sum(alarmcount) from (select mcacode,count(1) as alarmcount from McaEventStatisticByDay a
  470. where 1=1 {filter} and EventCode='C00007'
  471. and EventCode='C00007' group by mcacode ) tt
  472. inner join
  473. (select b.fcode from machine b
  474. inner join mactprocess c on b.id=c.macid
  475. inner join tprocess d on c.pcode=d.fcode
  476. inner join MacModel e on b.MModeId= e.id
  477. -- INNER JOIN mtbacode p ON p.MModeID = e.id
  478. inner join Supplier f on e.SupplierId=f.id
  479. inner join FactoryRegion g on b.factoryId = g.id
  480. inner join FactoryRegion h on b.regionId=h.id
  481. inner join FactoryRegion i on h.parentId = i.id
  482. inner join FactoryRegion j on i.parentId = j.id
  483. where 1=1 {subFilter}) macinfo on tt.mcacode=macinfo.fcode ";
  484. total = Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  485. return datas;
  486. }
  487. public int GetAlarmCodeCount(string filter)
  488. {
  489. string sql = $@"select count(*)
  490. from McaEventStatisticByDay a force index(starttime)
  491. where 1=1
  492. and a.eventcode='C00007' {filter}";
  493. return Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  494. }
  495. public IEnumerable<MacTProcess> GetAllMachines(string filter)
  496. {
  497. string sql = $@"select a.*,b.FCode MacCode,b.FName MacName,d.FCode MacModel,c.FName ProcessName,
  498. c.FCode ProcessCode,d.FName MacModelName,e.FName factory,f.FName line,g.FName floor from MacTProcess a
  499. left join Machine b on a.MacID=b.ID
  500. left join TProcess c on a.PCode = c.FCode
  501. left join MacModel d on b.MModeId=d.id
  502. left join factoryregion e on b.factoryId=e.id
  503. left join factoryregion f on b.regionId=f.id
  504. left join factoryregion g on f.parentid=g.id
  505. where 1=1 {filter}";
  506. var machines = CurrDb.FindList<MacTProcess>(sql);
  507. if (machines != null && machines.Count() > 0)
  508. {
  509. foreach (var item in machines)
  510. {
  511. item.RegionName = ((!string.IsNullOrEmpty(item.Factory)) ? ("/" + item.Factory) : "")
  512. + ((!string.IsNullOrEmpty(item.Floor)) ? ("/" + item.Floor) : "")
  513. + ((!string.IsNullOrEmpty(item.Line)) ? ("/" + item.Line) : "");
  514. if (!string.IsNullOrEmpty(item.RegionName))
  515. item.RegionName = item.RegionName.Substring(1);
  516. }
  517. }
  518. return machines;
  519. }
  520. /// <summary>
  521. /// 获取MTBF统计
  522. /// </summary>
  523. /// <param name="mcaVMsts"></param>
  524. /// <returns></returns>
  525. public IEnumerable<MTBFDto> GetMTBFs(string filter, string subFilter, string type)
  526. {
  527. var msts = GetStatisticDetails($" and EventCode = '{DllHsms.StandardCode.CEID_Run}'" + filter, subFilter).Where(c => c.TimeSpan != null);
  528. var alarms = GetStatisticDetails($" and EventCode = '{DllHsms.StandardCode.CEID_AlarmOccurred}'" + filter, subFilter).Where(c => c.TimeSpan != null);
  529. switch (type)
  530. {
  531. case "machine":
  532. var groups = alarms.GroupBy(c => new { c.McaCode, c.McaName });
  533. var list = new List<MTBFDto>();
  534. foreach (var item in groups)
  535. {
  536. var mtbf = new MTBFDto()
  537. {
  538. name = item.Key.McaName,
  539. count = item.Count(),
  540. code = item.Key.McaCode,
  541. pcode = item.FirstOrDefault().PCode,
  542. minutes = msts.Where(c => c.McaCode == item.Key.McaCode).Sum(c =>
  543. {
  544. return (float)(c.TimeSpan == null ? 0 : c.TimeSpan) / 60f;
  545. })
  546. };
  547. mtbf.MTBF = mtbf.minutes / mtbf.count;
  548. list.Add(mtbf);
  549. }
  550. return list.Where(c => !string.IsNullOrEmpty(c.code)).OrderByDescending(c => c.MTBF).Take(10);
  551. case "macmodel":
  552. var groupsMacModels = alarms.GroupBy(c => new { c.MacModel });
  553. var listMacModels = new List<MTBFDto>();
  554. foreach (var item in groupsMacModels)
  555. {
  556. var mtbf = new MTBFDto()
  557. {
  558. name = item.Key.MacModel,
  559. count = item.Count(),
  560. code = item.Key.MacModel,
  561. minutes = msts.Where(c => c.MacModel == item.Key.MacModel).Sum(c =>
  562. {
  563. return (float)(c.TimeSpan == null ? 0 : c.TimeSpan) / 60f;
  564. })
  565. };
  566. mtbf.MTBF = mtbf.minutes / mtbf.count;
  567. listMacModels.Add(mtbf);
  568. }
  569. return listMacModels.Where(c => !string.IsNullOrEmpty(c.code)).OrderByDescending(c => c.MTBF).Take(10);
  570. case "process":
  571. var groupProcesses = alarms.GroupBy(c => new { c.PCode, c.PName });
  572. var listProcesses = new List<MTBFDto>();
  573. foreach (var item in groupProcesses)
  574. {
  575. var mtbf = new MTBFDto()
  576. {
  577. name = item.Key.PName,
  578. count = item.Count(),
  579. code = item.Key.PCode,
  580. minutes = msts.Where(c => c.PCode == item.Key.PCode).Sum(c =>
  581. {
  582. return (float)(c.TimeSpan == null ? 0 : c.TimeSpan) / 60f;
  583. })
  584. };
  585. mtbf.MTBF = mtbf.minutes / mtbf.count;
  586. listProcesses.Add(mtbf);
  587. }
  588. return listProcesses.Where(c => !string.IsNullOrEmpty(c.code)).OrderByDescending(c => c.MTBF).Take(10);
  589. default:
  590. return null;
  591. }
  592. }
  593. public string AppendFilter(string type, DateType dateType, IEnumerable<string> codes)
  594. {
  595. if (codes == null || codes.Count() <= 0)
  596. return null;
  597. var filterCodes = string.Join(",", codes.Select(c => $"'{c}'"));
  598. var typeFilter = "";
  599. if (type == "machine")
  600. {
  601. typeFilter = $" and a.McaCode in ({filterCodes})";
  602. }
  603. else if (type == "macmodel")
  604. {
  605. typeFilter = $" and c.FCode in ({filterCodes})";
  606. }
  607. else
  608. {
  609. typeFilter = $" and c.PCode in ({filterCodes})";
  610. }
  611. return typeFilter;
  612. }
  613. public EChartsBar GetMTBFsNew(string type, DateType dateType, string filter, string subFilter, IEnumerable<string> codes)
  614. {
  615. if (string.IsNullOrEmpty(filter))
  616. return null;
  617. //var msts = GetStatisticDetails($" and EventCode = '{DllHsms.StandardCode.CEID_Run}'" + filter, subFilter).Where(c => c.TimeSpan != null);
  618. //var alarms = GetStatisticDetails($" and EventCode = '{DllHsms.StandardCode.CEID_AlarmOccurred}'" + filter, subFilter).Where(c => c.TimeSpan != null);
  619. switch (type)
  620. {
  621. case "machine":
  622. filter += AppendFilter(type, dateType, codes);
  623. return GetBarsForMachine(filter, subFilter, dateType);
  624. case "macmodel":
  625. subFilter += AppendFilter(type, dateType, codes);
  626. return GetBarsForMacModel(filter, subFilter, dateType);
  627. case "process":
  628. subFilter += AppendFilter(type, dateType, codes);
  629. return GetBarsForProcess(filter, subFilter, dateType);
  630. default:
  631. return null;
  632. }
  633. }
  634. public EChartsBar GetMtbfForDisplay(string filter)
  635. {
  636. var msts = GetStatisticDetailsForDisplay($" and EventCode = '{DllHsms.StandardCode.CEID_Run}'" + filter).Where(c => c.TimeSpan != null);
  637. var alarms = GetStatisticDetailsForDisplay($" and EventCode = '{DllHsms.StandardCode.CEID_AlarmOccurred}'" + filter).Where(c => c.TimeSpan != null);
  638. alarms = alarms.Where(c => !string.IsNullOrEmpty(c.PCode)).OrderBy(c => c.StartTime);
  639. msts = msts.Where(c => !string.IsNullOrEmpty(c.PCode));
  640. var barData = new List<EChartsBarItem>();
  641. // DateTime dateNow = DateTime.Now;
  642. var min = 0;
  643. // var max = alarms.Select(c => Convert.ToInt32(c.Hour)).Max();
  644. var max = DateTime.Now.Hour;
  645. var groups = alarms.GroupBy(c => new { c.Hour, c.PCode, c.PName });
  646. var hours = groups
  647. .Select(c => c.Key.Hour).Distinct();
  648. for (var i = 0; i < max; i++)
  649. {
  650. var barItemDatas = new List<BarItemData>();
  651. var yearGroups = alarms.Where(c => Convert.ToInt32(c.Hour) == min + i).GroupBy(c => new { c.PCode, c.PName });
  652. var list = new List<MTBFDto>();
  653. if (yearGroups == null || yearGroups.Count() <= 0)
  654. {
  655. var mtbf = new MTBFDto()
  656. {
  657. name = "装片",
  658. code = "DB",
  659. MTBF = 0
  660. };
  661. list.Add(mtbf);
  662. barItemDatas.Add(new BarItemData { Code = mtbf.code, Value = mtbf.MTBF.Value });
  663. list.Add(new MTBFDto
  664. {
  665. name = "焊线",
  666. code = "WB",
  667. MTBF = 0
  668. });
  669. barItemDatas.Add(new BarItemData { Code = "WB", Value = 0 });
  670. }
  671. else
  672. {
  673. foreach (var item in yearGroups)
  674. {
  675. var mtbf = new MTBFDto()
  676. {
  677. name = item.Key.PName,
  678. count = item.Count(),
  679. code = item.Key.PCode,
  680. pcode = item.FirstOrDefault().PCode,
  681. minutes = msts.Where(c => c.PCode == item.Key.PCode && Convert.ToInt32(c.Hour) == min + i).Sum(c =>
  682. {
  683. return (float)(c.TimeSpan == null ? 0 : c.TimeSpan) / 60f;
  684. })
  685. };
  686. mtbf.MTBF = mtbf.minutes / mtbf.count;
  687. list.Add(mtbf);
  688. barItemDatas.Add(new BarItemData { Code = item.Key.PCode, Value = mtbf.MTBF.Value });
  689. }
  690. }
  691. barData.Add(new EChartsBarItem { Title = (min + i).ToString(), Data = barItemDatas });
  692. }
  693. var bar = new EChartsBar();
  694. bar.Legend = alarms.Select(c => c.PCode).Distinct().ToArray();
  695. bar.Sources = barData;
  696. return bar;
  697. }
  698. private string CreateMachineMTBASql(string filter, string subFilter, string eventCode, DateType dateType)
  699. {
  700. string sql = "";
  701. switch (dateType)
  702. {
  703. case DateType.Year:
  704. sql = $@"select t.date,t.count,t.timelen,t.mcacode from
  705. (select year(a.starttime) as date,count(1) as count,sum(timespan) timelen,mcacode
  706. from mcaeventstatisticbyday a
  707. where EventCode='{eventCode}' {filter}
  708. group by year(a.starttime),mcacode) t
  709. left join machine b on t.mcacode=b.Fcode
  710. where 1=1 {subFilter}";
  711. break;
  712. case DateType.Month:
  713. sql = $@"select t.date,t.count,t.timelen,t.mcacode from
  714. (select concat_ws('-',year(a.starttime),month(a.starttime)) as date,count(1) as count,sum(timespan) timelen,mcacode
  715. from mcaeventstatisticbyday a
  716. where EventCode='{eventCode}' {filter}
  717. group by concat_ws('-',year(a.starttime),month(a.starttime)),mcacode) t
  718. left join machine b on t.mcacode=b.Fcode
  719. where 1=1 {subFilter}";
  720. break;
  721. case DateType.Day:
  722. sql = $@"select t.date,t.count,t.timelen,t.mcacode from
  723. (select concat_ws('-',year(a.starttime),month(a.starttime),day(a.starttime)) as date,count(1) as count,sum(timespan) timelen,mcacode
  724. from mcaeventstatisticbyday a
  725. where EventCode='{eventCode}' {filter}
  726. group by concat_ws('-',year(a.starttime),month(a.starttime),day(a.starttime)),mcacode) t
  727. left join machine b on t.mcacode=b.Fcode
  728. where 1=1 {subFilter}";
  729. break;
  730. }
  731. return sql;
  732. }
  733. private string CreateMacModelMTBASql(string filter, string subFilter, string eventCode, DateType dateType)
  734. {
  735. string sql = "";
  736. switch (dateType)
  737. {
  738. case DateType.Year:
  739. sql = $@"select t.date,sum(t.count) count,sum(t.timelen) timelen,c.fcode macmodel from
  740. (select year(a.starttime) as date,count(1) as count,sum(timespan) timelen,mcacode
  741. from mcaeventstatisticbyday a
  742. where eventCode='{eventCode}' {filter}
  743. group by year(a.starttime),mcacode) t
  744. left join machine b on t.mcacode=b.Fcode
  745. left join macmodel c on b.mmodeid=c.id
  746. where 1=1 {subFilter}
  747. group by t.date,c.fcode";
  748. break;
  749. case DateType.Month:
  750. sql = $@"select t.date,sum(t.count) count,sum(t.timelen) timelen,c.fcode macmodel from
  751. (select concat_ws('-',year(a.starttime),month(a.starttime)) as date,count(1) as count,sum(timespan) timelen,mcacode
  752. from mcaeventstatisticbyday a
  753. where EventCode='{eventCode}' {filter}
  754. group by concat_ws('-',year(a.starttime),month(a.starttime)),mcacode) t
  755. left join machine b on t.mcacode=b.Fcode
  756. left join macmodel c on b.mmodeid=c.id
  757. where 1=1 {subFilter}
  758. group by t.date,c.fcode";
  759. break;
  760. case DateType.Day:
  761. sql = $@"select t.date,sum(t.count) count,sum(t.timelen) timelen,c.fcode macmodel from
  762. (select concat_ws('-',year(a.starttime),month(a.starttime),day(a.starttime)) as date,count(1) as count,sum(timespan) timelen,mcacode
  763. from mcaeventstatisticbyday a
  764. where EventCode='{eventCode}' {filter}
  765. group by concat_ws('-',year(a.starttime),month(a.starttime),day(a.starttime)),mcacode) t
  766. left join machine b on t.mcacode=b.Fcode
  767. left join macmodel c on b.mmodeid=c.id
  768. where 1=1 {subFilter}
  769. group by t.date,c.fcode";
  770. break;
  771. }
  772. return sql;
  773. }
  774. private string CreatePCodeMTBASql(string filter, string subFilter, string eventCode, DateType dateType)
  775. {
  776. string sql = "";
  777. switch (dateType)
  778. {
  779. case DateType.Year:
  780. sql = $@"select t.date,sum(t.count) count,sum(t.timelen) timelen,c.pcode Pcode,d.FName pname from
  781. (select year(a.starttime) as date,count(1) as count,sum(timespan) timelen,mcacode
  782. from mcaeventstatisticbyday a
  783. where EventCode='{eventCode}' {filter}
  784. group by year(a.starttime),mcacode) t
  785. left join machine b on t.mcacode=b.Fcode
  786. left join mactprocess c on b.id=c.macid
  787. left join tprocess d on c.pcode=d.fcode
  788. where 1=1 {subFilter}
  789. group by t.date,c.pcode,d.FName";
  790. break;
  791. case DateType.Month:
  792. sql = $@"select t.date,sum(t.count) count,sum(t.timelen) timelen,c.pcode Pcode,d.FName pname from
  793. (select concat_ws('-',year(a.starttime),month(a.starttime)) as date,count(1) as count,sum(timespan) timelen,mcacode
  794. from mcaeventstatisticbyday a
  795. where EventCode='{eventCode}' {filter}
  796. group by concat_ws('-',year(a.starttime),month(a.starttime)),mcacode) t
  797. left join machine b on t.mcacode=b.Fcode
  798. left join mactprocess c on b.id=c.macid
  799. left join tprocess d on c.pcode=d.fcode
  800. where 1=1 {subFilter}
  801. group by t.date,c.pcode,d.FName";
  802. break;
  803. case DateType.Day:
  804. sql = $@"select t.date,sum(t.count) count,sum(t.timelen) timelen,c.pcode Pcode,d.FName pname from
  805. (select concat_ws('-',year(a.starttime),month(a.starttime),day(a.starttime)) as date,count(1) as count,sum(timespan) timelen,mcacode
  806. from mcaeventstatisticbyday a
  807. where EventCode='{eventCode}' {filter}
  808. group by concat_ws('-',year(a.starttime),month(a.starttime),day(a.starttime)),mcacode) t
  809. left join machine b on t.mcacode=b.Fcode
  810. left join mactprocess c on b.id=c.macid
  811. left join tprocess d on c.pcode=d.fcode
  812. where 1=1 {subFilter}
  813. group by t.date,c.pcode,d.FName";
  814. break;
  815. }
  816. return sql;
  817. }
  818. public EChartsBar GetBarsForMachine(string filter, string subFilter, DateType dateType)
  819. {
  820. var barData = new List<EChartsBarItem>();
  821. string[] legends = null;
  822. var alarms = CurrDb.FindList<MTBFFromDb>(CreateMachineMTBASql(filter, subFilter, StandardCode.CEID_AlarmOccurred, dateType));
  823. var runs = CurrDb.FindList<MTBFFromDb>(CreateMachineMTBASql(filter, subFilter, StandardCode.CEID_Run, dateType));
  824. var list = new List<MTBFDto>();
  825. IList<BarItemData> barItemDatas = null;
  826. var dateGroups = runs.GroupBy(c => c.Date).OrderBy(c => c.Key.Length).ThenBy(c => c.Key);
  827. foreach (var dateItem in dateGroups)
  828. {
  829. barItemDatas = new List<BarItemData>();
  830. foreach (var item in dateItem)
  831. {
  832. var count = 0;
  833. var currAlarms = alarms.Where(c => c.McaCode == item.McaCode && c.Date == item.Date);
  834. if (currAlarms == null || currAlarms.Count() <= 0)
  835. {
  836. count = 1;
  837. }
  838. else
  839. {
  840. count = currAlarms.Sum(c => c.Count);
  841. }
  842. var mtbf = new MTBFDto()
  843. {
  844. name = item.McaCode,
  845. count = count,
  846. code = item.McaCode,
  847. pcode = item.PCode,
  848. minutes = item.TimeLen / 60f
  849. };
  850. mtbf.MTBF = mtbf.minutes / (mtbf.count == 0 ? 1 : mtbf.count);
  851. list.Add(mtbf);
  852. barItemDatas.Add(new BarItemData { Code = item.McaCode, Value = mtbf.MTBF.Value });
  853. }
  854. barData.Add(new EChartsBarItem { Title = dateItem.Key, Data = barItemDatas });
  855. }
  856. legends = runs.Select(c => c.McaCode).Distinct().ToArray();
  857. var bar = new EChartsBar();
  858. bar.Legend = legends;
  859. bar.Sources = barData;
  860. return bar;
  861. }
  862. public EChartsBar GetBarsForMacModel(string filter, string subFilter, DateType dateType)
  863. {
  864. var barData = new List<EChartsBarItem>();
  865. string[] legends = null;
  866. var alarms = CurrDb.FindList<MTBFFromDb>(CreateMacModelMTBASql(filter, subFilter, StandardCode.CEID_AlarmOccurred, dateType));
  867. var runs = CurrDb.FindList<MTBFFromDb>(CreateMacModelMTBASql(filter, subFilter, StandardCode.CEID_Run, dateType));
  868. var list = new List<MTBFDto>();
  869. IList<BarItemData> barItemDatas = null;
  870. var dateGroups = runs.GroupBy(c => c.Date).OrderBy(c => c.Key.Length).ThenBy(c => c.Key); ;
  871. foreach (var dateItem in dateGroups)
  872. {
  873. barItemDatas = new List<BarItemData>();
  874. foreach (var item in dateItem)
  875. {
  876. var count = 0;
  877. var currAlarms = alarms.Where(c => c.MacModel == item.MacModel && c.Date == item.Date);
  878. if (currAlarms == null || currAlarms.Count() <= 0)
  879. {
  880. count = 1;
  881. }
  882. else
  883. {
  884. count = currAlarms.Sum(c => c.Count);
  885. }
  886. var mtbf = new MTBFDto()
  887. {
  888. name = item.MacModel,
  889. count = count,
  890. code = item.MacModel,
  891. pcode = item.PCode,
  892. minutes = item.TimeLen / 60f
  893. };
  894. mtbf.MTBF = mtbf.minutes / (mtbf.count == 0 ? 1 : mtbf.count);
  895. list.Add(mtbf);
  896. barItemDatas.Add(new BarItemData { Code = item.MacModel, Value = mtbf.MTBF.Value });
  897. }
  898. barData.Add(new EChartsBarItem { Title = dateItem.Key, Data = barItemDatas });
  899. }
  900. legends = runs.Select(c => c.MacModel).Distinct().ToArray();
  901. var bar = new EChartsBar();
  902. bar.Legend = legends;
  903. bar.Sources = barData;
  904. return bar;
  905. }
  906. public EChartsBar GetBarsForProcess(string filter, string subFilter, DateType dateType)
  907. {
  908. var barData = new List<EChartsBarItem>();
  909. string[] legends = null;
  910. var alarms = CurrDb.FindList<MTBFFromDb>(CreatePCodeMTBASql(filter, subFilter, StandardCode.CEID_AlarmOccurred, dateType));
  911. var runs = CurrDb.FindList<MTBFFromDb>(CreatePCodeMTBASql(filter, subFilter, StandardCode.CEID_Run, dateType));
  912. var list = new List<MTBFDto>();
  913. IList<BarItemData> barItemDatas = null;
  914. var dateGroups = runs.GroupBy(c => c.Date).OrderBy(c => c.Key.Length).ThenBy(c => c.Key); ;
  915. foreach (var dateItem in dateGroups)
  916. {
  917. barItemDatas = new List<BarItemData>();
  918. foreach (var item in dateItem)
  919. {
  920. var count = 0;
  921. var currAlarms = alarms.Where(c => c.PCode == item.PCode && c.Date == item.Date);
  922. if (currAlarms == null || currAlarms.Count() <= 0)
  923. {
  924. count = 1;
  925. }
  926. else
  927. {
  928. count = currAlarms.Sum(c => c.Count);
  929. }
  930. var mtbf = new MTBFDto()
  931. {
  932. name = item.PCode,
  933. count = count,
  934. code = item.PCode,
  935. pcode = item.PCode,
  936. minutes = item.TimeLen / 60f
  937. };
  938. mtbf.MTBF = mtbf.minutes / (mtbf.count == 0 ? 1 : mtbf.count);
  939. list.Add(mtbf);
  940. barItemDatas.Add(new BarItemData { Code = item.PCode, Value = mtbf.MTBF.Value });
  941. }
  942. barData.Add(new EChartsBarItem { Title = dateItem.Key, Data = barItemDatas });
  943. }
  944. legends = runs.Select(c => c.PCode).Distinct().ToArray();
  945. var bar = new EChartsBar();
  946. bar.Legend = legends;
  947. bar.Sources = barData;
  948. return bar;
  949. }
  950. /// <summary>
  951. /// 组装返回客户端的最终数据
  952. /// </summary>
  953. /// <param name="filter"></param>
  954. /// <param name="type"></param>
  955. /// <returns></returns>
  956. public LineDateDto GetAlarmTimeDtos(string filter, string subFilter, string type)
  957. {
  958. var dtos = GetDatasFromDb(filter, subFilter, type);
  959. if (dtos == null || dtos.Count() == 0)
  960. return null;
  961. var dateStart = dtos.Min(c => c.Time); //统计开始时间
  962. var dateEnd = dtos.Max(c => c.Time); //统计结束时间
  963. TimeSpan timeSpan = dateEnd - dateStart;
  964. var days = (int)Math.Ceiling(timeSpan.TotalDays);
  965. var groups = dtos.GroupBy(c => c.Name);
  966. var series = new List<LineSeries>();
  967. if (groups != null && groups.Count() > 0)
  968. {
  969. foreach (var item in groups)
  970. {
  971. var temps = dtos.Where(c => c.Name == item.Key).ToList();
  972. for (var i = 0; i <= days; i++)
  973. {
  974. if (temps.FirstOrDefault(c => c.Time == dateStart.AddDays(i)) == null)
  975. {
  976. temps.Add(new AlarmTimeDto()
  977. {
  978. Name = item.Key,
  979. Count = 0,
  980. Time = dateStart.AddDays(i)
  981. });
  982. }
  983. }
  984. series.Add(new LineSeries()
  985. {
  986. Name = item.Key,
  987. AlarmTimeDtos = temps.OrderBy(c => c.Time)
  988. });
  989. }
  990. }
  991. var dates = new List<DateTime>();
  992. for (var j = 0; j <= days; j++)
  993. {
  994. dates.Add(dateStart.AddDays(j));
  995. }
  996. var lineDateDto = new LineDateDto()
  997. {
  998. LineSeries = series,
  999. Dates = dates
  1000. };
  1001. return lineDateDto;
  1002. }
  1003. public LineDateDtoForDisplay GetAlarmTimeDtosForScreenDisplay(string filter)
  1004. {
  1005. var sql = "select c.PCode as name,SUM(1) as count,SUBSTRING(CONVERT(varchar(50),StartTime,24),0,3) time from McaEventStatisticByDay a " +
  1006. "left join machine b on a.mcacode=b.Fcode " +
  1007. "left join mactprocess c on b.id=c.macid "
  1008. + "where 1=1 and b.isanalysis<>-1 "
  1009. + $" {filter} "
  1010. + "group by c.PCode,SUBSTRING(CONVERT(varchar(50), StartTime, 24), 0, 3) order by c.PCode,SUBSTRING(CONVERT(varchar(50), StartTime, 24), 0, 3)";
  1011. var dtos = CurrDb.FindList<AlarmTimeDtoForScreenDisplay>(sql);
  1012. if (dtos == null || dtos.Count() == 0)
  1013. return null;
  1014. var dateStart = dtos.Select(c => Convert.ToInt32(c.Time)).Min(c => c); //统计开始时间
  1015. var dateEnd = dtos.Select(c => Convert.ToInt32(c.Time)).Max(c => c); //统计结束时间
  1016. int timeSpan = dateEnd - dateStart;
  1017. var hours = timeSpan;
  1018. var groups = dtos.GroupBy(c => c.Name);
  1019. var series = new List<LineSeriesForDisplay>();
  1020. if (groups != null && groups.Count() > 0)
  1021. {
  1022. foreach (var item in groups)
  1023. {
  1024. var temps = dtos.Where(c => c.Name == item.Key).ToList();
  1025. for (var i = 0; i <= hours; i++)
  1026. {
  1027. if (temps.FirstOrDefault(c => Convert.ToInt32(c.Time) == (dateStart + i)) == null)
  1028. {
  1029. temps.Add(new AlarmTimeDtoForScreenDisplay()
  1030. {
  1031. Name = item.Key,
  1032. Count = 0,
  1033. Time = (dateStart + i).ToString()
  1034. });
  1035. }
  1036. }
  1037. series.Add(new LineSeriesForDisplay()
  1038. {
  1039. Name = item.Key,
  1040. AlarmTimeDtos = temps.OrderBy(c => c.Time)
  1041. });
  1042. }
  1043. }
  1044. var dates = new List<string>();
  1045. for (var j = 0; j <= hours; j++)
  1046. {
  1047. dates.Add((dateStart + j).ToString());
  1048. }
  1049. var lineDateDto = new LineDateDtoForDisplay()
  1050. {
  1051. LineSeries = series,
  1052. Dates = dates
  1053. };
  1054. return lineDateDto;
  1055. }
  1056. /// <summary>
  1057. /// 从数据库中读取原始统计数据
  1058. /// </summary>
  1059. /// <param name="filter"></param>
  1060. /// <param name="type"></param>
  1061. /// <returns></returns>
  1062. private IEnumerable<AlarmTimeDto> GetDatasFromDb(string filter, string subFilter, string type)
  1063. {
  1064. string sql = string.Empty;
  1065. switch (type)
  1066. {
  1067. case "machine":
  1068. sql = $@"select t.name,t.count,t.time from
  1069. (select a.mcacode as name,SUM(1) as count,substring(DATE_FORMAT(a.StartTime,'%Y-%m-%d'),1,11) time
  1070. from McaEventStatisticByDay a
  1071. where 1=1 {filter}
  1072. group by a.mcaCode,substring(DATE_FORMAT(a.StartTime,'%Y-%m-%d'),1,11)) t
  1073. left join machine b on t.name=b.FCode
  1074. where 1=1 and b.isanalysis<>-1 {subFilter}
  1075. order by t.name,t.time ";
  1076. break;
  1077. case "macmodel":
  1078. sql = $@"select c.FCode name,sum(t.count) as count,t.time from (
  1079. select a.mcacode,SUM(1) as count,substring(DATE_FORMAT(a.StartTime,'%Y-%m-%d'),1,11) time
  1080. from McaEventStatisticByDay a
  1081. where 1=1 {filter}
  1082. group by a.mcacode,substring(DATE_FORMAT(a.StartTime,'%Y-%m-%d'),1,11)
  1083. ) t
  1084. left join Machine b on t.mcacode=b.FCode
  1085. left join MacModel c on b.MModeId=c.id
  1086. where b.isanalysis<>-1 {subFilter}
  1087. group by c.FCode,t.time
  1088. order by name,time";
  1089. break;
  1090. case "process":
  1091. sql = $@"select c.pcode name,sum(t.count) as count,t.time from (
  1092. select a.mcacode,SUM(1) as count,substring(DATE_FORMAT(a.StartTime,'%Y-%m-%d'),1,11) time
  1093. from McaEventStatisticByDay a
  1094. where 1=1 {filter}
  1095. group by a.mcacode,substring(DATE_FORMAT(a.StartTime,'%Y-%m-%d'),1,11)
  1096. ) t
  1097. left join Machine b on t.mcacode=b.FCode
  1098. left join mactprocess c on b.id=c.macid
  1099. where 1=1 and b.isanalysis<>-1 {subFilter}
  1100. group by c.pcode,t.time
  1101. order by c.pcode,time";
  1102. break;
  1103. }
  1104. IEnumerable<AlarmTimeDto> dtos = CurrDb.FindList<AlarmTimeDto>(sql); ;
  1105. return dtos;
  1106. }
  1107. /// <summary>
  1108. /// 获取数据库中所有的机台的运行开始结束时间
  1109. /// </summary>
  1110. /// <param name="filter"></param>
  1111. /// <returns></returns>
  1112. public IEnumerable<McaEventStatisticByDay> GetEffiencyEntities(string filter, string subFilter)
  1113. {
  1114. var mcaEvents = this.GetStatisticDetails($"and EventCode='{DllHsms.StandardCode.CEID_Run}' {filter}", subFilter);
  1115. return mcaEvents;
  1116. }
  1117. public IEnumerable<McaEventStatisticByDay> GetAlarms(string filter, string subFilter)
  1118. {
  1119. var alarms = this.GetStatisticDetails($"and EventCode='{DllHsms.StandardCode.CEID_AlarmOccurred}' {filter}", subFilter);
  1120. return alarms;
  1121. }
  1122. public IEnumerable<StatusCountDto> GetStatusCounts(DateTime? dateStart, DateTime? dateEnd)
  1123. {
  1124. var filter = $" and a.etime>='{dateStart}' and a.etime<='{dateEnd}'";
  1125. string sql = $"select a.maccode,c.fcode as macmodel,d.pcode,count(1) as count1 from macstatus a " +
  1126. $"left join machine b on a.maccode=b.fcode " +
  1127. $" left join macmodel c on b.mmodeid=c.id " +
  1128. $" left join mactprocess d on b.id=d.macid where 1=1 {filter} and b.isanalysis<>-1 " +
  1129. $"and statusid<>'{MacStatusVal.Run}' group by maccode,c.fcode,d.pcode";
  1130. var stopDtos = CurrDb.FindList<StatusCountDto>(sql);
  1131. return stopDtos;
  1132. }
  1133. /// <summary>
  1134. /// 生成获取效率基础信息的SQL语句
  1135. /// </summary>
  1136. /// <param name="type"></param>
  1137. /// <param name="filter"></param>
  1138. /// <param name="subFilter"></param>
  1139. /// <returns></returns>
  1140. private string CreateEnffiencySql(string type, string filter, string subFilter, string macModel, string pCode)
  1141. {
  1142. string sql = string.Empty;
  1143. if (!string.IsNullOrEmpty(macModel) && macModel != "null")
  1144. {
  1145. subFilter += $" and e.fcode='{macModel}'";
  1146. }
  1147. if (!string.IsNullOrEmpty(pCode) && pCode != "null")
  1148. {
  1149. subFilter += $" and d.fcode='{pCode}'";
  1150. }
  1151. switch (type)
  1152. {
  1153. case "pcode":
  1154. sql = $@"select count(1) count,sum(tt.timelength),c.pcode,tt.eventcode from (select sum(timespan) as timelength,mcacode,eventCode eventCode
  1155. from mcaeventstatisticbyday a
  1156. where 1=1 {filter}
  1157. group by mcacode,eventCode
  1158. )tt
  1159. left join Machine b on tt.McaCode=b.FCode
  1160. left join MacTProcess c on b.id=c.MacID
  1161. left join TProcess d on c.PCode=d.FCode
  1162. left join MacModel e on b.MModeId=e.id
  1163. left join Supplier f on e.SupplierId=f.id
  1164. left join FactoryRegion g on b.FactoryId=g.id
  1165. where 1=1 and b.isanalysis<>-1 and c.pcode is not null {subFilter}
  1166. group by c.pcode,tt.EventCode";
  1167. break;
  1168. case "macmodel":
  1169. sql = $@"select count(1) count,sum(tt.timelength),c.pcode,e.fCode macmodel,tt.eventcode from (select sum(timespan) as timelength,mcacode,eventCode eventCode
  1170. from mcaeventstatisticbyday a
  1171. where 1=1 {filter}
  1172. group by mcacode,eventCode
  1173. )tt
  1174. left join Machine b on tt.McaCode=b.FCode
  1175. left join MacTProcess c on b.id=c.MacID
  1176. left join TProcess d on c.PCode=d.FCode
  1177. left join MacModel e on b.MModeId=e.id
  1178. left join Supplier f on e.SupplierId=f.id
  1179. left join FactoryRegion g on b.FactoryId=g.id
  1180. where 1=1 and b.isanalysis<>-1 and c.pcode is not null {subFilter}
  1181. group by c.pcode,tt.EventCode,e.fcode";
  1182. break;
  1183. case "machine":
  1184. sql = $@"select sum(tt.timelength) timeLength,c.pcode,e.fCode macmodel,mcacode,tt.eventcode from (select sum(timespan) as timelength,mcacode,eventCode eventCode
  1185. from mcaeventstatisticbyday a
  1186. where 1=1 {filter}
  1187. group by mcacode,eventCode
  1188. )tt
  1189. left join Machine b on tt.McaCode=b.FCode
  1190. left join MacTProcess c on b.id=c.MacID
  1191. left join TProcess d on c.PCode=d.FCode
  1192. left join MacModel e on b.MModeId=e.id
  1193. left join Supplier f on e.SupplierId=f.id
  1194. left join FactoryRegion g on b.FactoryId=g.id
  1195. where 1=1 and b.isanalysis<>-1 and c.pcode is not null {subFilter}
  1196. group by c.pcode,tt.EventCode,e.fcode,tt.mcacode";
  1197. break;
  1198. }
  1199. return sql;
  1200. }
  1201. private string CreateEnffiencyMachineSql(string filter, string subFilter, int start, int pageSize, string sortField, string sortOrder, double se)
  1202. {
  1203. string sql = string.Empty;
  1204. sql = $@"SELECT
  1205. FactoryName,
  1206. FloorName,
  1207. PlantName,
  1208. PCode,
  1209. modelName,
  1210. MacCode,
  1211. macnumber,
  1212. SUM( runTime ) runTime,
  1213. SUM( idleTime ) idleTime,
  1214. SUM( errorTime ) errorTime,
  1215. SUM( allTime ) allTime,
  1216. ROUND(SUM( runTime )/SUM( allTime )* 100, 1 ) runrRate,
  1217. ROUND(SUM( idleTime )/SUM( allTime )* 100, 1 ) idleRate,
  1218. ROUND( sum( errorTime) / SUM( allTime ) * 100, 1 ) errorRate,
  1219. IFNULL( ROUND( (sum( CASE WHEN faulttype=1 THEN errorTime WHEN faulttype='' THEN errorTime WHEN faulttype IS NULL THEN errorTime ELSE 0 END ) ) / SUM( allTime ) * 100, 1 ), 0 ) errorRateOne,
  1220. IFNULL( ROUND( (sum( CASE faulttype WHEN 2 THEN errorTime ELSE 0 END ) ) / SUM( allTime ) * 100, 1 ), 0 ) errorRateTwo,
  1221. sum( CASE WHEN faulttype=1 THEN errorTime WHEN faulttype='' THEN errorTime WHEN faulttype IS NULL THEN errorTime ELSE 0 END ) errorTimeOne,
  1222. sum( CASE faulttype WHEN 2 THEN errorTime ELSE 0 END ) errorTimeTwo
  1223. FROM
  1224. (
  1225. SELECT
  1226. p.faulttype,
  1227. i.FName FactoryName,
  1228. k.FName FloorName,
  1229. l.Fname PlantName,
  1230. f.PCode,
  1231. d.FName modelName,
  1232. a.FCode MacCode,
  1233. machinenumber.macnumber macnumber,
  1234. tt.AlarmCode,
  1235. IFNULL( ROUND( tt.RUN / 60 / {se} * 100, 1 ), 0 ) runrRate,
  1236. IFNULL( ROUND( tt.IDLE / 60 / {se} * 100, 1 ), 0 ) idleRate,
  1237. IFNULL( ROUND( tt.ERROR / 60 / {se} * 100, 1 ), 0 ) errorRate,
  1238. IFNULL( ROUND( tt.ERROR / 60 + tt.IDLE / 60 + tt.RUN/60 ), 0 ) allTime,
  1239. IFNULL( ROUND( tt.RUN / 60 ), 0 ) runTime,
  1240. IFNULL( ROUND( tt.IDLE / 60 ), 0 ) idleTime,
  1241. IFNULL( ROUND( tt.ERROR / 60 ), 0 ) errorTime
  1242. FROM
  1243. Machine a
  1244. LEFT JOIN (
  1245. SELECT
  1246. a.MacCode,
  1247. AlarmCode,
  1248. sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1249. sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1250. sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1251. FROM
  1252. macstatus a
  1253. WHERE
  1254. StatusID IN ( 3, 4, 6 )
  1255. {filter}
  1256. GROUP BY
  1257. a.MacCode,
  1258. a.AlarmCode
  1259. ) tt ON tt.MacCode = a.FCode
  1260. LEFT OUTER JOIN macstatus01 m ON a.fcode = m.maccode
  1261. LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1262. LEFT JOIN mtbacode p ON p.MModeID = d.id
  1263. AND p.AlarmCode = tt.AlarmCode
  1264. LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1265. LEFT OUTER JOIN tprocess g ON f.PCode = g.FCode
  1266. LEFT OUTER JOIN factoryregion i ON a.factoryid = i.id
  1267. LEFT OUTER JOIN factoryregion j ON a.regionid = j.id
  1268. LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1269. LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1270. left join machinenumber on a.id=machinenumber.macid
  1271. WHERE
  1272. 1 = 1 {subFilter}
  1273. -- AND a.FCode = 'AA00041'
  1274. ORDER BY
  1275. tt.MacCode
  1276. ) hh
  1277. GROUP BY
  1278. FactoryName,
  1279. FloorName,
  1280. PlantName,
  1281. PCode,
  1282. modelName,
  1283. MacCode,
  1284. macnumber
  1285. ORDER BY MacCode
  1286. LIMIT {start - 1},{pageSize}";
  1287. #region 原始
  1288. //sql = $@"SELECT
  1289. // i.FName FactoryName,
  1290. // k.FName FloorName,
  1291. // l.Fname PlantName,
  1292. // f.PCode,
  1293. // d.FName modelName,
  1294. // a.FCode MacCode,
  1295. // IFNULL(ROUND(tt.RUN /60/ {se}*100,1),0) runrRate,
  1296. // IFNULL(ROUND(tt.IDLE /60/ {se}*100,1),0) idleRate,
  1297. // IFNULL(ROUND(tt.ERROR /60/ {se}*100,1),0) errorRate,
  1298. // IFNULL(ROUND(tt.ERROR/ 60 + tt.IDLE/ 60 + tt.RUN),0) allTime,
  1299. // IFNULL(ROUND(tt.RUN/ 60),0) runTime,
  1300. // IFNULL(ROUND(tt.IDLE/ 60),0) idleTime
  1301. // FROM Machine a
  1302. // LEFT JOIN (
  1303. // SELECT
  1304. // a.MacCode,
  1305. // sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1306. // sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1307. // sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1308. // FROM
  1309. // macstatus a
  1310. // WHERE
  1311. // StatusID in(3,4,6)
  1312. // {filter}
  1313. // GROUP BY
  1314. // a.MacCode
  1315. // ) tt
  1316. // ON tt.MacCode = a.FCode
  1317. // LEFT OUTER JOIN macstatus01 m ON a.fcode = m.maccode
  1318. // LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1319. // LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1320. // LEFT OUTER JOIN tprocess g ON f.PCode = g.FCode
  1321. // LEFT OUTER JOIN factoryregion i ON a.factoryid = i.id
  1322. // LEFT OUTER JOIN factoryregion j ON a.regionid = j.id
  1323. // LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1324. // LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1325. // where 1=1 {subFilter}
  1326. // ORDER BY tt.MacCode
  1327. // LIMIT {start - 1},{pageSize} ";
  1328. #endregion
  1329. return sql;
  1330. }
  1331. private string CreateEnffiencyMachineTotalSql(string filter, string subFilter, int start, int pageSize, string sortField, string sortOrder, double se)
  1332. {
  1333. string sql = string.Empty;
  1334. sql = $@"SELECT
  1335. ROUND(sum(tt.RUN) /60/ (sum(tt.errorTime)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60) *100,1) runrRate,
  1336. ROUND(sum(tt.IDLE) /60/ (sum(tt.errorTime)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60) *100,1) idleRate,
  1337. ROUND(sum(tt.errorTime) /60/ (sum(tt.errorTime)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60)*100,1) errorRate,
  1338. ROUND(sum(tt.errorTime)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60) allTime,
  1339. ROUND(sum(tt.RUN)/ 60) runTime,
  1340. ROUND(sum(tt.IDLE)/ 60) idleTime,
  1341. ROUND(SUM( errorTime/60 )) errorTime,
  1342. IFNULL( ROUND( (sum( CASE WHEN faulttype=1 THEN errorTime WHEN faulttype='' THEN errorTime WHEN faulttype IS NULL THEN errorTime ELSE 0 END ) )/60 / (sum(tt.errorTime)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60) * 100, 1 ), 0 ) errorRateOne,
  1343. IFNULL( ROUND( (sum( CASE faulttype WHEN 2 THEN errorTime ELSE 0 END ) )/60 / (sum(tt.errorTime)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60) * 100, 1 ), 0 ) errorRateTwo,
  1344. ROUND(sum( CASE WHEN faulttype=1 THEN errorTime WHEN faulttype='' THEN errorTime WHEN faulttype IS NULL THEN errorTime ELSE 0 END )/60) errorTimeOne,
  1345. ROUND(sum( CASE faulttype WHEN 2 THEN errorTime ELSE 0 END )/60) errorTimeTwo
  1346. FROM Machine a
  1347. LEFT OUTER JOIN (
  1348. SELECT
  1349. a.MacCode,
  1350. AlarmCode,
  1351. sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1352. sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1353. sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) errorTime
  1354. FROM
  1355. macstatus a
  1356. WHERE
  1357. StatusID in(3,4,6)
  1358. {filter}
  1359. GROUP BY
  1360. a.MacCode ,
  1361. a.AlarmCode
  1362. ) tt ON tt.MacCode = a.FCode
  1363. LEFT OUTER JOIN macstatus01 m ON a.fcode = m.maccode
  1364. LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1365. LEFT JOIN mtbacode p ON p.MModeID = d.id
  1366. AND p.AlarmCode = tt.AlarmCode
  1367. LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1368. LEFT OUTER JOIN tprocess g ON f.PCode = g.FCode
  1369. LEFT OUTER JOIN factoryregion i ON a.factoryid = i.id
  1370. LEFT OUTER JOIN factoryregion j ON a.regionid = j.id
  1371. LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1372. LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1373. left join machinenumber on a.id=machinenumber.macid
  1374. where 1=1 {subFilter} and l.fname not like '%试产%'
  1375. ";
  1376. #region
  1377. // sql = $@"SELECT
  1378. // ROUND(sum(tt.RUN) /60/ {se}*100,1) runrRate,
  1379. // ROUND(sum(tt.IDLE) /60/ {se}*100,1) idleRate,
  1380. // ROUND(sum(tt.ERROR) /60/ {se}*100,1) errorRate,
  1381. // ROUND(sum(tt.ERROR)/ 60 + sum(tt.IDLE)/ 60 + sum(tt.RUN)/60) allTime,
  1382. // ROUND(sum(tt.RUN)/ 60/Count(tt.MacCode)) runTime,
  1383. // ROUND(sum(tt.IDLE)/ 60/Count(tt.MacCode)) idleTime
  1384. // FROM Machine a
  1385. // LEFT OUTER JOIN (
  1386. // SELECT
  1387. // a.MacCode,
  1388. // AlarmCode,
  1389. // sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1390. // sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1391. // sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1392. // FROM
  1393. // macstatus a
  1394. // WHERE
  1395. // StatusID in(3,4,6)
  1396. // {filter}
  1397. // GROUP BY
  1398. // a.MacCode ,
  1399. // a.AlarmCode
  1400. // ) tt ON tt.MacCode = a.FCode
  1401. // LEFT OUTER JOIN macstatus01 m ON a.fcode = m.maccode
  1402. // LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1403. // LEFT JOIN mtbacode p ON p.MModeID = d.id
  1404. //AND p.AlarmCode = tt.AlarmCode
  1405. // LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1406. // LEFT OUTER JOIN tprocess g ON f.PCode = g.FCode
  1407. // LEFT OUTER JOIN factoryregion i ON a.factoryid = i.id
  1408. // LEFT OUTER JOIN factoryregion j ON a.regionid = j.id
  1409. // LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1410. // LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1411. // where 1=1 {subFilter} and l.fname not like '%试产%'
  1412. // ";
  1413. #endregion
  1414. return sql;
  1415. }
  1416. private string CreateEnffiencyFactorySql(string filter, double se)
  1417. {
  1418. string sql = string.Empty;
  1419. sql = $@"select * from
  1420. (
  1421. SELECT
  1422. concat( i.FName,l.FName, k.FName ) FactoryName,
  1423. i.id FactoryID,
  1424. k.id FloorID,
  1425. ROUND( sum( tt.RUN ) / 60 / {se}/count(tt.MacCode) * 100, 1 ) runrRate,
  1426. ROUND( sum( tt.IDLE ) / 60 / {se}/count(tt.MacCode) * 100, 1 ) idleRate,
  1427. ROUND( sum( tt.ERROR ) / 60 / {se}/count(tt.MacCode) * 100, 1 ) errorRate,
  1428. count( aa.FCode) allTime
  1429. FROM
  1430. (
  1431. SELECT
  1432. a.MacCode,
  1433. sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1434. sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1435. sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1436. FROM
  1437. macstatus a
  1438. WHERE
  1439. a.StatusID IN ( 3, 4, 6 )
  1440. {filter}
  1441. GROUP BY
  1442. a.MacCode
  1443. ) tt
  1444. LEFT OUTER JOIN Machine aa ON tt.MacCode = aa.FCode
  1445. LEFT OUTER JOIN factoryregion i ON aa.factoryid = i.id
  1446. LEFT OUTER JOIN factoryregion j ON aa.regionid = j.id
  1447. LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1448. LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1449. GROUP BY
  1450. i.FName,
  1451. i.id,
  1452. k.FName,
  1453. l.FName,
  1454. k.id) t
  1455. WHERE t.FactoryName is not null";
  1456. return sql;
  1457. }
  1458. private string CreateEnffiencyMachineCountSql(string filter, string subFilter, string sortField, string sortOrder)
  1459. {
  1460. string sql = string.Empty;
  1461. sql = $@"SELECT
  1462. count(*)
  1463. FROM
  1464. (
  1465. SELECT
  1466. FCode
  1467. FROM
  1468. (
  1469. SELECT
  1470. a.FCode
  1471. FROM Machine a
  1472. LEFT OUTER JOIN (
  1473. SELECT
  1474. a.MacCode,AlarmCode,
  1475. sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1476. sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1477. sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1478. FROM
  1479. macstatus a
  1480. WHERE
  1481. StatusID in(3,4,6)
  1482. {filter}
  1483. GROUP BY
  1484. a.MacCode ,a.AlarmCode
  1485. ) tt
  1486. ON tt.MacCode = a.FCode
  1487. LEFT OUTER JOIN macstatus01 m on a.FCode=m.MacCode
  1488. LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1489. LEFT JOIN mtbacode p ON p.MModeID = d.id
  1490. AND p.AlarmCode = tt.AlarmCode
  1491. LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1492. LEFT OUTER JOIN tprocess g ON f.PCode = g.FCode
  1493. LEFT OUTER JOIN factoryregion i ON a.factoryid = i.id
  1494. LEFT OUTER JOIN factoryregion j ON a.regionid = j.id
  1495. LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1496. LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1497. left join machinenumber on a.id=machinenumber.macid
  1498. where 1=1 {subFilter}
  1499. ORDER BY tt.MacCode
  1500. ) t
  1501. GROUP BY
  1502. FCode
  1503. ) l";
  1504. return sql;
  1505. }
  1506. private string CreateEnffiencyMachineSqlExport(string filter, string subFilter, string sortField, string sortOrder, double se)
  1507. {
  1508. string sql = string.Empty;
  1509. sql = $@"SELECT
  1510. FactoryName,
  1511. FloorName,
  1512. PlantName,
  1513. PCode,
  1514. modelName,
  1515. MacCode,
  1516. SUM( runTime ) runTime,
  1517. SUM( idleTime ) idleTime,
  1518. SUM( errorTime ) errorTime,
  1519. SUM( allTime ) allTime,
  1520. SUM( runrRate ) runrRate,
  1521. SUM( idleRate ) idleRate,
  1522. ROUND( sum( errorTime) / {se} * 100, 1 ) errorRate,
  1523. IFNULL( ROUND( (sum( CASE WHEN faulttype=1 THEN errorTime WHEN faulttype='' THEN errorTime WHEN faulttype IS NULL THEN errorTime ELSE 0 END ) ) / {se} * 100, 1 ), 0 ) errorRateOne,
  1524. IFNULL( ROUND( (sum( CASE faulttype WHEN 2 THEN errorTime ELSE 0 END ) ) / {se} * 100, 1 ), 0 ) errorRateTwo,
  1525. sum( CASE WHEN faulttype=1 THEN errorTime WHEN faulttype='' THEN errorTime WHEN faulttype IS NULL THEN errorTime ELSE 0 END ) errorTimeOne,
  1526. sum( CASE faulttype WHEN 2 THEN errorTime ELSE 0 END ) errorTimeTwo
  1527. FROM
  1528. (
  1529. SELECT
  1530. p.faulttype,
  1531. i.FName FactoryName,
  1532. k.FName FloorName,
  1533. l.Fname PlantName,
  1534. f.PCode,
  1535. d.FName modelName,
  1536. a.FCode MacCode,
  1537. tt.AlarmCode,
  1538. IFNULL( ROUND( tt.RUN / 60 / {se} * 100, 1 ), 0 ) runrRate,
  1539. IFNULL( ROUND( tt.IDLE / 60 / {se} * 100, 1 ), 0 ) idleRate,
  1540. IFNULL( ROUND( tt.ERROR / 60 / {se} * 100, 1 ), 0 ) errorRate,
  1541. IFNULL( ROUND( tt.ERROR / 60 + tt.IDLE / 60 + tt.RUN/60 ), 0 ) allTime,
  1542. IFNULL( ROUND( tt.RUN / 60 ), 0 ) runTime,
  1543. IFNULL( ROUND( tt.IDLE / 60 ), 0 ) idleTime,
  1544. IFNULL( ROUND( tt.ERROR / 60 ), 0 ) errorTime
  1545. FROM
  1546. Machine a
  1547. LEFT JOIN (
  1548. SELECT
  1549. a.MacCode,
  1550. AlarmCode,
  1551. sum( CASE a.StatusID WHEN 3 THEN ifnull( FLen, 0 ) ELSE 0 END ) IDLE,
  1552. sum( CASE a.StatusID WHEN 4 THEN ifnull( FLen, 0 ) ELSE 0 END ) RUN,
  1553. sum( CASE a.StatusID WHEN 6 THEN ifnull( FLen, 0 ) ELSE 0 END ) ERROR
  1554. FROM
  1555. macstatus a
  1556. WHERE
  1557. StatusID IN ( 3, 4, 6 )
  1558. {filter}
  1559. GROUP BY
  1560. a.MacCode,
  1561. a.AlarmCode
  1562. ) tt ON tt.MacCode = a.FCode
  1563. LEFT OUTER JOIN macstatus01 m ON a.fcode = m.maccode
  1564. LEFT OUTER JOIN macmodel d ON a.MModeID = d.id
  1565. LEFT JOIN mtbacode p ON p.MModeID = d.id
  1566. AND p.AlarmCode = tt.AlarmCode
  1567. LEFT OUTER JOIN mactprocess f ON a.id = f.macid
  1568. LEFT OUTER JOIN tprocess g ON f.PCode = g.FCode
  1569. LEFT OUTER JOIN factoryregion i ON a.factoryid = i.id
  1570. LEFT OUTER JOIN factoryregion j ON a.regionid = j.id
  1571. LEFT OUTER JOIN factoryregion k ON j.parentid = k.id
  1572. LEFT OUTER JOIN factoryregion l ON k.parentid = l.id
  1573. WHERE
  1574. 1 = 1 {subFilter}
  1575. ORDER BY
  1576. tt.MacCode
  1577. ) hh
  1578. GROUP BY
  1579. FactoryName,
  1580. FloorName,
  1581. PlantName,
  1582. PCode,
  1583. modelName,
  1584. MacCode
  1585. ORDER BY MacCode";
  1586. return sql;
  1587. }
  1588. public IEnumerable<MachineEfficiency> GetMachineEfficy(string type, string filter, string subFilter, string macmodel, string pcode, int? factoryId, DateTime? dateStart = null, DateTime? dateEnd = null)
  1589. {
  1590. var list = new List<MachineEfficiency>();
  1591. var regionDal = new FactoryRegionDal(CurrDb);
  1592. IEnumerable<MachineEffiencyDto> dtos = CurrDb.FindList<MachineEffiencyDto>(CreateEnffiencySql("machine", filter, subFilter, macmodel, pcode));
  1593. if (dtos == null || dtos.Count() <= 0)
  1594. return null;
  1595. var macFilter = $" and b.isAnalysis=1 ";
  1596. if (factoryId != null && factoryId != 0)
  1597. {
  1598. macFilter += $" and b.factoryId={factoryId}";
  1599. }
  1600. var machines = GetAllMachines(macFilter);
  1601. if (type == "pcode")
  1602. {
  1603. int j = 0;
  1604. var runs = dtos.Where(c => c.EventCode == StandardCode.CEID_Run);
  1605. var alarms = dtos.Where(c => c.EventCode == StandardCode.CEID_AlarmOccurred);
  1606. var gruop = runs.GroupBy(c => c.PCode);
  1607. foreach (var item in gruop)
  1608. {
  1609. var entity = new MachineEfficiency
  1610. {
  1611. Count = machines.Where(c => c.ProcessCode == item.Key).Count(),
  1612. Type = "pcode",
  1613. Index = ++j,
  1614. Name = item.Key,
  1615. Key = item.Key,
  1616. HasChildren = true,
  1617. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  1618. PCode = item.Key
  1619. };
  1620. var runTime = item.Sum(c => c.TimeLength);
  1621. var alarmTime = alarms.Where(c => c.PCode == item.Key)?.Sum(c => c.TimeLength);
  1622. entity.RunTime = runTime / entity.Count;
  1623. entity.RunRate = entity.RunTime / entity.TotalTime; // 稼动率
  1624. entity.AlarmRate = 0;
  1625. entity.AlarmRate = (alarmTime == null ? 0 : alarmTime.Value) / item.Count() / entity.TotalTime; // 故障率
  1626. entity.IdleRate = 1 - entity.RunRate - entity.AlarmRate; // 闲置率
  1627. entity.LossTime = entity.TotalTime - entity.RunTime;
  1628. // var inProducingTime = item.Where(c => c.IsInProducing == 1 && c.EventCode == DllHsms.StandardCode.CEID_Run)?.Sum(c => c.TimeSpan.Value) / count; // 机台中有料的生产时间 //entity.LoadRate = (decimal)inProducingTime / entity.TotalTime; //entity.RDRate = (1 - entity.LoadRate) //为数据显示美观 后期计算方式会变化
  1629. entity.LoadRate = entity.RunRate + entity.AlarmRate;
  1630. entity.RDRate = 1 - entity.LoadRate;
  1631. list.Add(entity);
  1632. }
  1633. }
  1634. else if (type == "macmodel")
  1635. {
  1636. int j = 0;
  1637. var runs = dtos.Where(c => c.EventCode == StandardCode.CEID_Run);
  1638. var alarms = dtos.Where(c => c.EventCode == StandardCode.CEID_AlarmOccurred);
  1639. var gruop = runs.GroupBy(c => c.MacModel);
  1640. foreach (var item in gruop)
  1641. {
  1642. var entity = new MachineEfficiency
  1643. {
  1644. Count = machines.Where(c => c.ProcessCode == pcode && c.MacModel == item.Key).Count(),
  1645. Type = "macmodel",
  1646. Index = ++j,
  1647. Name = item.Key,
  1648. Key = item.Key,
  1649. HasChildren = true,
  1650. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  1651. PCode = item.First().PCode
  1652. };
  1653. var runTime = item.Sum(c => c.TimeLength);
  1654. var alarmTime = alarms.Where(c => c.MacModel == item.Key && c.PCode == pcode)?.Sum(c => c.TimeLength);
  1655. entity.RunTime = runTime / entity.Count;
  1656. entity.RunRate = entity.RunTime / entity.TotalTime; // 稼动率
  1657. entity.AlarmRate = 0;
  1658. entity.AlarmRate = (alarmTime == null ? 0 : alarmTime.Value) / item.Count() / entity.TotalTime; // 故障率
  1659. entity.IdleRate = 1 - entity.RunRate - entity.AlarmRate; // 闲置率
  1660. entity.LossTime = entity.TotalTime - entity.RunTime;
  1661. // var inProducingTime = item.Where(c => c.IsInProducing == 1 && c.EventCode == DllHsms.StandardCode.CEID_Run)?.Sum(c => c.TimeSpan.Value) / count; // 机台中有料的生产时间 //entity.LoadRate = (decimal)inProducingTime / entity.TotalTime; //entity.RDRate = (1 - entity.LoadRate) //为数据显示美观 后期计算方式会变化
  1662. entity.LoadRate = entity.RunRate + entity.AlarmRate;
  1663. entity.RDRate = 1 - entity.LoadRate;
  1664. list.Add(entity);
  1665. }
  1666. }
  1667. else
  1668. {
  1669. int j = 0;
  1670. var runs = dtos.Where(c => c.EventCode == StandardCode.CEID_Run);
  1671. var alarms = dtos.Where(c => c.EventCode == StandardCode.CEID_AlarmOccurred);
  1672. var gruop = runs.GroupBy(c => c.McaCode);
  1673. foreach (var item in gruop)
  1674. {
  1675. var mac = machines.FirstOrDefault(c => c.MacCode == item.Key);
  1676. var entity = new MachineEfficiency
  1677. {
  1678. Count = 1,
  1679. Type = "machine",
  1680. Index = ++j,
  1681. Name = item.Key,
  1682. Key = item.Key,
  1683. HasChildren = false,
  1684. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  1685. PCode = item.First().PCode,
  1686. RegionName = mac.RegionName
  1687. };
  1688. var runTime = item.Sum(c => c.TimeLength);
  1689. var alarmTime = alarms.Where(c => c.McaCode == item.Key)?.Sum(c => c.TimeLength);
  1690. entity.RunTime = runTime / entity.Count;
  1691. entity.RunRate = entity.RunTime / entity.TotalTime; // 稼动率
  1692. entity.AlarmRate = 0;
  1693. entity.AlarmRate = (alarmTime == null ? 0 : alarmTime.Value) / item.Count() / entity.TotalTime; // 故障率
  1694. entity.IdleRate = 1 - entity.RunRate - entity.AlarmRate; // 闲置率
  1695. entity.LossTime = entity.TotalTime - entity.RunTime;
  1696. // var inProducingTime = item.Where(c => c.IsInProducing == 1 && c.EventCode == DllHsms.StandardCode.CEID_Run)?.Sum(c => c.TimeSpan.Value) / count; // 机台中有料的生产时间 //entity.LoadRate = (decimal)inProducingTime / entity.TotalTime; //entity.RDRate = (1 - entity.LoadRate) //为数据显示美观 后期计算方式会变化
  1697. entity.LoadRate = entity.RunRate + entity.AlarmRate;
  1698. entity.RDRate = 1 - entity.LoadRate;
  1699. list.Add(entity);
  1700. }
  1701. var disconns = machines.Except(machines.Where(c => gruop.Select(t => t.Key).Contains(c.MacCode)))
  1702. .Where(c => c.PCode == pcode && c.MacModel == macmodel);
  1703. foreach (var d in disconns)
  1704. {
  1705. list.Add(new MachineEfficiency
  1706. {
  1707. Count = 1,
  1708. Type = "machine",
  1709. Index = ++j,
  1710. Name = d.MacCode,
  1711. Key = d.MacCode,
  1712. HasChildren = false,
  1713. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  1714. PCode = d.PCode,
  1715. RegionName = d.RegionName
  1716. });
  1717. }
  1718. list = list.OrderBy(c => c.Key).ToList();
  1719. }
  1720. return list;
  1721. }
  1722. public IEnumerable<MachineEfDto> GetMachineEfficyMachine(string filter, string subFilter, int start, int pageSize, string sortField, string sortOrder, out int total, double se)
  1723. {
  1724. var list = new List<MachineEfDto>();
  1725. var regionDal = new FactoryRegionDal(CurrDb);
  1726. string errorinfo = "";
  1727. string sql = $@"SELECT a.MacCode,b.FName StatusName from macstatus01 a
  1728. INNER JOIN standardstatus b on a.StatusID = b.StatusVal ";
  1729. var macstatus01 = CurrDb.FindList<StatusDto>(sql).Select(c => new { MacCode = c.MacCode, StatusName = c.StatusName });
  1730. IEnumerable<MachineEfDto> dtos = CurrDb.FindList<MachineEfDto>(CreateEnffiencyMachineSql(filter, subFilter, start, pageSize, sortField, sortOrder, se));
  1731. foreach (var item in dtos)
  1732. {
  1733. var dt = new MachineEfDto
  1734. {
  1735. FactoryName = item.FactoryName,
  1736. PlantName = item.PlantName,
  1737. FloorName = item.FloorName,
  1738. PCode = item.PCode,
  1739. ModelName = item.ModelName,
  1740. MacCode = item.MacCode,
  1741. macnumber = item.macnumber,
  1742. RunrRate = (string.IsNullOrEmpty(item.RunrRate) ? "0.00" : item.RunrRate) + "%",
  1743. IdleRate = (string.IsNullOrEmpty(item.IdleRate) ? "0.00" : item.IdleRate) + "%",
  1744. ErrorRate = (string.IsNullOrEmpty(item.ErrorRate) ? "0.00" : item.ErrorRate) + "%",
  1745. AllTime = item.AllTime,
  1746. RunTime = item.RunTime,
  1747. IdleTime = item.IdleTime,
  1748. ErrorTime = item.ErrorTime,
  1749. ErrorTimeOne = item.ErrorTimeOne,
  1750. ErrorTimeTwo = item.ErrorTimeTwo,
  1751. ErrorRateOne = (string.IsNullOrEmpty(item.ErrorRateOne) ? "0.00" : item.ErrorRateOne) + "%",
  1752. ErrorRateTwo = (string.IsNullOrEmpty(item.ErrorRateTwo) ? "0.00" : item.ErrorRateTwo) + "%",
  1753. StatusName = macstatus01.Where(l => l.MacCode == item.MacCode).Select(l => l.StatusName).FirstOrDefault()
  1754. };
  1755. list.Add(dt);
  1756. }
  1757. total = Convert.ToInt32(CurrDb.FindList<string>(CreateEnffiencyMachineCountSql(filter, subFilter, sortField, sortOrder)).FirstOrDefault() ?? "0");
  1758. if (dtos == null || dtos.Count() <= 0)
  1759. return null;
  1760. return list;
  1761. }
  1762. public IEnumerable<MachineEfDto> GetMachineEfficyMachineTotal(string filter, string subFilter, int start, int pageSize, string sortField, string sortOrder, double se)
  1763. {
  1764. var list = new List<MachineEfDto>();
  1765. IEnumerable<MachineEfDto> dtos = CurrDb.FindList<MachineEfDto>(CreateEnffiencyMachineTotalSql(filter, subFilter, start, pageSize, sortField, sortOrder, se));
  1766. foreach (var item in dtos)
  1767. {
  1768. var dt = new MachineEfDto
  1769. {
  1770. RunrRate = (string.IsNullOrEmpty(item.RunrRate) ? "0.00" : item.RunrRate) + "%",
  1771. IdleRate = (string.IsNullOrEmpty(item.IdleRate) ? "0.00" : item.IdleRate) + "%",
  1772. ErrorRate = (string.IsNullOrEmpty(item.ErrorRate) ? "0.00" : item.ErrorRate) + "%",
  1773. AllTime = item.AllTime < 0 ? 0 : item.AllTime,
  1774. RunTime = item.RunTime < 0 ? 0 : item.RunTime,
  1775. IdleTime = item.IdleTime < 0 ? 0 : item.IdleTime,
  1776. ErrorTime = item.ErrorTime < 0 ? 0 : item.ErrorTime,
  1777. ErrorTimeOne = item.ErrorTimeOne < 0 ? 0 : item.ErrorTimeOne,
  1778. ErrorTimeTwo = item.ErrorTimeTwo < 0 ? 0 : item.ErrorTimeTwo,
  1779. ErrorRateOne = (string.IsNullOrEmpty(item.ErrorRateOne) ? "0.00" : item.ErrorRateOne) + "%",
  1780. ErrorRateTwo = (string.IsNullOrEmpty(item.ErrorRateTwo) ? "0.00" : item.ErrorRateTwo) + "%",
  1781. };
  1782. list.Add(dt);
  1783. }
  1784. if (dtos == null || dtos.Count() <= 0)
  1785. return null;
  1786. return list;
  1787. }
  1788. public IEnumerable<MachineEfFactoryDto> GetMachineEfficyFactory(string filter, double se)
  1789. {
  1790. IEnumerable<MachineEfFactoryDto> dtos = CurrDb.FindList<MachineEfFactoryDto>(CreateEnffiencyFactorySql(filter, se));
  1791. if (dtos == null || dtos.Count() <= 0)
  1792. return null;
  1793. return dtos;
  1794. }
  1795. public IEnumerable<MachineEfDto> GetMachineEfficyMachineExprort(string filter, string subFilter, string sortField, string sortOrder, int take, double se)
  1796. {
  1797. var list = new List<MachineEfDto>();
  1798. var regionDal = new FactoryRegionDal(CurrDb);
  1799. IEnumerable<MachineEfDto> dtos = CurrDb.FindList<MachineEfDto>(CreateEnffiencyMachineSqlExport(filter, subFilter, sortField, sortOrder, se)).Take(take);
  1800. if (dtos == null || dtos.Count() <= 0)
  1801. return null;
  1802. string sql = $@"SELECT a.MacCode,b.FName StatusName from macstatus01 a
  1803. INNER JOIN standardstatus b on a.StatusID = b.StatusVal";
  1804. var macstatus01 = CurrDb.FindList<StatusDto>(sql).Select(c => new { MacCode = c.MacCode, StatusName = c.StatusName });
  1805. Parallel.ForEach(dtos, item =>
  1806. {
  1807. var dt = new MachineEfDto
  1808. {
  1809. FactoryName = item.FactoryName,
  1810. PlantName = item.PlantName,
  1811. FloorName = item.FloorName,
  1812. PCode = item.PCode,
  1813. ModelName = item.ModelName,
  1814. MacCode = item.MacCode,
  1815. RunrRate = item.RunrRate,
  1816. IdleRate = item.IdleRate,
  1817. ErrorRate = item.ErrorRate,
  1818. AllTime = item.AllTime,
  1819. RunTime = item.RunTime,
  1820. IdleTime = item.IdleTime,
  1821. StatusName = macstatus01.Where(l => l.MacCode == item.MacCode).Select(l => l.StatusName).FirstOrDefault()
  1822. };
  1823. list.Add(dt);
  1824. });
  1825. return list.Where(c => !string.IsNullOrEmpty(c.FactoryName)).OrderBy(c => c.MacCode);
  1826. }
  1827. /// <summary>
  1828. /// 获取以机台为基准的效率统计列表
  1829. /// </summary>
  1830. /// <param name="filter"></param>
  1831. /// <returns></returns>
  1832. public IEnumerable<MachineEfficiency> GetMachineEfficienciesGroupByMcaCode(string filter, string macModel, string pCode, DateTime? dateStart = null, DateTime? dateEnd = null)
  1833. {
  1834. var datas = GetEffiencyEntities(filter, string.Empty).Where(c => c.PCode == pCode && c.MacModel == macModel).ToList();
  1835. var alarms = GetAlarms(filter, string.Empty).Where(c => c.PCode == pCode && c.MacModel == macModel).ToList();
  1836. // var stops = GetStatusCounts(dateStart, dateEnd);
  1837. // var oees = GetOeeEntities($" and b.FDate>='{dateStart}' and c.FDate<='{dateEnd}' ", dateStart.Value, dateEnd.Value);
  1838. //if (datas == null)
  1839. //{
  1840. // datas = new List<McaEventStatisticByDay>();
  1841. //}
  1842. datas.AddRange(alarms);
  1843. var list = new List<MachineEfficiency>();
  1844. var groups = datas.GroupBy(c => new { c.McaCode, c.McaName });
  1845. int j = 0;
  1846. if (dateStart == null && dateEnd == null)
  1847. {
  1848. dateStart = datas.OrderBy(c => c.StartTime).FirstOrDefault()?.StartTime;
  1849. // dateEnd = datas.OrderBy(c => c.EndTime).LastOrDefault()?.EndTime;
  1850. }
  1851. dateEnd = datas.Max(c => c.EndTime);
  1852. var regionDal = new FactoryRegionDal(CurrDb);
  1853. foreach (var item in groups)
  1854. {
  1855. var regionId = item.FirstOrDefault().RegionId;
  1856. var regionName = string.Empty;
  1857. string errorinfo = string.Empty;
  1858. var allRegions = regionDal.Get(1, 10000, "ID", "asc", string.Empty, errorinfo);
  1859. if (regionId != null)
  1860. {
  1861. regionName = regionDal.GetFullRegionName(regionId.Value, allRegions);
  1862. }
  1863. var entity = new MachineEfficiency
  1864. {
  1865. Index = ++j,
  1866. Count = 1,
  1867. Name = item.Key.McaCode,
  1868. RunTime = item.Where(c => c.EventCode == DllHsms.StandardCode.CEID_Run).Sum(c => c.TimeSpan.Value) / 1,
  1869. Key = item.Key.McaCode,
  1870. HasChildren = false,
  1871. Type = "machine",
  1872. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  1873. PCode = item.FirstOrDefault().PCode,
  1874. Factory = item.FirstOrDefault().Factory,
  1875. RegionName = regionName
  1876. // StopCount = stops.Where(c => c.MacCode == item.Key.McaCode)?.Sum(c => c.Count1)
  1877. };
  1878. var alarmTime = item.Where(c => c.EventCode == DllHsms.StandardCode.CEID_AlarmOccurred)?.Sum(c => c.TimeSpan);
  1879. // var alramscount = alarms.Where(c => c.MacModel == item.Key.McaCode).Select(c => c.McaCode).Distinct().Count();
  1880. entity.RunRate = entity.RunTime / entity.TotalTime; // 稼动率
  1881. entity.AlarmRate = (decimal)alarms.Where(c => c.McaCode == item.Key.McaCode && c.EventCode == DllHsms.StandardCode.CEID_AlarmOccurred)?.Sum(c => c.TimeSpan) / 1 / entity.TotalTime; // 故障率
  1882. entity.IdleRate = 1 - entity.RunRate - entity.AlarmRate; // 闲置率
  1883. entity.LossTime = entity.TotalTime - entity.RunTime;
  1884. var inProducingTime = item.Where(c => c.IsInProducing == 1 && c.EventCode == DllHsms.StandardCode.CEID_Run)?.Sum(c => c.TimeSpan.Value) / 1; // 机台中有料的生产时间
  1885. //entity.LoadRate = (decimal)inProducingTime / entity.TotalTime;
  1886. //entity.RDRate = (1 - entity.LoadRate);
  1887. //为数据显示美观 后期计算方式会变化
  1888. entity.LoadRate = entity.RunRate + entity.AlarmRate;
  1889. entity.RDRate = 1 - entity.LoadRate;
  1890. //if (oees != null && oees.Count() > 0 && oees.Where(c => c.MacCode == entity.Name).Count() > 0)
  1891. //{
  1892. // entity.PerformanceEfficiency = oees.Where(c => c.MacCode == entity.Name)?.Average(c => c.PerformanceEffi) ?? 0;
  1893. // entity.TimeEfficiency = oees.Where(c => c.MacCode == entity.Name)?.Average(c => c.TimeEffi) ?? 0;
  1894. // entity.OverallEfficiency = oees.Where(c => c.MacCode == entity.Key)?.Average(c => c.Oee) ?? 0;
  1895. //}
  1896. list.Add(entity);
  1897. }
  1898. list = list.OrderBy(c => c.Name).ToList();
  1899. var machines = this.GetAllMachines($" and d.FCode='{macModel}' and a.PCode='{pCode}'");
  1900. var notContainedEffis = new List<MachineEfficiency>();
  1901. foreach (var mac in machines)
  1902. {
  1903. var item = list.FirstOrDefault(c => c.Key == mac.MacCode);
  1904. if (item == null)
  1905. {
  1906. list.Add(new MachineEfficiency { PCode = pCode, Key = mac.MacCode, Name = mac.MacCode, Count = 1, HasChildren = false, Type = "machine" });
  1907. }
  1908. }
  1909. return list;
  1910. }
  1911. /// <summary>
  1912. /// 以机型为基准的效率统计列表
  1913. /// </summary>
  1914. /// <param name="filter"></param>
  1915. /// <returns></returns>
  1916. public IEnumerable<MachineEfficiency> GetMachineEfficienciesGroupByMacModel(string filter, string pCode, DateTime? dateStart = null, DateTime? dateEnd = null)
  1917. {
  1918. var datas = GetEffiencyEntities(filter, string.Empty).Where(c => c.PCode == pCode).ToList();
  1919. var alarms = GetAlarms(filter, string.Empty).Where(c => c.PCode == pCode).ToList();
  1920. // var stops = GetStatusCounts(dateStart,dateEnd);
  1921. var machines = GetAllMachines(string.Empty);
  1922. datas.AddRange(alarms);
  1923. // var oees = GetOeeEntities($" and b.FDate>='{dateStart}' and c.FDate<='{dateEnd}'", dateStart.Value, dateEnd.Value);
  1924. var list = new List<MachineEfficiency>();
  1925. var groups = datas.GroupBy(c => new { c.MacModel }); ;
  1926. int j = 0;
  1927. if (dateStart == null && dateEnd == null)
  1928. {
  1929. dateStart = datas.OrderBy(c => c.StartTime).FirstOrDefault()?.StartTime;
  1930. }
  1931. dateEnd = datas.Max(c => c.EndTime);
  1932. foreach (var item in groups)
  1933. {
  1934. var count = item.Select(c => c.McaCode).Distinct().Count();
  1935. var entity = new MachineEfficiency
  1936. {
  1937. Index = ++j,
  1938. Count = machines.Where(c => c.MacModel == item.Key.MacModel && c.PCode == item.FirstOrDefault().PCode).Distinct().Count(),
  1939. Name = item.Key.MacModel,
  1940. RunTime = item.Where(c => c.EventCode == DllHsms.StandardCode.CEID_Run).Sum(c => c.TimeSpan.Value) / count,
  1941. Key = item.Key.MacModel,
  1942. HasChildren = true,
  1943. Type = "macmodel",
  1944. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  1945. PCode = pCode,
  1946. // StopCount = stops.Where(c => c.MacModel == item.Key.MacModel)?.Sum(c => c.Count1)
  1947. };
  1948. entity.RunRate = entity.RunTime / entity.TotalTime; // 稼动率
  1949. entity.AlarmRate = 0;
  1950. entity.AlarmRate = (decimal)item.Where(c => c.EventCode == DllHsms.StandardCode.CEID_AlarmOccurred)?.Sum(c => c.TimeSpan) / count / entity.TotalTime; // 故障率
  1951. entity.IdleRate = 1 - entity.RunRate - entity.AlarmRate; // 闲置率
  1952. entity.LossTime = entity.TotalTime - entity.RunTime;
  1953. var inProducingTime = item.Where(c => c.IsInProducing == 1 && c.EventCode == DllHsms.StandardCode.CEID_Run)?.Sum(c => c.TimeSpan.Value) / count; // 机台中有料的生产时间
  1954. //entity.LoadRate = (decimal)inProducingTime / entity.TotalTime;
  1955. //entity.RDRate = (1 - entity.LoadRate); //为数据显示美观 后期计算方式会变化
  1956. entity.LoadRate = entity.RunRate + entity.AlarmRate;
  1957. entity.RDRate = 1 - entity.LoadRate;
  1958. //if (oees != null && oees.Count() > 0 && oees.Where(c => c.MacModelCode == entity.Key && c.PCode == pCode).Count() > 0)
  1959. //{
  1960. // entity.PerformanceEfficiency = oees.Where(c => c.MacModelCode == entity.Key && c.PCode == pCode)?.Average(c => c.PerformanceEffi) ?? 0;
  1961. // entity.TimeEfficiency = oees.Where(c => c.MacModelCode == entity.Key && c.PCode == pCode)?.Average(c => c.TimeEffi) ?? 0;
  1962. // entity.OverallEfficiency = oees.Where(c => c.MacModelCode == entity.Key && c.PCode == pCode)?.Average(c => c.Oee) ?? 0;
  1963. //}
  1964. list.Add(entity);
  1965. }
  1966. list = list.OrderBy(c => c.Name).ToList();
  1967. var groupedMachines = machines.Where(c => c.PCode == datas[0].PCode).GroupBy(c => c.MacModel);
  1968. foreach (var mac in groupedMachines)
  1969. {
  1970. var item = list.FirstOrDefault(c => c.Key == mac.Key);
  1971. if (item == null)
  1972. {
  1973. list.Add(new MachineEfficiency { PCode = pCode, Key = mac.Key, Name = mac.Key, Count = mac.Count(), HasChildren = true, Type = "macmodel" });
  1974. }
  1975. }
  1976. return list;
  1977. }
  1978. /// <summary>
  1979. /// 以制程为基准的效率统计列表
  1980. /// </summary>
  1981. /// <param name="filter"></param>
  1982. /// <returns></returns>
  1983. public IEnumerable<MachineEfficiency> GetMachineEfficienciesGroupByPcode(string filter, string subFilter, DateTime? dateStart = null, DateTime? dateEnd = null)
  1984. {
  1985. var datas = GetEffiencyEntities(filter, subFilter).ToList();
  1986. var alarms = GetAlarms(filter, subFilter).ToList();
  1987. // var stops = GetStatusCounts(dateStart,dateEnd);
  1988. var machines = GetAllMachines(string.Empty);
  1989. datas.AddRange(alarms);
  1990. // var oees = GetOeeEntities($" and b.FDate>='{dateStart}' and c.FDate<='{dateEnd}'", dateStart.Value, dateEnd.Value);
  1991. var list = new List<MachineEfficiency>();
  1992. var groups = datas.GroupBy(c => new { c.PCode, c.PName });
  1993. int j = 0;
  1994. if (dateStart == null && dateEnd == null)
  1995. {
  1996. dateStart = datas.OrderBy(c => c.StartTime).FirstOrDefault()?.StartTime;
  1997. }
  1998. dateEnd = datas.Max(c => c.EndTime);
  1999. foreach (var item in groups)
  2000. {
  2001. var count = item.Select(c => c.McaCode).Distinct().Count();
  2002. var entity = new MachineEfficiency
  2003. {
  2004. Index = ++j,
  2005. Count = machines.Where(c => c.PCode == item.Key.PCode).Select(c => c.MacCode).Distinct().Count(),
  2006. Name = item.Key.PCode,
  2007. RunTime = item.Where(c => c.EventCode == DllHsms.StandardCode.CEID_Run).Sum(c => c.TimeSpan.Value) / count,
  2008. Key = item.Key.PCode,
  2009. HasChildren = true,
  2010. Type = "pcode",
  2011. TotalTime = (decimal)(dateEnd - dateStart).Value.TotalSeconds,
  2012. PCode = item.Key.PCode,
  2013. // StopCount = stops.Where(c => c.PCode == item.Key.PCode)?.Sum(c => c.Count1)
  2014. };
  2015. entity.RunRate = entity.RunTime / entity.TotalTime; // 稼动率
  2016. entity.AlarmRate = 0;
  2017. entity.AlarmRate = (decimal)item.Where(c => c.EventCode == DllHsms.StandardCode.CEID_AlarmOccurred)?
  2018. .Sum(c => c.TimeSpan) / count / entity.TotalTime; // 故障率
  2019. entity.IdleRate = 1 - entity.RunRate - entity.AlarmRate; // 闲置率
  2020. entity.LossTime = entity.TotalTime - entity.RunTime;
  2021. var inProducingTime = item.Where(c => c.IsInProducing == 1 && c.EventCode == DllHsms.StandardCode.CEID_Run)?.Sum(c => c.TimeSpan.Value) / count; // 机台中有料的生产时间
  2022. //entity.LoadRate = (decimal)inProducingTime / entity.TotalTime;
  2023. //entity.RDRate = (1 - entity.LoadRate);
  2024. //为数据显示美观 后期计算方式会变化
  2025. entity.LoadRate = entity.RunRate + entity.AlarmRate;
  2026. entity.RDRate = 1 - entity.LoadRate;
  2027. //if (oees != null && oees.Count() > 0 && oees.Where(c => c.PCode == entity.Key).Count() > 0)
  2028. //{
  2029. // entity.PerformanceEfficiency = oees.Where(c => c.PCode == entity.Key)?.Average(c => c.PerformanceEffi) ?? 0;
  2030. // entity.TimeEfficiency = oees.Where(c => c.PCode == entity.Key)?.Average(c => c.TimeEffi) ?? 0;
  2031. // entity.OverallEfficiency = oees.Where(c => c.PCode == entity.Key)?.Average(c => c.Oee) ?? 0;
  2032. //}
  2033. list.Add(entity);
  2034. }
  2035. return list;
  2036. }
  2037. /// <summary>
  2038. /// 获取机台产量信息
  2039. /// </summary>
  2040. /// <param name="filter"></param>
  2041. /// <returns></returns>
  2042. public IEnumerable<OutputDto> GetMachineOutput(string filter, out int total, out int outputTotal, ref string errorinfo, int pageIndex = 1, int size = 10)
  2043. {
  2044. using (IDatabase eapdb = DbFactory.Base("eap"))
  2045. {
  2046. var outputs = new List<OutputDto>();
  2047. var maccounts = eapdb.FindListForCondition<MacCount02>(filter, ref errorinfo);
  2048. var groups = maccounts?.GroupBy(c => c.MacCode);
  2049. if (groups != null && groups.Count() > 0)
  2050. {
  2051. foreach (var item in groups)
  2052. {
  2053. var singles = item.OrderBy(c => c.FDate);
  2054. var output = 0;
  2055. for (var i = 0; i < singles.Count() - 1; i++)
  2056. {
  2057. var minus = singles.ElementAt(i + 1).FCount - singles.ElementAt(i).FCount;
  2058. if (minus < 0)
  2059. {
  2060. minus = 0;
  2061. }
  2062. output += minus;
  2063. }
  2064. outputs.Add(new OutputDto
  2065. {
  2066. MacCode = item.Key,
  2067. PCode = item.FirstOrDefault().PCode,
  2068. PName = item.FirstOrDefault().PName,
  2069. MacModel = item.FirstOrDefault().MacModelCode,
  2070. Supplier = item.FirstOrDefault().SupplierCode,
  2071. Count = output
  2072. });
  2073. }
  2074. }
  2075. total = outputs.Count;
  2076. outputTotal = outputs.Sum(c => c.Count);
  2077. return outputs.Skip((pageIndex - 1) * size).Take(size);
  2078. }
  2079. }
  2080. /// <summary>
  2081. /// 已制程分组获取产量信息
  2082. /// </summary>
  2083. /// <param name="filter"></param>
  2084. /// <param name="errorinfo"></param>
  2085. /// <returns></returns>
  2086. public IEnumerable<OutputTree> GetOutputs(string filter, string subFilter, ref string errorinfo)
  2087. {
  2088. var dtos = this.GetOutputsByMachine(filter, subFilter, ref errorinfo);
  2089. var trees = new List<OutputTree>();
  2090. if (dtos != null && dtos.Count() > 0)
  2091. {
  2092. var regionDal = new FactoryRegionDal(CurrDb);
  2093. var allRegions = regionDal.Get(1, 10000, "ID", "asc", string.Empty, errorinfo);
  2094. var facItem = new OutputTree
  2095. {
  2096. Key = "全厂",
  2097. Code = "全厂",
  2098. Name = "全厂",
  2099. Count = dtos.Sum(c => c.Count),
  2100. TimeLen = dtos.Sum(c => c.TimeLen)
  2101. };
  2102. if (facItem.TimeLen == 0)
  2103. {
  2104. facItem.UPH = 0;
  2105. }
  2106. else
  2107. {
  2108. facItem.UPH = Convert.ToInt32(Math.Round(Convert.ToDecimal(facItem.Count) / (decimal)facItem.TimeLen * 60 * 60));
  2109. }
  2110. var pcodeGroups = dtos.GroupBy(c => new { c.PCode, c.PName });
  2111. var pcodeTrees = new List<OutputTree>();
  2112. if (pcodeGroups != null && pcodeGroups.Count() > 0)
  2113. {
  2114. foreach (var item in pcodeGroups)
  2115. {
  2116. var root = new OutputTree
  2117. {
  2118. Key = item.Key.PCode,
  2119. Code = item.Key.PCode,
  2120. Name = item.Key.PName,
  2121. Level = 1,
  2122. Expand = false,
  2123. MacCode = "--",
  2124. MacModel = "--",
  2125. MacName = "--",
  2126. MacModelName = "--",
  2127. Count = item.Sum(c => c.Count),
  2128. TimeLen = item.Sum(c => c.TimeLen)
  2129. };
  2130. if (root.TimeLen == 0)
  2131. {
  2132. root.UPH = 0;
  2133. }
  2134. else
  2135. {
  2136. root.UPH = Convert.ToInt32(Math.Round(root.Count / (decimal)root.TimeLen * 60 * 60));
  2137. }
  2138. var macmodelGroups = item.GroupBy(e => new { e.MacModel, e.MacModelName });
  2139. if (macmodelGroups != null && macmodelGroups.Count() > 0)
  2140. {
  2141. var modelTrees = new List<OutputTree>();
  2142. foreach (var modelItem in macmodelGroups)
  2143. {
  2144. var macmodel = new OutputTree
  2145. {
  2146. Key = item.Key.PName + modelItem.Key.MacModel,
  2147. Code = modelItem.Key.MacModel,
  2148. Name = modelItem.Key.MacModelName,
  2149. Level = 2,
  2150. Expand = false,
  2151. Count = modelItem.Sum(c => c.Count),
  2152. TimeLen = modelItem.Sum(c => c.TimeLen)
  2153. };
  2154. if (macmodel.TimeLen == 0)
  2155. {
  2156. macmodel.UPH = 0;
  2157. }
  2158. else
  2159. {
  2160. macmodel.UPH = Convert.ToInt32(Math.Round(macmodel.Count / (decimal)macmodel.TimeLen * 60 * 60));
  2161. }
  2162. var macTrees = new List<OutputTree>();
  2163. foreach (var mac in modelItem)
  2164. {
  2165. var regionName = string.Empty;
  2166. if (mac.RegionId != null)
  2167. {
  2168. regionName = regionDal.GetFullRegionName(mac.RegionId.Value, allRegions);
  2169. }
  2170. var macItem = new OutputTree
  2171. {
  2172. Key = mac.Code,
  2173. Code = mac.Code,
  2174. Name = mac.Name,
  2175. RegionName = regionName,
  2176. Level = 3,
  2177. Expand = false,
  2178. Count = mac.Count,
  2179. Children = null,
  2180. TimeLen = mac.TimeLen
  2181. };
  2182. if (mac.TimeLen == 0)
  2183. {
  2184. macItem.UPH = 0;
  2185. }
  2186. else
  2187. {
  2188. macItem.UPH = Convert.ToInt32(Math.Round(macItem.Count / (decimal)macItem.TimeLen * 60 * 60));
  2189. }
  2190. macTrees.Add(macItem);
  2191. }
  2192. macmodel.Children = macTrees;
  2193. modelTrees.Add(macmodel);
  2194. }
  2195. root.Children = modelTrees;
  2196. }
  2197. pcodeTrees.Add(root);
  2198. }
  2199. }
  2200. facItem.Children = pcodeTrees;
  2201. trees.Add(facItem);
  2202. }
  2203. return trees;
  2204. }
  2205. private IEnumerable<OutputDto> GetOutputsByMachine(string filter, string subFilter, ref string errorinfo)
  2206. {
  2207. string sql = $@"select count,e.fcode as pcode,e.fname as pname,f.fcode as macmodel,
  2208. f.fname as macmodelname,c.fcode as code,c.fname as name,TimeLen,
  2209. c.RegionId from
  2210. (select a.macid,sum(b.fcount) count,sum(a.timeLen) timeLen from maccountmst a
  2211. left join maccountdetail b on a.id=b.mstid
  2212. where b.paramcode='S00026' and b.typeid=0 {filter}
  2213. group by a.macid) t
  2214. left join machine c on t.macid=c.id
  2215. left join mactprocess d on c.id=d.macid
  2216. left join tprocess e on d.pcode=e.fcode
  2217. left join macmodel f on c.mmodeid=f.id
  2218. where 1=1 {subFilter}";
  2219. var dtos = CurrDb.FindList<OutputDto>(sql);
  2220. return dtos;
  2221. }
  2222. public IEnumerable<OutputDto> GetOutputsByProgram(string filter, string subFilter, int skip, int take, string sort, string order, ref string errorinfo)
  2223. {
  2224. var sql = $@"select count,timelen,round(count/timelen*3600) uph,name,pcode from (select sum(cc.count) as count,sum(cc.timelen) as timelen,cc.pname as name,
  2225. c.pcode from
  2226. (select tt.macid,tt.pname,sum(tt.timelen) timelen,sum(a.fcount) count from
  2227. (select b.id,b.macid,b.timelen,b.pname from maccountmst b where 1=1
  2228. {filter} and b.timelen<>0
  2229. and b.pname is not null) tt
  2230. left join maccountdetail a on tt.id=a.mstid
  2231. where 1=1
  2232. and a.typeid=0 and a.paramcode='S00026' group by tt.macid,tt.pname) cc
  2233. left join mactprocess c on cc.macid=c.macid
  2234. left join machine d on cc.macid = d.id
  2235. where 1=1 {subFilter}
  2236. group by cc.pname,c.pcode) t order by {sort} {order} limit {skip - 1},{take}";
  2237. return CurrDb.FindList<OutputDto>(sql);
  2238. }
  2239. public int GetProgramCountFromMacCount(string filter, string subFilter)
  2240. {
  2241. var sql = $@"select count(1) from(select sum(count),pname from (
  2242. select count(1) count ,pname,macid from maccountmst b where 1 = 1 {filter}
  2243. and b.timelen <> 0 and b.pname is not null
  2244. group by pname,macid) tt
  2245. left join mactprocess c on tt.macid = c.macid
  2246. left join machine d on tt.macid = d.id
  2247. where 1=1 {subFilter}
  2248. group by pname)t";
  2249. return Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  2250. }
  2251. public int GetExtra(string filter, string subFilter)
  2252. {
  2253. var sql = $@"select sum(cc.count) as count from
  2254. (select tt.macid,sum(a.fcount) count from
  2255. (select b.id,b.macid,b.timelen from maccountmst b where 1=1
  2256. and b.timelen<>0 {filter}
  2257. and b.pname is not null) tt
  2258. left join maccountdetail a on tt.id=a.mstid
  2259. where 1=1
  2260. and a.typeid=0 and a.paramcode='S00026' group by tt.macid) cc
  2261. left join mactprocess c on cc.macid=c.macid
  2262. left join machine d on cc.macid = d.id
  2263. where 1=1 {subFilter}";
  2264. return Convert.ToInt32(CurrDb.FindList<string>(sql).FirstOrDefault() ?? "0");
  2265. }
  2266. public IEnumerable<OeeEntity> GetOeeEntities(string filter, DateTime dateStart, DateTime dateEnd)
  2267. {
  2268. string sql = $@"select b.FDate as TrackInTime,c.FDate as TrackOutTime,a.PCode,a.FTotal,a.FGoods,a.Rejects,a.Losts,a.MacCode,d.FModel as MacModelCode,
  2269. e.FName as MacModelName,g.PartCode as ProductCode from JobBooking a
  2270. left join JbTrack b on a.ID=b.JbID and b.FType=1
  2271. left join JbTrack c on a.ID=c.JbID and c.FType=-1
  2272. left join Machine d on a.MacCode=d.FCode
  2273. left join MacModel e on d.FModel=e.FCode
  2274. left join LotMst f on a.LotNo=f.LotNo
  2275. left join ProductOrder g on f.PoCode=g.FCode
  2276. where a.StatusID=2 and a.IsAuto=1 {filter}";
  2277. var jobs = CurrDb.FindList<JobbookingDto>(sql);
  2278. var list = new List<OeeEntity>();
  2279. var idealDal = new ProductOutputConfigDal(CurrDb);
  2280. var runs = this.GetEffiencyEntities($"and a.StartTime>='{dateStart}' and a.StartTime<='{dateEnd}'", string.Empty);
  2281. foreach (var item in jobs)
  2282. {
  2283. item.RunTime = runs.Where(c => c.McaCode == item.MacCode && c.StartTime >= item.TrackInTime && c.EndTime <= item.TrackOutTime)
  2284. ?.Sum(c => c.TimeSpan) ?? 0;
  2285. }
  2286. string errorinfo = string.Empty;
  2287. var configs = idealDal.Get(1, 10000, "asc", "a.id", string.Empty, errorinfo);
  2288. if (jobs != null && jobs.Count() > 0)
  2289. {
  2290. var groups = jobs.GroupBy(c => new { c.PCode, c.MacModelCode, c.MacCode, c.ProductCode });
  2291. foreach (var item in groups)
  2292. {
  2293. var entity = new OeeEntity
  2294. {
  2295. MacCode = item.Key.MacCode,
  2296. PCode = item.FirstOrDefault().PCode,
  2297. ProductCode = item.Key.ProductCode,
  2298. FGoods = item.Sum(c => c.FGoods),
  2299. Rejects = item.Sum(c => c.Rejects),
  2300. Losts = item.Sum(c => c.Losts),
  2301. Output = item.Sum(c => c.FTotal),
  2302. MacModelCode = item.FirstOrDefault().MacModelCode,
  2303. MacModelName = item.FirstOrDefault().MacModelName
  2304. };
  2305. var config = configs.FirstOrDefault(c => c.MacCode == entity.MacCode && c.ProductCode == entity.ProductCode);
  2306. if (config == null)
  2307. {
  2308. entity.TimeEffi = 0;
  2309. entity.PerformanceEffi = 0;
  2310. entity.Oee = 0;
  2311. }
  2312. else
  2313. {
  2314. var idealTs = 60 * 60 / config.FLen; // 理想加工周期
  2315. entity.RunTime = item.Sum(c => c.RunTime); // 机台在这段时间内的运行时长
  2316. entity.LoadTime = (decimal)item.Sum(c => (c.TrackOutTime - c.TrackInTime).TotalSeconds); // 负荷时间 当前时间段内所有trackin到trackout的时间和
  2317. entity.TimeEffi = entity.RunTime / entity.LoadTime;
  2318. if (entity.RunTime > 0)
  2319. {
  2320. entity.PerformanceEffi = (decimal)idealTs * entity.Output / entity.RunTime;
  2321. }
  2322. entity.Oee = (decimal)idealTs * entity.FGoods / entity.LoadTime;
  2323. list.Add(entity);
  2324. }
  2325. }
  2326. }
  2327. return list;
  2328. }
  2329. #endregion
  2330. #region 定时汇总相关
  2331. /// <summary>
  2332. /// 从Eap数据库中获取
  2333. /// </summary>
  2334. /// <param name="filter"></param>
  2335. /// <returns></returns>
  2336. public IEnumerable<MacStatus> GetMacStatusesFromMySql(string filter)
  2337. {
  2338. return CurrDb.FindList<MacStatus>($@"select a.* from macstatus a
  2339. where a.ishandeled=0 {filter}");
  2340. }
  2341. /// <summary>
  2342. /// 获取上次汇总报警的时间
  2343. /// </summary>
  2344. /// <returns></returns>
  2345. public DateTime GetLastAsyncDate()
  2346. {
  2347. string errorinfo = string.Empty;
  2348. var macstaus = CurrDb.FindListForCondition<MacStatus>($" and a.ishandled=1 " +
  2349. $"order by id desc limit 0,1", ref errorinfo).FirstOrDefault();
  2350. if (macstaus == null)
  2351. return DateTime.Now.AddDays(-2);
  2352. return macstaus.ETime;
  2353. }
  2354. public int Async(DateTime dateNow, ref string errorinfo)
  2355. {
  2356. // using(IDatabase db = DbFactory.Base())
  2357. var details = CurrDb.FindList<AlarmCode>(CreateDetailSql(dateNow)).ToList();
  2358. LogHelper<McaEventStatisticByDayDal>.LogFatal($"开始同步报警数据", "EapAsync", string.Empty);
  2359. if (details == null || details.Count() <= 0)
  2360. {
  2361. errorinfo = "暂无需要汇总的数据";
  2362. // LogHelper<McaEventStatisticByDayDal>.LogFatal($"暂无需要汇总的数据", "EapAsync", string.Empty);
  2363. return -1;
  2364. }
  2365. var minumnDate = details.Min(c => c.ptime);
  2366. IList<int> alarmHandledIds = new List<int>();
  2367. string runHandledIds = string.Empty;
  2368. var entities = AppendAlarmEndTime(details, StandardCode.CEID_AlarmOccurred, DllHsms.StandardCode.CEID_AlarmRelease, dateNow, out alarmHandledIds).ToList();
  2369. var runs = AppendRunTime(details, dateNow, out runHandledIds);
  2370. entities.AddRange(runs);
  2371. var aoiAlarmIds = string.Empty;
  2372. entities = entities.Where(c => c.IsHandled == 1).Distinct(new AlarmByDayComparer()).ToList();
  2373. var aoiAlarms = AppendAoiAlarms(dateNow, out aoiAlarmIds);
  2374. entities.AddRange(aoiAlarms);
  2375. if (CurrDb.Insert<McaEventStatisticByDay>(entities) < 0)
  2376. {
  2377. errorinfo = "插入目标表失败";
  2378. return -1;
  2379. }
  2380. var sql = string.Empty;
  2381. #region sql批量插入
  2382. //DataTable dt = new DataTable();
  2383. //var sql = "select * from McaEventStatisticByDay where 1<>1";
  2384. //Console.WriteLine("开始插入目标表");
  2385. //dt = CurrDb.FindTable(sql);
  2386. //SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, trans);
  2387. //bulkCopy.DestinationTableName = "McaEventStatisticByDay";
  2388. //foreach (var item in entities)
  2389. //{
  2390. // var rows = dt.Select($" McaCode ='{item.McaCode}' and AlarmCode ='{item.AlarmCode}' " +
  2391. // $"and EventCode='{item.EventCode}' and StartTime='{item.StartTime}'" +
  2392. // $"and EndTime='{item.EndTime}'");
  2393. // if (rows != null && rows.Count() > 0)
  2394. // {
  2395. // continue;
  2396. // }
  2397. // DataRow row = dt.NewRow();
  2398. // row["ProductName"] = item.ProductName;
  2399. // row["Manufacturer"] = item.Manufacturer;
  2400. // row["AlarmCode"] = item.AlarmCode;
  2401. // row["AlarmDesc"] = item.AlarmDesc;
  2402. // row["EventCode"] = item.EventCode;
  2403. // row["McaCode"] = item.McaCode;
  2404. // row["McaName"] = item.McaName;
  2405. // row["MacModel"] = item.MacModel;
  2406. // row["MacModelName"] = item.MacModelName;
  2407. // row["PCode"] = item.PCode;
  2408. // row["PName"] = item.PName;
  2409. // row["ProgramName"] = item.ProgramName;
  2410. // row["StartTime"] = item.StartTime;
  2411. // row["IsInProducing"] = item.IsInProducing;
  2412. // var endTime = DBNull.Value;
  2413. // if (item.EndTime == null)
  2414. // {
  2415. // row["EndTime"] = endTime;
  2416. // }
  2417. // else
  2418. // {
  2419. // row["EndTime"] = item.EndTime;
  2420. // }
  2421. // if (item.TimeSpan == null)
  2422. // {
  2423. // row["TimeSpan"] = DBNull.Value;
  2424. // }
  2425. // else
  2426. // {
  2427. // row["TimeSpan"] = item.TimeSpan;
  2428. // }
  2429. // row["IsHandled"] = item.IsHandled;
  2430. // row["InsertTime"] = DateTime.Now;
  2431. // dt.Rows.Add(row);
  2432. //}
  2433. //bulkCopy.BatchSize = dt.Rows.Count;
  2434. //bulkCopy.WriteToServer(dt);
  2435. //bulkCopy.Close();
  2436. #endregion
  2437. var updateSql = "delete from McaEventStatisticByDay where id not in (select max(id) from McaEventStatisticByDay " +
  2438. "group by McaCode,EventCode,AlarmCode,StartTime,EndTime) ";
  2439. if (alarmHandledIds != null && alarmHandledIds.Count > 0)
  2440. {
  2441. updateSql = $"update McaSecTime set IsHandled=1 where id in({string.Join(",", alarmHandledIds.Select(c => $"'{c}'"))})";
  2442. var res = CurrDb.ExecuteBySql(updateSql);
  2443. if (res < 0)
  2444. {
  2445. errorinfo = "更新数据源表失败";
  2446. // LogHelper<McaEventStatisticByDayDal>.LogError($"更新数据源表失败", "EapAsync", string.Empty);
  2447. return -1;
  2448. }
  2449. }
  2450. if (!string.IsNullOrEmpty(runHandledIds))
  2451. {
  2452. updateSql = $"update MacStatus set ishandeled=1 where id in ({runHandledIds})";
  2453. if (CurrDb.ExecuteBySql(updateSql) < 0)
  2454. {
  2455. // LogHelper<McaEventStatisticByDayDal>.LogError($"更新MYSQL中运行状态表失败", "EapAsync", string.Empty);
  2456. errorinfo = "更新MYSQL中运行状态表失败";
  2457. return -1;
  2458. }
  2459. }
  2460. if (!string.IsNullOrEmpty(aoiAlarmIds))
  2461. {
  2462. updateSql = $"update MacStatus set ishandeled=1 where id in ({aoiAlarmIds})";
  2463. if (CurrDb.ExecuteBySql(updateSql) < 0)
  2464. {
  2465. // LogHelper<McaEventStatisticByDayDal>.LogError($"更新MYSQL中运行状态表失败", "EapAsync", string.Empty);
  2466. errorinfo = "更新MYSQL中AOI报警状态表失败";
  2467. return -1;
  2468. }
  2469. }
  2470. return 1;
  2471. }
  2472. public void AsyncFails(string connStr, DatabaseType dbType, ref string errorinfo)
  2473. {
  2474. IDatabase db = null;
  2475. try
  2476. {
  2477. db = CurrDb;
  2478. var fails = CurrDb.FindListForCondition<EapAsyncHistory>($" and a.IsSuccess=-1", ref errorinfo)
  2479. ?.Where(c => (DateTime.Now - c.AsyncTime).TotalMinutes > 62);
  2480. if (fails != null && fails.Count() > 0)
  2481. {
  2482. foreach (var item in fails)
  2483. {
  2484. using (IDatabase tempDb = DbFactory.Base(connStr, dbType))
  2485. {
  2486. if (this.Async(item.AsyncTime, ref errorinfo) < 0)
  2487. {
  2488. tempDb.Rollback();
  2489. continue;
  2490. }
  2491. item.IsSuccess = 1;
  2492. if (CurrDb.UpdateFor(item, string.Empty) < 0)
  2493. {
  2494. tempDb.Rollback();
  2495. LogHelper<McaEventStatisticByDay>.LogFatal($"更新汇总记录[{item.AsyncTime.ToString("yyyy-MM-dd HH:mm:ss")}]失败", "EapAsync", string.Empty);
  2496. continue;
  2497. }
  2498. tempDb.Commit();
  2499. }
  2500. }
  2501. }
  2502. else
  2503. {
  2504. LogHelper<McaEventStatisticByDay>.LogFatal("暂无需要处理的记录", "EapAsync", string.Empty);
  2505. }
  2506. }
  2507. catch (Exception e)
  2508. {
  2509. if (db != null)
  2510. db.Rollback();
  2511. LogHelper<McaEventStatisticByDayDal>.LogError(e.Message, "EapAsync", string.Empty);
  2512. LogHelper<McaEventStatisticByDayDal>.LogError(e.StackTrace, "EapAsync", string.Empty);
  2513. }
  2514. finally
  2515. {
  2516. if (db != null)
  2517. {
  2518. db.Close();
  2519. db.Dispose();
  2520. }
  2521. }
  2522. }
  2523. private object obj = new object();
  2524. /// <summary>
  2525. /// 加入报警结束时间
  2526. /// </summary>
  2527. /// <param name="details"></param>
  2528. /// <param name="startCode"></param>
  2529. /// <param name="endCode"></param>
  2530. /// <returns></returns>
  2531. public IEnumerable<McaEventStatisticByDay> AppendAlarmEndTime(IEnumerable<AlarmCode> details, string startCode, string endCode, DateTime date, out IList<int> ids)
  2532. {
  2533. LogHelper<McaEventStatisticByDayDal>.LogFatal($"开始同步报警,总数:{details.Count()}", "EapAsync", string.Empty);
  2534. if (string.IsNullOrEmpty(endCode))
  2535. {
  2536. endCode = startCode;
  2537. }
  2538. IList<AlarmCode> occcurrs, releases;
  2539. occcurrs = details.Where(c => c.eventCode == startCode).OrderBy(c => c.ptime).ToList(); //所有报警开始的数据
  2540. LogHelper<McaEventStatisticByDayDal>.LogFatal($"报警开始数量:{occcurrs.Count()}", "EapAsync", string.Empty);
  2541. releases = details.Where(c => c.eventCode == endCode).OrderBy(c => c.ptime).ToList(); //所有报警结束的数据
  2542. LogHelper<McaEventStatisticByDayDal>.LogFatal($"报警解除数量:{releases.Count()}", "EapAsync", string.Empty);
  2543. var entities = new ConcurrentBag<McaEventStatisticByDay>();
  2544. var handledIds = new List<int>();
  2545. //Parallel.For(0, occcurrs.Count, i =>
  2546. //{
  2547. for (var i = 0; i < occcurrs.Count; i++)
  2548. {
  2549. var element = occcurrs[i];
  2550. var entity = new McaEventStatisticByDay()
  2551. {
  2552. AlarmCode = element.name,
  2553. AlarmDesc = element.description,
  2554. StartTime = element.ptime,
  2555. MacModel = element.macmodel,
  2556. McaCode = element.maccode,
  2557. McaName = element.macname,
  2558. MacModelName = element.macmodelname,
  2559. PCode = element.pcode,
  2560. PName = element.pname,
  2561. EventCode = DllHsms.StandardCode.CEID_AlarmOccurred,
  2562. Manufacturer = element.supplier
  2563. };
  2564. AlarmCode releaseItem = null;
  2565. //获取当前报警的机台的下一次报警,如果此次报警不是当前机台的最后一次报警,
  2566. //则限定结束报警的时间要在当前报警的后面且在下一次报警之前
  2567. var nextItem = occcurrs.FirstOrDefault(c => c.maccode == element.maccode && c.ptime > element.ptime);
  2568. if (nextItem != null)
  2569. {
  2570. releaseItem = releases.Where(c => c.ptime >= occcurrs[i].ptime
  2571. && c.maccode == occcurrs[i].maccode && c.ptime < nextItem.ptime
  2572. && c.name == occcurrs[i].name).OrderBy(c => c.ptime).FirstOrDefault();
  2573. }
  2574. else
  2575. {
  2576. releaseItem = releases.Where(c => c.ptime >= occcurrs[i].ptime
  2577. && c.maccode == occcurrs[i].maccode && c.name == occcurrs[i].name)
  2578. .OrderBy(c => c.ptime).FirstOrDefault();
  2579. }
  2580. //如果有报警有结束的记录,则取结束的记录,如果没有,判断该报警距离今天是不是超过24小时,
  2581. //未超过则跳过该记录,将该记录置为未处理,等下次汇总时处理,如果超过一天,则取
  2582. //该机台下一次报警的开始时间作为此次报警的结束时间,如果没有报警,则取下一次状态改变的时间
  2583. //
  2584. if (releaseItem != null)
  2585. {
  2586. entity.EndTime = releaseItem.ptime;
  2587. entity.TimeSpan = (decimal)(entity.EndTime - entity.StartTime).Value.TotalSeconds;
  2588. entity.IsHandled = 1;
  2589. handledIds.Add(element.Id);
  2590. handledIds.Add(releaseItem.Id);
  2591. }
  2592. else
  2593. {
  2594. TimeSpan ts = date - element.ptime.Value;
  2595. if (ts.TotalDays > 1)
  2596. {
  2597. entity.EndTime = entity.StartTime.Value.AddMinutes(10);
  2598. entity.TimeSpan = (decimal)(entity.EndTime - entity.StartTime).Value.TotalSeconds;
  2599. //releaseItem = details.Where(c => c.ptime > element.ptime && c.maccode == element.maccode).FirstOrDefault();
  2600. //if (releaseItem == null)
  2601. //{
  2602. // var nextEvent = details.FirstOrDefault(c => c.ptime > element.ptime);
  2603. // if (nextEvent == null)
  2604. // {
  2605. // entity.EndTime = entity.StartTime;
  2606. // }
  2607. // else
  2608. // {
  2609. // entity.EndTime = nextEvent.ptime;
  2610. // }
  2611. //}
  2612. //else if (nextItem == null)
  2613. //{
  2614. // entity.EndTime = releaseItem.ptime;
  2615. //}
  2616. //else
  2617. //{
  2618. // if (nextItem.ptime < releaseItem.ptime)
  2619. // {
  2620. // entity.EndTime = nextItem.ptime;
  2621. // }
  2622. // else
  2623. // {
  2624. // entity.EndTime = releaseItem.ptime;
  2625. // }
  2626. //}
  2627. //entity.TimeSpan = (decimal)(entity.EndTime - entity.StartTime).Value.TotalSeconds;
  2628. entity.IsHandled = 1;
  2629. //if (releaseItem != null)
  2630. //{
  2631. // handledIds.Add(releaseItem.Id);
  2632. //}
  2633. handledIds.Add(element.Id);
  2634. }
  2635. else
  2636. {
  2637. entity.IsHandled = -1;
  2638. }
  2639. }
  2640. if (entity.IsHandled == 1)
  2641. {
  2642. entities.Add(entity);
  2643. }
  2644. Console.WriteLine($"========插入机台[{entity.McaCode}]报警代码为{entity.AlarmCode}的记录成功==========={i + 1}");
  2645. }
  2646. //});
  2647. ids = handledIds;
  2648. LogHelper<McaEventStatisticByDayDal>.LogFatal($"提取报警结束时间成功", "EapAsync", string.Empty);
  2649. return entities;
  2650. }
  2651. /// <summary>
  2652. /// 加入设备运行时间
  2653. /// </summary>
  2654. /// <param name="startCode"></param>
  2655. /// <returns></returns>
  2656. public IEnumerable<McaEventStatisticByDay> AppendRunTime(IEnumerable<AlarmCode> details, DateTime date, out string ids)
  2657. {
  2658. var macStatuses = this.GetMacStatusesFromMySql($" and a.statusid=4 and " +
  2659. $"a.stime>'{date.AddMinutes(-62).ToString("yyyy-MM-dd HH:mm:ss")}' " +
  2660. $"and a.stime<='{date.ToString("yyyy-MM-dd HH:mm:ss")}' " +
  2661. $" and a.etime<>'0001-01-01 00:00:00' " +
  2662. $"" +
  2663. $"order by a.stime asc").ToList(); // 设备运行事件
  2664. LogHelper<McaEventStatisticByDayDal>.LogFatal($"机台运行记录总数:{macStatuses.Count()}", "EapAsync", string.Empty);
  2665. var entities = new ConcurrentBag<McaEventStatisticByDay>();
  2666. var macProcesses = GetMacTProcesses();
  2667. var handledIds = string.Empty;
  2668. if (macStatuses != null && macStatuses.Count > 0)
  2669. {
  2670. var index = 0;
  2671. //Parallel.ForEach<MacStatus>(macStatuses, item =>
  2672. //{
  2673. foreach (var item in macStatuses)
  2674. {
  2675. DateTime? endTime = null;
  2676. if (item.ETime.ToString("yyyy-MM-dd") != "0001-01-01")
  2677. {
  2678. endTime = item.ETime;
  2679. }
  2680. var element = new McaEventStatisticByDay
  2681. {
  2682. AlarmCode = string.Empty,
  2683. AlarmDesc = string.Empty,
  2684. StartTime = item.STime,
  2685. EndTime = endTime,
  2686. TimeSpan = item.FLen,
  2687. EventCode = DllHsms.StandardCode.CEID_Run,
  2688. McaCode = item.MacCode,
  2689. Manufacturer = item.Supplier
  2690. };
  2691. var macP = macProcesses.FirstOrDefault(c => c.MacCode == element.McaCode);
  2692. if (macP != null)
  2693. {
  2694. element.MacModel = macP.MacModel;
  2695. element.MacModelName = macP.MacModelName;
  2696. // element.Manufacturer = string.Empty;
  2697. element.McaName = macP.MacName;
  2698. element.PCode = macP.ProcessCode;
  2699. element.PName = macP.ProcessName;
  2700. }
  2701. if (element.EndTime != null)
  2702. {
  2703. element.IsHandled = 1;
  2704. handledIds += $"{item.ID},";
  2705. if (element.TimeSpan != null)
  2706. {
  2707. if (entities.FirstOrDefault(c => c.McaCode == element.McaCode
  2708. && c.StartTime == element.StartTime && c.EndTime == element.EndTime
  2709. && c.EventCode == element.EventCode) == null)
  2710. entities.Add(element);
  2711. }
  2712. index++;
  2713. Console.WriteLine($"========插入机台为{element.McaCode}的运行记录成功==========={index}");
  2714. }
  2715. }
  2716. //});
  2717. }
  2718. ids = string.IsNullOrEmpty(handledIds) ? handledIds : handledIds.Substring(0, handledIds.Length - 1);
  2719. LogHelper<McaEventStatisticByDayDal>.LogFatal($"提取机台运行数据成功", "EapAsync", string.Empty);
  2720. return entities;
  2721. }
  2722. /// <summary>
  2723. /// 处理AOI报警
  2724. /// </summary>
  2725. /// <param name="date"></param>
  2726. /// <param name="ids"></param>
  2727. /// <returns></returns>
  2728. public IEnumerable<McaEventStatisticByDay> AppendAoiAlarms(DateTime date, out string ids)
  2729. {
  2730. var entities = new ConcurrentBag<McaEventStatisticByDay>();
  2731. var handledIds = string.Empty;
  2732. var alarms = GetAOIAlarms(date);
  2733. if (alarms != null && alarms.Count() > 0)
  2734. {
  2735. var index = 0;
  2736. //Parallel.ForEach<MacStatus>(macStatuses, item =>
  2737. //{
  2738. foreach (var item in alarms)
  2739. {
  2740. DateTime? endTime = null;
  2741. if (item.ETime.ToString("yyyy-MM-dd") != "0001-01-01")
  2742. {
  2743. endTime = item.ETime;
  2744. }
  2745. var element = new McaEventStatisticByDay
  2746. {
  2747. AlarmCode = string.Empty,
  2748. AlarmDesc = string.Empty,
  2749. StartTime = item.STime,
  2750. EndTime = endTime,
  2751. TimeSpan = item.FLen,
  2752. EventCode = DllHsms.StandardCode.CEID_AlarmOccurred,
  2753. McaCode = item.MacCode
  2754. };
  2755. if (element.EndTime != null)
  2756. {
  2757. element.IsHandled = 1;
  2758. handledIds += $"{item.ID},";
  2759. if (element.TimeSpan != null)
  2760. {
  2761. if (entities.FirstOrDefault(c => c.McaCode == element.McaCode
  2762. && c.StartTime == element.StartTime && c.EndTime == element.EndTime
  2763. && c.EventCode == element.EventCode) == null)
  2764. entities.Add(element);
  2765. }
  2766. index++;
  2767. Console.WriteLine($"========插入机台为{element.McaCode}的报警记录成功==========={index}");
  2768. }
  2769. }
  2770. //});
  2771. }
  2772. ids = string.IsNullOrEmpty(handledIds) ? handledIds : handledIds.Substring(0, handledIds.Length - 1);
  2773. return entities;
  2774. }
  2775. /// <summary>
  2776. /// 获取所有机型制程对应关系
  2777. /// </summary>
  2778. /// <returns></returns>
  2779. public IEnumerable<MacTProcess> GetMacTProcesses()
  2780. {
  2781. string sql = "select a.*,b.FCode as MacCode,b.FName as MacName,c.FCode as ProcessCode,c.FName as ProcessName,d.FCode as macmodel," +
  2782. "d.fname as MacModelName "
  2783. + "from MacTProcess a " +
  2784. "inner join Machine b on a.MacId=b.id " +
  2785. "inner join TProcess c on a.PCode=c.FCode " +
  2786. "inner join MacModel d on b.MModeId = d.id";
  2787. return CurrDb.FindList<MacTProcess>(sql);
  2788. }
  2789. public string CreateDetailSql(DateTime date)
  2790. {
  2791. var sql = $@"select
  2792. a.Id,b.McaCode as maccode,b.eventcode,c.FVal as name,
  2793. d.FVal as description,a.ptime
  2794. from (select * from McaSecTime temp where
  2795. temp.ptime>'{date.AddMinutes(-62).ToString("yyyy-MM-dd HH:mm:ss")}'
  2796. and temp.ptime<='{date.ToString("yyyy-MM-dd HH:mm:ss")}') a
  2797. inner join McaSecVMst b on a.PreID = b.ID
  2798. left outer join McaSecVDetail c on b.ID = c.PreID and c.FNum = 2
  2799. left outer join McaSecVDetail d on b.ID = d.PreID and d.FNum = 3
  2800. "
  2801. + $"where 1=1 and (b.eventcode ='{DllHsms.StandardCode.CEID_AlarmOccurred}' " +
  2802. $"or b.eventcode='{DllHsms.StandardCode.CEID_AlarmRelease}') " +
  2803. $" and (a.ishandled is null or a.ishandled=0) and left(b.McaCode,4)<>'LXJC' ";
  2804. return sql;
  2805. }
  2806. /// <summary>
  2807. /// 获取AOI报警
  2808. /// </summary>
  2809. /// <param name="date"></param>
  2810. /// <returns></returns>
  2811. private IEnumerable<MacStatus> GetAOIAlarms(DateTime date)
  2812. {
  2813. var sql = "select a.id,a.maccode,a.alarmcode,a.alarmdescribe,a.stime,a.etime,a.flen from macstatus where left(maccode,4)='LXJC' and " +
  2814. $"stime>'{date.AddMinutes(-62).ToString("yyyy-MM-dd HH:mm:ss")}' " +
  2815. $"and stime<'{date.ToString("yyyy-MM-dd HH:mm:ss")}' and ishandeled=0 " +
  2816. $"and a.etime<>'0001-01-01 00:00:00' ";
  2817. return CurrDb.FindList<MacStatus>(sql);
  2818. }
  2819. #endregion
  2820. #region 大屏展示
  2821. public IEnumerable<OrderProgressDto> GetOrderProgress(string filter)
  2822. {
  2823. string sql = @"select top 12 b.PoCode as OrderNo,Sum(c.FTotal) as CompleteCount from JobBooking a
  2824. left join LotMst b on a.LotNo = b.LotNo
  2825. left join JbStaff c on a.ID=c.JbID "
  2826. + $" where a.StatusID = 2 {filter} group by b.PoCode order by sum(b.FCount) desc";
  2827. var progresses = CurrDb.FindList<OrderProgressDto>(sql);
  2828. sql = "select sum(FCount) as Count ,pocode as OrderNo from LotMst where 1=1 "
  2829. + $" and pocode in ({string.Join(",", progresses.Select(c => $"'{c.OrderNo}'"))}) group by PoCode";
  2830. var orders = CurrDb.FindList<OrderCountDto>(sql);
  2831. foreach (var item in progresses)
  2832. {
  2833. item.TotalCount = orders.FirstOrDefault(c => c.OrderNo == item.OrderNo).Count;
  2834. }
  2835. return progresses;
  2836. }
  2837. #endregion
  2838. }
  2839. }