ops.go 298 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "tmr-watch/conf/setting"
  19. "tmr-watch/http/handle/gm"
  20. "tmr-watch/http/handle/restful"
  21. "tmr-watch/module"
  22. "tmr-watch/pkg/app"
  23. "tmr-watch/pkg/e"
  24. "tmr-watch/pkg/logging"
  25. "github.com/360EntSecGroup-Skylar/excelize"
  26. "github.com/Anderson-Lu/gofasion/gofasion"
  27. "github.com/astaxie/beego/logs"
  28. "github.com/gin-gonic/gin"
  29. "github.com/qichengzx/coordtransform"
  30. "github.com/tealeg/xlsx"
  31. "github.com/xormplus/xorm"
  32. )
  33. // @Summary 根据SQL执行得到数据集
  34. // @Tags getData
  35. // @Accept json
  36. // @Produce json
  37. // @Param sql query string true "sql"
  38. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  39. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  40. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  41. // @Router /data/getdata [POST]
  42. func GetData(c *gin.Context) {
  43. appG := app.Gin{C: c}
  44. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  45. fsion := gofasion.NewFasion(string(dataByte))
  46. sqlstr := fsion.Get("sql").ValueStr()
  47. offset := fsion.Get("offset").ValueDefaultInt(0)
  48. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  49. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  50. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  51. if err != nil {
  52. appG.Response(http.StatusOK, e.ERROR, err.Error())
  53. } else {
  54. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  55. }
  56. }
  57. func Testpartitions(c *gin.Context) {
  58. appG := app.Gin{C: c}
  59. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  60. fsion := gofasion.NewFasion(string(dataByte))
  61. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  62. user := fsion.Get("user").ValueStr() //获取新数据库用户
  63. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  64. host := fsion.Get("host").ValueStr() //获取新数据库名称
  65. port := fsion.Get("port").ValueStr() //获取新数据库名称
  66. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  67. if sqls == nil || err1 != nil {
  68. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  69. }
  70. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  71. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  72. mydb, err := sql.Open("mysql", connecting) //连接新连接
  73. if err != nil {
  74. println("err1", err.Error())
  75. }
  76. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  77. if err != nil {
  78. println("err2", err.Error())
  79. }
  80. mydb.Close()
  81. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  82. mydb, err = sql.Open("mysql", connecting)
  83. if err != nil {
  84. println("err3", err.Error())
  85. }
  86. defer mydb.Close()
  87. if err == nil {
  88. mydb.SetMaxOpenConns(10)
  89. mydb.SetMaxIdleConns(10)
  90. }
  91. errmsg := ""
  92. if err == nil {
  93. //tx ,_ :=mydb.Begin()
  94. for _, sqlstr := range sqlstrs {
  95. //println("sqlstr---",sqlstr)
  96. if sqlstr == "" {
  97. continue
  98. }
  99. _, err = mydb.Exec(sqlstr)
  100. if err != nil {
  101. println("err4", err.Error())
  102. errmsg = err.Error()
  103. //err1 :=tx.Rollback()
  104. }
  105. }
  106. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  107. //err =tx.Commit()
  108. }
  109. if errmsg == "" {
  110. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  111. } else {
  112. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  113. }
  114. }
  115. func TestData(c *gin.Context) {
  116. appG := app.Gin{C: c}
  117. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  118. fsion := gofasion.NewFasion(string(dataByte))
  119. sqlstr := fsion.Get("sql").ValueStr()
  120. token := ""
  121. if tempv, exists := c.Get("jwt_username"); exists {
  122. token = tempv.(string)
  123. }
  124. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  125. }
  126. // @Summary 根据APISQL表中SQL执行得到数据集
  127. // @Tags GetDataByName
  128. // @Accept json
  129. // @Produce json
  130. // @Param sqlname body string true "sqlname"
  131. // @Param offset body int true "offset"
  132. // @Param pagecount body int true "pagecount"
  133. // @Param returntype body string true "returntype"
  134. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  135. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  136. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  137. // @Router /data/GetDataByName [POST]
  138. func GetDataByName(c *gin.Context) {
  139. appG := app.Gin{C: c}
  140. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  141. fsion := gofasion.NewFasion(string(dataByte))
  142. sqlnamestr := fsion.Get("name").ValueStr()
  143. offset := fsion.Get("offset").ValueDefaultInt(0)
  144. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  145. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  146. tx := restful.Engine.NewSession()
  147. err := tx.Begin()
  148. defer func() {
  149. switch {
  150. case err != nil:
  151. logging.Error("tx.Begin 事务启动失败__error:", err)
  152. if tx != nil {
  153. tx.Rollback()
  154. }
  155. default:
  156. if tx != nil {
  157. err = tx.Commit()
  158. }
  159. }
  160. if tx != nil {
  161. tx.Close()
  162. }
  163. }()
  164. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  165. if sql != "" {
  166. s_params := make([]interface{}, 0)
  167. if fsion.HasKey("parammaps") {
  168. parammaps := fsion.Get("parammaps")
  169. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  170. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  171. }
  172. paramslist := strings.Split(p, ",")
  173. if len(paramslist) > 0 && p != "" {
  174. for _, value := range paramslist {
  175. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  176. if tempv, exists := c.Get("jwt_username"); exists {
  177. s_params = append(s_params, tempv.(string))
  178. } else {
  179. s_params = append(s_params, "")
  180. }
  181. } else {
  182. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  183. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  184. // tmrNameList := []string{}
  185. // for _, tmr := range tmrArray {
  186. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  187. // }
  188. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  189. // } else {
  190. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  191. // }
  192. }
  193. }
  194. }
  195. } else if fsion.HasKey("params") {
  196. params := fsion.Get("params").Array()
  197. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  198. for _, v_params := range params {
  199. s_params = append(s_params, v_params.ValueStr())
  200. }
  201. }
  202. if returntype == "xlsx" {
  203. var xlsxfile *xlsx.File
  204. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  205. //c.File("c:/dd.xlsx")
  206. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  207. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  208. c.Header("Content-Transfer-Encoding", "binary")
  209. _ = xlsxfile.Write(c.Writer)
  210. } else {
  211. if sqlnamestr == "getHomepageStr" {
  212. parammaps := fsion.Get("parammaps")
  213. pastureid := parammaps.Get("pastureid").ValueStr()
  214. var montimeList []float64
  215. var montime float64
  216. var wg sync.WaitGroup
  217. now := time.Now()
  218. for i := 0; i < 30; i++ {
  219. wg.Add(1)
  220. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  221. go func(nowstr string) {
  222. defer wg.Done()
  223. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  224. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  225. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  226. montimeList = append(montimeList, m)
  227. }(nowstr)
  228. }
  229. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  230. if err != nil {
  231. logging.Error("GetDataByName err: ", err)
  232. msg := geterrmsg(err.Error())
  233. appG.Response(http.StatusOK, e.ERROR, msg)
  234. }
  235. wg.Wait()
  236. for _, m := range montimeList {
  237. montime += m
  238. }
  239. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  240. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  241. return
  242. }
  243. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  244. if err != nil {
  245. logging.Error("GetDataByName err: ", err)
  246. msg := geterrmsg(err.Error())
  247. appG.Response(http.StatusOK, e.ERROR, msg)
  248. } else {
  249. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  250. }
  251. }
  252. } else {
  253. appG.Response(http.StatusOK, e.SUCCESS, nil)
  254. }
  255. }
  256. // @Summary 根据APISQL表中SQL执行得到数据集
  257. // @Tags GetDataByName
  258. // @Accept json
  259. // @Produce json
  260. // @Param sqlname body string true "sqlname"
  261. // @Param offset body int true "offset"
  262. // @Param pagecount body int true "pagecount"
  263. // @Param returntype body string true "returntype"
  264. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  265. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  266. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  267. // @Router /data/GetDataByName [POST]
  268. func GetDataBySqlIN(c *gin.Context) {
  269. appG := app.Gin{C: c}
  270. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  271. fsion := gofasion.NewFasion(string(dataByte))
  272. sqlnamestr := fsion.Get("name").ValueStr()
  273. offset := fsion.Get("offset").ValueDefaultInt(0)
  274. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  275. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  276. tx := restful.Engine.NewSession()
  277. err := tx.Begin()
  278. defer func() {
  279. switch {
  280. case err != nil:
  281. logging.Error("tx.Begin 事务启动失败__error:", err)
  282. if tx != nil {
  283. tx.Rollback()
  284. }
  285. default:
  286. if tx != nil {
  287. err = tx.Commit()
  288. }
  289. }
  290. if tx != nil {
  291. tx.Close()
  292. }
  293. }()
  294. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  295. if sql != "" {
  296. s_params := make([]interface{}, 0)
  297. if fsion.HasKey("parammaps") {
  298. parammaps := fsion.Get("parammaps")
  299. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  300. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  301. }
  302. paramslist := strings.Split(p, ",")
  303. if len(paramslist) > 0 && p != "" {
  304. for _, value := range paramslist {
  305. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  306. if tempv, exists := c.Get("jwt_username"); exists {
  307. s_params = append(s_params, tempv.(string))
  308. } else {
  309. s_params = append(s_params, "")
  310. }
  311. } else {
  312. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  313. }
  314. }
  315. }
  316. } else if fsion.HasKey("params") {
  317. params := fsion.Get("params").Array()
  318. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  319. for _, v_params := range params {
  320. s_params = append(s_params, v_params.ValueStr())
  321. }
  322. }
  323. if returntype == "xlsx" {
  324. var xlsxfile *xlsx.File
  325. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  326. //c.File("c:/dd.xlsx")
  327. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  328. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  329. c.Header("Content-Transfer-Encoding", "binary")
  330. _ = xlsxfile.Write(c.Writer)
  331. } else {
  332. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  333. if err != nil {
  334. logging.Error("GetDataByName err: ", err)
  335. msg := geterrmsg(err.Error())
  336. appG.Response(http.StatusOK, e.ERROR, msg)
  337. } else {
  338. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  339. }
  340. }
  341. } else {
  342. appG.Response(http.StatusOK, e.SUCCESS, nil)
  343. }
  344. }
  345. // 错误处理
  346. // 将报错信息处理成汉字
  347. func geterrmsg(errstr string) (msgstr string) {
  348. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  349. rs := []rune(errstr)
  350. if hzRegexp.MatchString(string(rs[0])) {
  351. msgstr = errstr
  352. return
  353. }
  354. if strings.Contains(errstr, "Duplicate entry") {
  355. strs := strings.Split(errstr, ` key '`)
  356. if len(strs) > 1 {
  357. if len(strs[len(strs)-1]) > 1 {
  358. errstr = "Duplicate entry :" + strs[len(strs)-1]
  359. }
  360. }
  361. }
  362. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  363. if err != nil {
  364. msgstr = errstr
  365. return
  366. }
  367. if msg == nil || len(msg) == 0 {
  368. var param []interface{}
  369. param = append(param, errstr, errstr)
  370. go func() {
  371. tx := restful.Engine.NewSession()
  372. err := tx.Begin()
  373. defer func() {
  374. switch {
  375. case err != nil:
  376. logging.Error("tx.Begin 事务启动失败__error:", err)
  377. if tx != nil {
  378. tx.Rollback()
  379. }
  380. default:
  381. if tx != nil {
  382. err = tx.Commit()
  383. }
  384. }
  385. if tx != nil {
  386. tx.Close()
  387. }
  388. }()
  389. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  390. if err != nil {
  391. logging.Error("insert into err_msg(err,msg) err", err)
  392. }
  393. }()
  394. msgstr = errstr
  395. } else {
  396. msgstr = msg[0]["msg"]
  397. }
  398. return
  399. }
  400. // @Summary 根据APISQL表中SQL执行得到数据集
  401. // @Tags GetDataByNameForm
  402. // @Accept json
  403. // @Produce json
  404. // @Param sqlname body json true "sqlname"
  405. // @Param offset query int true "offset"
  406. // @Param pagecount query int true "pagecount"
  407. // @Param returntype query string true "returntype"
  408. // @Param s formData json true "ss"
  409. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  410. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  411. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  412. // @Router /data/GetDataByNameForm [POST]
  413. func GetDataByNameForm(c *gin.Context) {
  414. appG := app.Gin{C: c}
  415. //sqlnamestr := c.PostForm("measureNumber")
  416. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  417. //fsion := gofasion.NewFasion(string(dataByte))
  418. //sqlnamestr := fsion.Get("name").ValueStr()
  419. //offset := fsion.Get("offset").ValueInt()
  420. //pagecount := fsion.Get("pagecount").ValueInt()
  421. //returntype := fsion.Get("returntype").ValueStr()
  422. //params := fsion.Get("params").Array()
  423. c.Request.ParseForm()
  424. params := c.Request.Form
  425. offset := 0
  426. pageSize_ := 0
  427. returntype := params.Get("page")
  428. if returntype == "" {
  429. returntype = "0"
  430. }
  431. if tempv, exists := c.Get("jwt_username"); exists {
  432. params.Set("JwtUserName", tempv.(string))
  433. } else {
  434. params.Set("JwtUserName", "")
  435. }
  436. sqlnamestr := params.Get("name")
  437. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  438. s_params := make([]interface{}, 0)
  439. if returntype == "1" {
  440. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  441. if error != nil {
  442. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  443. }
  444. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  445. if error != nil {
  446. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  447. }
  448. pageSize_ = pageSize
  449. offset = pageNum
  450. }
  451. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  452. paramslist := strings.Split(p, ",")
  453. if len(paramslist) > 0 && p != "" {
  454. for _, value := range paramslist {
  455. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  456. }
  457. }
  458. if sql != "" {
  459. if returntype == "xlsx" {
  460. var xlsxfile *xlsx.File
  461. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  462. c.Header("Content-Type", "application/octet-stream")
  463. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  464. c.Header("Content-Transfer-Encoding", "binary")
  465. _ = xlsxfile.Write(c.Writer)
  466. } else {
  467. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  468. if err != nil {
  469. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  470. } else {
  471. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  472. }
  473. }
  474. } else {
  475. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  476. }
  477. }
  478. // @Summary 递归获取所有
  479. // @Tags menu
  480. // @Accept json
  481. // @Produce json
  482. // @Param Ton query string true "Ton"
  483. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  484. // @Router /authdata/GetRoleMenus [GET]
  485. func GetRecuDataByName(c *gin.Context) {
  486. appG := app.Gin{C: c}
  487. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  488. fsion := gofasion.NewFasion(string(dataByte))
  489. sqlnamestr := fsion.Get("name").ValueStr()
  490. parentidname := fsion.Get("idname").ValueStr()
  491. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  492. params := make(map[string]interface{})
  493. s_params := make([]interface{}, 0)
  494. if fsion.HasKey("params") {
  495. for _, v_params := range fsion.Get("params").Array() {
  496. s_params = append(s_params, v_params.ValueStr())
  497. }
  498. params["params"] = s_params
  499. } else {
  500. jparams := fsion.Get("parammaps")
  501. paramslist := strings.Split(p, ",")
  502. if len(paramslist) > 0 && p != "" {
  503. for _, value := range paramslist {
  504. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  505. if tempv, exists := c.Get("jwt_username"); exists {
  506. params[value] = tempv.(string)
  507. } else {
  508. params[value] = ""
  509. }
  510. } else {
  511. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  512. }
  513. }
  514. }
  515. }
  516. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  517. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  518. if err != nil {
  519. appG.Response(http.StatusOK, e.ERROR, err.Error())
  520. }
  521. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  522. }
  523. // @Summary 根据APISQL表中SQL执行得到数据集
  524. // @Tags GetDataByNames
  525. // @Accept json
  526. // @Produce json
  527. // @RequestBody sqlname query string true "sqlname"
  528. // @Param offset query int true "offset"
  529. // @Param pagecount query int true "pagecount"
  530. // @Param returntype query string true "returntype"
  531. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  532. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  533. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  534. // @Router /data/GetDataByNames [POST]
  535. func GetDataByNames(c *gin.Context) {
  536. appG := app.Gin{C: c}
  537. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  538. fsion := gofasion.NewFasion(string(dataByte))
  539. sqlParams := fsion.Array()
  540. queryData := make(map[string]interface{})
  541. for _, v := range sqlParams {
  542. fsion2 := gofasion.NewFasion(v.Json())
  543. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  544. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  545. if sql == "" {
  546. errorm := make(map[string]interface{})
  547. errorm["code"] = e.ERROR
  548. errorm["message"] = "sql没找到"
  549. queryData[fsion2.Get("name").ValueStr()] = errorm
  550. continue
  551. } else if sql != "" {
  552. offset := fsion2.Get("offset").ValueInt()
  553. pagecount := fsion2.Get("pagecount").ValueInt()
  554. returntype := fsion2.Get("returntype").ValueStr()
  555. s_params := make([]interface{}, 0)
  556. if fsion2.HasKey("parammaps") {
  557. parammaps := fsion2.Get("parammaps")
  558. paramslist := strings.Split(p, ",")
  559. if len(paramslist) > 0 && p != "" {
  560. for _, value := range paramslist {
  561. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  562. if tempv, exists := c.Get("jwt_username"); exists {
  563. s_params = append(s_params, tempv.(string))
  564. } else {
  565. s_params = append(s_params, "")
  566. }
  567. } else {
  568. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  569. }
  570. }
  571. }
  572. } else if fsion2.HasKey("params") {
  573. params := fsion2.Get("params").Array()
  574. for _, v_params := range params {
  575. s_params = append(s_params, v_params.ValueStr())
  576. }
  577. }
  578. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  579. if err != nil {
  580. errorm := make(map[string]interface{})
  581. errorm["code"] = e.ERROR
  582. errorm["message"] = err.Error()
  583. queryData[fsion2.Get("name").ValueStr()] = errorm
  584. logging.Error("GetDataByNames err: ", err)
  585. continue
  586. } else {
  587. queryData[fsion2.Get("name").ValueStr()] = queryData1
  588. }
  589. }
  590. }
  591. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  592. }
  593. // @Summary 根据APISQL表中SQL执行得到数据集
  594. // @Tags PostDataByNameForm
  595. // @Accept json
  596. // @Produce json
  597. // @Param sqlname query string true "sqlname"
  598. // @Param offset query int true "offset"
  599. // @Param pagecount query int true "pagecount"
  600. // @Param returntype query string true "returntype"
  601. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  602. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  603. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  604. // @Router /data/PostDataByNameForm [POST]
  605. func PostDataByNameForm(c *gin.Context) {
  606. appG := app.Gin{C: c}
  607. c.Request.ParseForm()
  608. params := c.Request.Form
  609. sqlnamestr := params.Get("name")
  610. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  611. s_params := make([]interface{}, 0)
  612. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  613. paramslist := strings.Split(p, ",")
  614. if len(paramslist) > 0 {
  615. for _, value := range paramslist {
  616. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  617. }
  618. }
  619. if sql != "" {
  620. queryData, err := execDataBySql(sql, s_params)
  621. if err != nil {
  622. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  623. } else {
  624. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  625. }
  626. } else {
  627. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  628. }
  629. }
  630. // GetReportform 将数据集转换格式
  631. // @Tags PostDataByNameForm
  632. // @Accept json
  633. // @Produce json
  634. // @Param sqlname query string true "sqlname"
  635. // @Param offset query int true "offset"
  636. // @Param pagecount query int true "pagecount"
  637. // @Param returntype query string true "returntype"
  638. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  639. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  640. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  641. func GetReportform(c *gin.Context) {
  642. appG := app.Gin{C: c}
  643. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  644. fsion := gofasion.NewFasion(string(dataByte))
  645. sqlnamestr := fsion.Get("name").ValueStr()
  646. checked := fsion.Get("checked").ValueStr()
  647. offset := fsion.Get("offset").ValueDefaultInt(0)
  648. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  649. parammaps := fsion.Get("parammaps")
  650. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  651. mode := parammaps.Get("mode").ValueDefaultInt(0)
  652. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  653. tx := restful.Engine.NewSession()
  654. err := tx.Begin()
  655. defer func() {
  656. switch {
  657. case err != nil:
  658. if tx != nil {
  659. tx.Rollback()
  660. }
  661. default:
  662. if tx != nil {
  663. err = tx.Commit()
  664. }
  665. }
  666. if tx != nil {
  667. tx.Close()
  668. }
  669. }()
  670. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  671. if err != nil {
  672. appG.Response(http.StatusOK, e.ERROR, err.Error())
  673. } else {
  674. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  675. }
  676. }
  677. // GetUpkeepPlan 保养计划
  678. func GetUpkeepPlan(c *gin.Context) {
  679. appG := app.Gin{C: c}
  680. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  681. fsion := gofasion.NewFasion(string(dataByte))
  682. sqlnamestr := fsion.Get("name").ValueStr()
  683. offset := fsion.Get("offset").ValueDefaultInt(0)
  684. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  685. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  686. month := fsion.Get("month").ValueDefaultStr("map")
  687. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  688. tx := restful.Engine.NewSession()
  689. err := tx.Begin()
  690. defer func() {
  691. switch {
  692. case err != nil:
  693. if tx != nil {
  694. tx.Rollback()
  695. }
  696. default:
  697. if tx != nil {
  698. err = tx.Commit()
  699. }
  700. }
  701. if tx != nil {
  702. tx.Close()
  703. }
  704. }()
  705. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  706. if sql != "" {
  707. s_params := make([]interface{}, 0)
  708. if fsion.HasKey("parammaps") {
  709. parammaps := fsion.Get("parammaps")
  710. paramslist := strings.Split(p, ",")
  711. if len(paramslist) > 0 && p != "" {
  712. for _, value := range paramslist {
  713. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  714. if tempv, exists := c.Get("jwt_username"); exists {
  715. s_params = append(s_params, tempv.(string))
  716. } else {
  717. s_params = append(s_params, "")
  718. }
  719. } else {
  720. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  721. }
  722. }
  723. }
  724. } else if fsion.HasKey("params") {
  725. params := fsion.Get("params").Array()
  726. for _, v_params := range params {
  727. s_params = append(s_params, v_params.ValueStr())
  728. }
  729. }
  730. if returntype == "xlsx" {
  731. var xlsxfile *xlsx.File
  732. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  733. //c.File("c:/dd.xlsx")
  734. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  735. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  736. c.Header("Content-Transfer-Encoding", "binary")
  737. _ = xlsxfile.Write(c.Writer)
  738. } else {
  739. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  740. if err != nil {
  741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  742. } else {
  743. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  744. if v, ok := value["id"]; ok {
  745. //month = "2020-03"
  746. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  747. if seviceplans != nil {
  748. for _, va := range seviceplans { //根据保养计划获取保养单
  749. //day,_ :=strconv.Atoi(va["day"])
  750. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  751. //buk := make(map[string]map[string]string)
  752. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  753. jstr := ""
  754. if bu["plantime"][8:9] == "0" {
  755. jstr = "m" + bu["plantime"][9:]
  756. } else {
  757. jstr = "m" + bu["plantime"][8:]
  758. }
  759. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  760. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  761. } else {
  762. if bu["flowCompeleted"] >= "2" {
  763. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  764. } else {
  765. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  766. }
  767. }
  768. }
  769. }
  770. }
  771. }
  772. }
  773. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  774. }
  775. }
  776. } else {
  777. appG.Response(http.StatusOK, e.SUCCESS, nil)
  778. }
  779. }
  780. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  781. // todo 优化性能 children统一查询
  782. // @Tags PostDataByNameForm
  783. // @Accept json
  784. // @Produce json
  785. // @Param sqlname query string true "sqlname"
  786. // @Param offset query int true "offset"
  787. // @Param pagecount query int true "pagecount"
  788. // @Param returntype query string true "returntype"
  789. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  790. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  791. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  792. func GetArrList(c *gin.Context) {
  793. appG := app.Gin{C: c}
  794. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  795. fsion := gofasion.NewFasion(string(dataByte))
  796. sqlnamestr := fsion.Get("name").ValueStr()
  797. sqlnamestr1 := fsion.Get("name1").ValueStr()
  798. offset := fsion.Get("offset").ValueDefaultInt(0)
  799. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  800. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  801. month := fsion.Get("month").ValueDefaultStr("map")
  802. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  803. tx := restful.Engine.NewSession()
  804. err := tx.Begin()
  805. defer func() {
  806. switch {
  807. case err != nil:
  808. if tx != nil {
  809. tx.Rollback()
  810. }
  811. default:
  812. if tx != nil {
  813. err = tx.Commit()
  814. }
  815. }
  816. if tx != nil {
  817. tx.Close()
  818. }
  819. }()
  820. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  821. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  822. if sql != "" {
  823. s_params := make([]interface{}, 0)
  824. if fsion.HasKey("parammaps") {
  825. parammaps := fsion.Get("parammaps")
  826. paramslist := strings.Split(p, ",")
  827. if len(paramslist) > 0 && p != "" {
  828. for _, value := range paramslist {
  829. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  830. if tempv, exists := c.Get("jwt_username"); exists {
  831. s_params = append(s_params, tempv.(string))
  832. } else {
  833. s_params = append(s_params, "")
  834. }
  835. } else {
  836. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  837. }
  838. }
  839. }
  840. }
  841. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  842. if err != nil {
  843. appG.Response(http.StatusOK, e.ERROR, err.Error())
  844. } else {
  845. paramslist1 := strings.Split(p1, ",")
  846. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  847. s_params1 := make([]interface{}, 0)
  848. if len(paramslist1) > 0 && p1 != "" {
  849. for _, v := range paramslist1 {
  850. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  851. }
  852. }
  853. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  854. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  855. }
  856. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  857. }
  858. } else {
  859. appG.Response(http.StatusOK, e.SUCCESS, nil)
  860. }
  861. }
  862. func GetAccount(c *gin.Context) {
  863. appG := app.Gin{C: c}
  864. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  865. fsion := gofasion.NewFasion(string(dataByte))
  866. sqlnamestr := fsion.Get("name").ValueStr()
  867. offset := fsion.Get("offset").ValueDefaultInt(0)
  868. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  869. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  870. tx := restful.Engine.NewSession()
  871. err := tx.Begin()
  872. defer func() {
  873. switch {
  874. case err != nil:
  875. logging.Error("tx.Begin 事务启动失败__error:", err)
  876. if tx != nil {
  877. tx.Rollback()
  878. }
  879. default:
  880. if tx != nil {
  881. err = tx.Commit()
  882. }
  883. }
  884. if tx != nil {
  885. tx.Close()
  886. }
  887. }()
  888. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  889. if sql != "" {
  890. s_params := make([]interface{}, 0)
  891. if fsion.HasKey("parammaps") {
  892. parammaps := fsion.Get("parammaps")
  893. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  894. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  895. }
  896. paramslist := strings.Split(p, ",")
  897. if len(paramslist) > 0 && p != "" {
  898. for _, value := range paramslist {
  899. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  900. if tempv, exists := c.Get("jwt_username"); exists {
  901. s_params = append(s_params, tempv.(string))
  902. } else {
  903. s_params = append(s_params, "")
  904. }
  905. } else {
  906. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  907. }
  908. }
  909. }
  910. } else if fsion.HasKey("params") {
  911. params := fsion.Get("params").Array()
  912. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  913. for _, v_params := range params {
  914. s_params = append(s_params, v_params.ValueStr())
  915. }
  916. }
  917. if returntype == "xlsx" {
  918. var xlsxfile *xlsx.File
  919. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  920. //c.File("c:/dd.xlsx")
  921. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  922. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  923. c.Header("Content-Transfer-Encoding", "binary")
  924. _ = xlsxfile.Write(c.Writer)
  925. } else {
  926. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  927. if err != nil {
  928. logging.Error("GetDataByName err: ", err)
  929. msg := geterrmsg(err.Error())
  930. appG.Response(http.StatusOK, e.ERROR, msg)
  931. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  932. } else {
  933. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  934. }
  935. }
  936. } else {
  937. appG.Response(http.StatusOK, e.SUCCESS, nil)
  938. }
  939. }
  940. // PostDataByName 根据APISQL表中SQL执行得到数据集
  941. // @Accept json
  942. // @Produce json
  943. // @Param sqlname query string true "sqlname"
  944. // @Param offset query int true "offset"
  945. // @Param pagecount query int true "pagecount"
  946. // @Param returntype query string true "returntype"
  947. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  948. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  949. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  950. // @Router /data/PostDataByName [POST]
  951. func PostDataByName(c *gin.Context) {
  952. appG := app.Gin{C: c}
  953. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  954. fsion := gofasion.NewFasion(string(dataByte))
  955. var err error
  956. queryData, err := module.PostDataByName(c, fsion)
  957. if err != nil {
  958. appG.Response(http.StatusOK, e.ERROR, err)
  959. return
  960. }
  961. var (
  962. keyWord string
  963. )
  964. switch fsion.Get("name").ValueStr() {
  965. case "insertFeedclass":
  966. keyWord = "feed"
  967. err = module.GroupCategorySync(keyWord, fsion)
  968. case "deleteFeedclass":
  969. keyWord = "feed_delete"
  970. err = module.GroupCategoryDelete(keyWord, fsion)
  971. case "insertCowclass":
  972. keyWord = "cow"
  973. err = module.GroupCategorySync(keyWord, fsion)
  974. case "deleteCowclass":
  975. keyWord = "cow_delete"
  976. err = module.GroupCategoryDelete(keyWord, fsion)
  977. default:
  978. }
  979. if err != nil {
  980. logging.Error(keyWord, err)
  981. }
  982. if queryData != nil {
  983. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  984. return
  985. }
  986. appG.Response(http.StatusOK, e.SUCCESS, nil)
  987. }
  988. //人脸识别/格润富德接口
  989. func GetRJSBData(c *gin.Context) {
  990. appG := app.Gin{C: c}
  991. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  992. fsion := gofasion.NewFasion(string(dataByte))
  993. sqlnamestr := fsion.Get("name").ValueStr()
  994. sqlnamestr1 := fsion.Get("name1").ValueStr()
  995. offset := fsion.Get("offset").ValueDefaultInt(0)
  996. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  997. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  998. month := fsion.Get("month").ValueDefaultStr("map")
  999. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1000. tx := restful.Engine.NewSession()
  1001. err := tx.Begin()
  1002. defer func() {
  1003. switch {
  1004. case err != nil:
  1005. if tx != nil {
  1006. tx.Rollback()
  1007. }
  1008. default:
  1009. if tx != nil {
  1010. err = tx.Commit()
  1011. }
  1012. }
  1013. if tx != nil {
  1014. tx.Close()
  1015. }
  1016. }()
  1017. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1018. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1019. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1020. if sql != "" {
  1021. s_params := make([]interface{}, 0)
  1022. if fsion.HasKey("parammaps") {
  1023. parammaps := fsion.Get("parammaps")
  1024. paramslist := strings.Split(p, ",")
  1025. if len(paramslist) > 0 && p != "" {
  1026. for _, value := range paramslist {
  1027. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1028. if tempv, exists := c.Get("jwt_username"); exists {
  1029. s_params = append(s_params, tempv.(string))
  1030. } else {
  1031. s_params = append(s_params, "")
  1032. }
  1033. } else {
  1034. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1035. }
  1036. }
  1037. }
  1038. }
  1039. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1040. if err != nil {
  1041. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1042. } else {
  1043. paramslist1 := strings.Split(p1, ",")
  1044. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1045. s_params1 := make([]interface{}, 0)
  1046. if len(paramslist1) > 0 && p1 != "" {
  1047. for _, v := range paramslist1 {
  1048. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1049. }
  1050. }
  1051. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1052. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1053. }
  1054. var wg sync.WaitGroup
  1055. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1056. wg.Add(1)
  1057. go func(value map[string]interface{}) {
  1058. defer wg.Done()
  1059. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1060. }(value)
  1061. }
  1062. wg.Wait()
  1063. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1064. }
  1065. } else {
  1066. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1067. }
  1068. }
  1069. func PostRJSBData(c *gin.Context) {
  1070. appG := app.Gin{C: c}
  1071. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1072. fsion := gofasion.NewFasion(string(dataByte))
  1073. logging.Info("PostRJSBData err: ", string(dataByte))
  1074. s_params := make([]interface{}, 0)
  1075. tx := restful.Engine.NewSession()
  1076. err := tx.Begin()
  1077. defer func() {
  1078. switch {
  1079. case err != nil:
  1080. if tx != nil {
  1081. tx.Rollback()
  1082. }
  1083. default:
  1084. if tx != nil {
  1085. err = tx.Commit()
  1086. }
  1087. }
  1088. if tx != nil {
  1089. tx.Close()
  1090. }
  1091. }()
  1092. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1093. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1094. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1095. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1096. if !fsion.HasKey("parammaps") {
  1097. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1098. return
  1099. }
  1100. parammaps := fsion.Get("parammaps")
  1101. paramslist := strings.Split(p, ",")
  1102. if len(paramslist) > 0 && p != "" {
  1103. for _, value := range paramslist {
  1104. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1105. }
  1106. }
  1107. _, err = tx.SQL(sql, s_params...).Execute()
  1108. if err != nil {
  1109. logging.Error("PostRJSBData err: ", err)
  1110. msg := geterrmsg(err.Error())
  1111. // appG.Response(http.StatusOK, e.ERROR, msg)
  1112. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1113. return
  1114. }
  1115. s_params = make([]interface{}, 0)
  1116. paramslist = strings.Split(p1, ",")
  1117. if len(paramslist) > 0 && p1 != "" {
  1118. for _, value := range paramslist {
  1119. // if value == "ID" {
  1120. // id := parammaps.Get("ID").ValueStr()
  1121. // pastureid := parammaps.Get("pastureid").ValueStr()
  1122. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1123. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1124. // if err != nil {
  1125. // logging.Error("PostRJSBData err: ", err)
  1126. // msg := geterrmsg(err.Error())
  1127. // appG.Response(http.StatusOK, e.ERROR, msg)
  1128. // return
  1129. // }
  1130. // for _, item := range datalist {
  1131. // id = item["id"]
  1132. // }
  1133. // s_params = append(s_params, id)
  1134. // } else {
  1135. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1136. // }
  1137. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1138. }
  1139. }
  1140. _, err = tx.SQL(sql1, s_params...).Execute()
  1141. if err != nil {
  1142. logging.Error("PostRJSBData1 err: ", err)
  1143. msg := geterrmsg(err.Error())
  1144. appG.Response(http.StatusOK, e.ERROR, msg)
  1145. return
  1146. }
  1147. s_params = make([]interface{}, 0)
  1148. paramslist = strings.Split(p2, ",")
  1149. if len(paramslist) > 0 && p2 != "" {
  1150. for _, value := range paramslist {
  1151. if value == "ID" {
  1152. id := parammaps.Get("ID").ValueStr()
  1153. pastureid := parammaps.Get("pastureid").ValueStr()
  1154. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1155. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1156. if err != nil {
  1157. logging.Error("PostRJSBData err: ", err)
  1158. msg := geterrmsg(err.Error())
  1159. appG.Response(http.StatusOK, e.ERROR, msg)
  1160. return
  1161. }
  1162. for _, item := range datalist {
  1163. id = item["id"]
  1164. }
  1165. s_params = append(s_params, id)
  1166. } else {
  1167. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1168. }
  1169. }
  1170. }
  1171. _, err = tx.SQL(sql2, s_params...).Execute()
  1172. if err != nil {
  1173. logging.Error("PostRJSBData2 err: ", err)
  1174. msg := geterrmsg(err.Error())
  1175. appG.Response(http.StatusOK, e.ERROR, msg)
  1176. return
  1177. }
  1178. s_params = make([]interface{}, 0)
  1179. paramslist = strings.Split(p3, ",")
  1180. if len(paramslist) > 0 && p3 != "" {
  1181. for _, value := range paramslist {
  1182. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1183. }
  1184. }
  1185. _, err = tx.SQL(sql3, s_params...).Execute()
  1186. if err != nil {
  1187. logging.Error("PostRJSBData3 err: ", err)
  1188. msg := geterrmsg(err.Error())
  1189. appG.Response(http.StatusOK, e.ERROR, msg)
  1190. return
  1191. }
  1192. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1193. }
  1194. func PostRJSBDatas(c *gin.Context) {
  1195. appG := app.Gin{C: c}
  1196. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1197. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1198. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1199. tx := restful.Engine.NewSession()
  1200. err := tx.Begin()
  1201. defer func() {
  1202. switch {
  1203. case err != nil:
  1204. if tx != nil {
  1205. tx.Rollback()
  1206. }
  1207. default:
  1208. if tx != nil {
  1209. err = tx.Commit()
  1210. }
  1211. }
  1212. if tx != nil {
  1213. tx.Close()
  1214. }
  1215. }()
  1216. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1217. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1218. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1219. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1220. for _, fsion := range fsions {
  1221. if !fsion.HasKey("parammaps") {
  1222. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1223. return
  1224. }
  1225. parammaps := fsion.Get("parammaps")
  1226. ID := parammaps.Get("ID").ValueStr()
  1227. if ID == "" {
  1228. continue
  1229. }
  1230. s_params := make([]interface{}, 0)
  1231. paramslist := strings.Split(p, ",")
  1232. if len(paramslist) > 0 && p != "" {
  1233. for _, value := range paramslist {
  1234. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1235. }
  1236. }
  1237. _, err = tx.SQL(sql, s_params...).Execute()
  1238. if err != nil {
  1239. logging.Error("PostRJSBData err: ", err)
  1240. msg := geterrmsg(err.Error())
  1241. // appG.Response(http.StatusOK, e.ERROR, msg)
  1242. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1243. return
  1244. }
  1245. s_params = make([]interface{}, 0)
  1246. paramslist = strings.Split(p1, ",")
  1247. if len(paramslist) > 0 && p1 != "" {
  1248. for _, value := range paramslist {
  1249. // if value == "ID" {
  1250. // id := parammaps.Get("ID").ValueStr()
  1251. // pastureid := parammaps.Get("pastureid").ValueStr()
  1252. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1253. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1254. // if err != nil {
  1255. // logging.Error("PostRJSBData err: ", err)
  1256. // msg := geterrmsg(err.Error())
  1257. // appG.Response(http.StatusOK, e.ERROR, msg)
  1258. // return
  1259. // }
  1260. // for _, item := range datalist {
  1261. // id = item["id"]
  1262. // }
  1263. // s_params = append(s_params, id)
  1264. // } else {
  1265. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1266. // }
  1267. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1268. }
  1269. }
  1270. _, err = tx.SQL(sql1, s_params...).Execute()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData1 err: ", err)
  1273. msg := geterrmsg(err.Error())
  1274. appG.Response(http.StatusOK, e.ERROR, msg)
  1275. return
  1276. }
  1277. s_params = make([]interface{}, 0)
  1278. paramslist = strings.Split(p2, ",")
  1279. if len(paramslist) > 0 && p2 != "" {
  1280. for _, value := range paramslist {
  1281. if value == "ID" {
  1282. id := parammaps.Get("ID").ValueStr()
  1283. pastureid := parammaps.Get("pastureid").ValueStr()
  1284. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1285. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1286. if err != nil {
  1287. logging.Error("PostRJSBData err: ", err)
  1288. msg := geterrmsg(err.Error())
  1289. appG.Response(http.StatusOK, e.ERROR, msg)
  1290. return
  1291. }
  1292. for _, item := range datalist {
  1293. id = item["id"]
  1294. }
  1295. s_params = append(s_params, id)
  1296. } else {
  1297. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1298. }
  1299. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1300. }
  1301. }
  1302. _, err = tx.SQL(sql2, s_params...).Execute()
  1303. if err != nil {
  1304. logging.Error("PostRJSBData2 err: ", err)
  1305. msg := geterrmsg(err.Error())
  1306. appG.Response(http.StatusOK, e.ERROR, msg)
  1307. return
  1308. }
  1309. s_params = make([]interface{}, 0)
  1310. paramslist = strings.Split(p3, ",")
  1311. if len(paramslist) > 0 && p3 != "" {
  1312. for _, value := range paramslist {
  1313. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1314. }
  1315. }
  1316. _, err = tx.SQL(sql3, s_params...).Execute()
  1317. if err != nil {
  1318. logging.Error("PostRJSBData3 err: ", err)
  1319. msg := geterrmsg(err.Error())
  1320. appG.Response(http.StatusOK, e.ERROR, msg)
  1321. return
  1322. }
  1323. }
  1324. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1325. }
  1326. // @Summary 根据APISQL表中SQL执行得到数据集
  1327. // @Tags ExecDataByConfig
  1328. // @Accept json
  1329. // @Produce json
  1330. // @Param sqlname query string true "sqlname"
  1331. // @Param offset query int true "offset"
  1332. // @Param pagecount query int true "pagecount"
  1333. // @Param returntype query string true "returntype"
  1334. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1335. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1336. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1337. // @Router /data/PostDataByName [POST]
  1338. func ExecDataByConfig(c *gin.Context) {
  1339. appG := app.Gin{C: c}
  1340. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1341. tempval_ := make(map[string]interface{})
  1342. tempCommon := make(map[string]interface{})
  1343. tempval := make([]map[string]interface{}, 0)
  1344. err := json.Unmarshal(dataByte, &tempval_)
  1345. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1346. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1347. if err != nil {
  1348. } else {
  1349. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1350. tempCommon = v
  1351. }
  1352. if v, ok := tempval_["data"].([]interface{}); ok {
  1353. for _, Tvalue := range v {
  1354. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1355. tempval = append(tempval, v1)
  1356. }
  1357. }
  1358. }
  1359. tx := restful.Engine.NewSession()
  1360. err := tx.Begin()
  1361. if err != nil {
  1362. logging.Error("tx.Begin 事务启动失败__error:", err)
  1363. }
  1364. defer func() {
  1365. switch {
  1366. case err != nil:
  1367. if tx != nil {
  1368. tx.Rollback()
  1369. }
  1370. default:
  1371. if tx != nil {
  1372. err = tx.Commit()
  1373. }
  1374. }
  1375. if tx != nil {
  1376. tx.Close()
  1377. }
  1378. }()
  1379. if err == nil {
  1380. if tempv, exists := c.Get("jwt_username"); exists {
  1381. tempCommon["jwt_username"] = tempv.(string)
  1382. }
  1383. for _, paramvalue := range tempval {
  1384. fmt.Println(paramvalue["name"])
  1385. if paramvalue["name"].(string) == "updateBigFP" {
  1386. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1387. if err != nil {
  1388. msg := geterrmsg(err.Error())
  1389. appG.Response(http.StatusOK, e.ERROR, msg)
  1390. return
  1391. }
  1392. }
  1393. }
  1394. for _, paramvalue := range tempval {
  1395. if _, ok := paramvalue["resultname"]; !ok {
  1396. paramvalue["resultname"] = paramvalue["name"]
  1397. }
  1398. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1399. if err != nil {
  1400. logging.Error("ExecDataParam error:", err)
  1401. break
  1402. }
  1403. if paramvalue["name"].(string) == "createdownloadedplan" {
  1404. checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1405. }
  1406. }
  1407. if err == nil {
  1408. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1409. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1410. } else {
  1411. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1412. }
  1413. } else {
  1414. msg := geterrmsg(err.Error())
  1415. appG.Response(http.StatusOK, e.ERROR, msg)
  1416. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1417. }
  1418. }
  1419. }
  1420. if err != nil {
  1421. msg := geterrmsg(err.Error())
  1422. appG.Response(http.StatusOK, e.ERROR, msg)
  1423. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1424. }
  1425. }
  1426. func interfacetostring(val interface{}) string {
  1427. switch val.(type) {
  1428. case string:
  1429. ss := val.(string)
  1430. return ss
  1431. break
  1432. case int:
  1433. ss := val.(int)
  1434. return strconv.Itoa(ss)
  1435. break
  1436. case int64:
  1437. ss := val.(int64)
  1438. return strconv.FormatInt(ss, 10)
  1439. break
  1440. case float64:
  1441. ss := val.(float64)
  1442. return strconv.FormatFloat(ss, 'E', -1, 32)
  1443. break
  1444. }
  1445. return ""
  1446. }
  1447. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1448. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1449. tempstrb := strings.IndexAny(valuestring, "@")
  1450. tempstre := strings.IndexAny(valuestring, ".")
  1451. if tempstrb > -1 && tempstre > -1 {
  1452. for _, ParamMapList := range ParamMap {
  1453. if v, ok := ParamMapList["resultname"]; ok {
  1454. if v == valuestring[tempstrb+1:tempstre] {
  1455. if v1, ok := ParamMapList["resultmaps"]; ok {
  1456. if newA, ok := v1.([]map[string]interface{}); ok {
  1457. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1458. } else if newA, ok := v1.(map[string]interface{}); ok {
  1459. return interfacetostring(newA[valuestring[tempstre+1:]])
  1460. }
  1461. }
  1462. }
  1463. }
  1464. }
  1465. } else {
  1466. return valuestring
  1467. }
  1468. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1469. return strconv.FormatInt(int64(valuestring), 10)
  1470. }
  1471. return ""
  1472. }
  1473. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1474. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1475. tempstrb := strings.IndexAny(valuestring, "@")
  1476. tempstre := strings.IndexAny(valuestring, ".")
  1477. if tempstrb > -1 && tempstre > -1 {
  1478. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1479. if s, ok := v.(string); ok {
  1480. return s
  1481. } else if s, ok := v.(float64); ok {
  1482. return strconv.FormatFloat(s, 'f', -1, 64)
  1483. // return strconv.FormatInt(int64(s), 10)
  1484. }
  1485. }
  1486. }
  1487. }
  1488. return ""
  1489. }
  1490. func ExecDataParam(fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, ParentParamMap map[string]interface{}, sameParamMap []map[string]interface{}, tx *xorm.Session) ([]map[string]interface{}, error) {
  1491. sqlname := fasion["name"].(string)
  1492. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1493. if v, ok := fasion["type"]; ok {
  1494. sqltype = v.(string)
  1495. }
  1496. sql := ""
  1497. p := ""
  1498. s_params := make([]interface{}, 0)
  1499. if sqltype != "" {
  1500. sql, p = restful.GetSqlByName(sqlname, tx)
  1501. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1502. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1503. paramslist := strings.Split(p, ",")
  1504. if len(paramslist) > 0 && p != "" {
  1505. for _, value := range paramslist {
  1506. ss := ""
  1507. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1508. ids, err := setting.SnowIds.NextId()
  1509. if err != nil {
  1510. ids = time.Now().UnixNano()
  1511. logging.Info("create SnowIds err", err)
  1512. }
  1513. s_params = append(s_params, ids)
  1514. } else {
  1515. if ss == "" && CommonParamMap != nil {
  1516. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1517. ss = valuestring
  1518. tempstrb := strings.IndexAny(valuestring, "@")
  1519. tempstre := strings.IndexAny(valuestring, ".")
  1520. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1521. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1522. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1523. }
  1524. } else {
  1525. ss = ""
  1526. }
  1527. }
  1528. }
  1529. if ss == "" && ParentParamMap != nil {
  1530. ss = getParamValue_(v, value, ParentParamMap)
  1531. }
  1532. if ss == "" && sameParamMap != nil {
  1533. ss = getParamValue(v, value, sameParamMap)
  1534. }
  1535. if ss == "" && ParamMap != nil {
  1536. ss = getParamValue(v, value, ParamMap)
  1537. }
  1538. s_params = append(s_params, ss)
  1539. }
  1540. }
  1541. }
  1542. }
  1543. }
  1544. if sql == "" {
  1545. sqltype = ""
  1546. }
  1547. if sqltype == "s1" {
  1548. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1549. if v, ok := tempValParam.(map[string]interface{}); ok {
  1550. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1551. }
  1552. if err != nil {
  1553. return nil, err
  1554. }
  1555. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1556. if err != nil {
  1557. return nil, err
  1558. }
  1559. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1560. } else if sqltype == "sm" {
  1561. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1562. if v, ok := tempValParam.(map[string]interface{}); ok {
  1563. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1564. } else {
  1565. }
  1566. if err != nil {
  1567. return nil, err
  1568. }
  1569. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1570. if err != nil {
  1571. return nil, err
  1572. }
  1573. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1574. } else if sqltype == "v" {
  1575. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1576. if v, ok := tempValParam.(map[string]interface{}); ok {
  1577. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1578. } else {
  1579. }
  1580. if err != nil {
  1581. return nil, err
  1582. }
  1583. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1584. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1585. }
  1586. } else if sqltype == "e" {
  1587. tempVal_arrary := make([]map[string]interface{}, 0)
  1588. tempVal_map := make(map[string]interface{})
  1589. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1590. if err == nil {
  1591. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1592. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1593. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1594. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1595. return tempVal_arrary, err
  1596. }
  1597. return nil, err
  1598. } else {
  1599. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1600. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1601. if err != nil {
  1602. return nil, err
  1603. }
  1604. return nil, err
  1605. }
  1606. }
  1607. return nil, nil
  1608. }
  1609. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1610. var err error
  1611. subarray, ok := fasion["children"]
  1612. if ok {
  1613. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1614. tempVal_arrary := make([]map[string]interface{}, 0)
  1615. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1616. tempVal_ := make(map[string]interface{})
  1617. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1618. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1619. } else {
  1620. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1621. }
  1622. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1623. if err != nil {
  1624. return err
  1625. }
  1626. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1627. }
  1628. v.(map[string]interface{})["children"] = tempVal_arrary
  1629. }
  1630. }
  1631. return nil
  1632. }
  1633. // @Summary 删除图片
  1634. // @Tags RemovePicByName
  1635. // @Accept json
  1636. // @Produce json
  1637. // @Param sqlname query string true "sqlname"
  1638. // @Param offset query int true "offset"
  1639. // @Param pagecount query int true "pagecount"
  1640. // @Param returntype query string true "returntype"
  1641. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1642. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1643. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1644. // @Router /data/PostDataByName [POST]
  1645. func RemovePicByName(c *gin.Context) {
  1646. logging.Info("RemovePicByName ", c.Keys)
  1647. appG := app.Gin{C: c}
  1648. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1649. fsion := gofasion.NewFasion(string(dataByte))
  1650. sqlnamestr := fsion.Get("name").ValueStr()
  1651. picname := fsion.Get("picname").ValueStr()
  1652. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1653. params := fsion.Get("params").Array()
  1654. s_params := make([]interface{}, 0)
  1655. for _, v_params := range params {
  1656. s_params = append(s_params, v_params.ValueStr())
  1657. }
  1658. if sql != "" {
  1659. queryData, err := execDataBySql(sql, s_params)
  1660. if picname != "" {
  1661. // Destination
  1662. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1663. err := os.Remove(distPath) //删除文件test.txt
  1664. if err != nil {
  1665. //如果删除失败则输出 file remove Error!
  1666. fmt.Println("file remove Error!")
  1667. //输出错误详细信息
  1668. fmt.Printf("%s", err)
  1669. } else {
  1670. //如果删除成功则输出 file remove OK!
  1671. fmt.Print("file remove OK!")
  1672. }
  1673. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1674. err = os.Remove(distPath) //删除文件test.txt
  1675. if err != nil {
  1676. //如果删除失败则输出 file remove Error!
  1677. fmt.Println("file remove Error!")
  1678. //输出错误详细信息
  1679. fmt.Printf("%s", err)
  1680. } else {
  1681. //如果删除成功则输出 file remove OK!
  1682. fmt.Print("file remove OK!")
  1683. }
  1684. }
  1685. if err != nil {
  1686. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1687. } else {
  1688. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1689. }
  1690. } else {
  1691. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1692. }
  1693. }
  1694. // @Summary 删除文件
  1695. // @Tags RemoveFileByName
  1696. // @Accept json
  1697. // @Produce json
  1698. // @Param sqlname query string true "sqlname"
  1699. // @Param offset query int true "offset"
  1700. // @Param pagecount query int true "pagecount"
  1701. // @Param returntype query string true "returntype"
  1702. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1703. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1704. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1705. // @Router /data/PostDataByName [POST]
  1706. func RemoveFileByName(c *gin.Context) {
  1707. appG := app.Gin{C: c}
  1708. id := c.Param("id")
  1709. logging.Info("DownloadFile ", c.Keys, id)
  1710. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1711. if eqdoc == nil {
  1712. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1713. return
  1714. }
  1715. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1716. err = os.Remove(distPath) //删除文件test.txt
  1717. if err != nil {
  1718. //如果删除失败则输出 file remove Error!
  1719. fmt.Println("file remove Error!")
  1720. //输出错误详细信息
  1721. fmt.Printf("%s", err)
  1722. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1723. return
  1724. }
  1725. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1726. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1727. }
  1728. // @Summary 根据APISQL表中SQL执行得到数据集
  1729. // @Tags PostDataByName
  1730. // @Accept json
  1731. // @Produce json
  1732. // @Param sqlname query string true "sqlname"
  1733. // @Param offset query int true "offset"
  1734. // @Param pagecount query int true "pagecount"
  1735. // @Param returntype query string true "returntype"
  1736. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1737. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1738. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1739. // @Router /data/PostDataByName [POST]
  1740. func UpdateDataRelation(c *gin.Context) {
  1741. appG := app.Gin{C: c}
  1742. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1743. fsion := gofasion.NewFasion(string(dataByte))
  1744. tablename := fsion.Get("name").ValueStr()
  1745. dataname := fsion.Get("dataname").ValueStr()
  1746. datavalue := fsion.Get("datavalue").ValueStr()
  1747. valuename := fsion.Get("valuename").ValueStr()
  1748. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1749. values := fsion.Get("values").Array()
  1750. tx := restful.Engine.NewSession()
  1751. err := tx.Begin()
  1752. defer func() {
  1753. switch {
  1754. case err != nil:
  1755. if tx != nil {
  1756. tx.Rollback()
  1757. }
  1758. default:
  1759. if tx != nil {
  1760. err = tx.Commit()
  1761. }
  1762. }
  1763. if tx != nil {
  1764. tx.Close()
  1765. }
  1766. }()
  1767. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1768. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1769. d_params := make([]interface{}, 4)
  1770. d_params[0] = datavalue
  1771. s_params := ""
  1772. for _, v_values := range values {
  1773. d_params[1] = v_values.ValueStr()
  1774. if s_params == "" {
  1775. s_params = v_values.ValueStr()
  1776. } else {
  1777. s_params = s_params + "," + v_values.ValueStr()
  1778. }
  1779. d_params[2] = d_params[1]
  1780. d_params[3] = d_params[0]
  1781. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1782. if err != nil {
  1783. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1784. break
  1785. }
  1786. }
  1787. if s_params != "" {
  1788. deleteSqlstr := "delete from " + tablename + " " +
  1789. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1790. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1791. if err != nil {
  1792. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1793. } else if err == nil {
  1794. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1795. }
  1796. } else {
  1797. deleteSqlstr := "delete from " + tablename + " " +
  1798. " where " + dataname + " = " + datavalue
  1799. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1800. if err != nil {
  1801. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1802. } else if err == nil {
  1803. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1804. }
  1805. }
  1806. }
  1807. // @Summary 根据APISQL表中SQL执行得到数据集
  1808. // @Tags PostDatasByName
  1809. // @Accept json
  1810. // @Produce json
  1811. // @Param sqlname query string true "sqlname"
  1812. // @Param offset query int true "offset"
  1813. // @Param pagecount query int true "pagecount"
  1814. // @Param returntype query string true "returntype"
  1815. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1816. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1817. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1818. // @Router /data/PostDatasByName [POST]
  1819. func PostDataByNames(c *gin.Context) {
  1820. appG := app.Gin{C: c}
  1821. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1822. fsion := gofasion.NewFasion(string(dataByte))
  1823. sqlParams := fsion.Get("array").Array()
  1824. queryData := make(map[string]interface{})
  1825. for _, v := range sqlParams {
  1826. fsion2 := gofasion.NewFasion(v.Json())
  1827. ss := fsion2.Get("name")
  1828. aa := fsion2.Get("params")
  1829. fmt.Println(ss, aa)
  1830. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1831. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1832. if sql == "" {
  1833. errorm := make(map[string]interface{})
  1834. errorm["code"] = e.ERROR
  1835. errorm["message"] = "sql没有找到"
  1836. errorm["param"] = ""
  1837. queryData[fsion2.Get("name").ValueStr()] = errorm
  1838. continue
  1839. } else if sql != "" {
  1840. s_params := make([]interface{}, 0)
  1841. if fsion2.HasKey("parammaps") {
  1842. parammaps := fsion2.Get("parammaps")
  1843. paramslist := strings.Split(p, ",")
  1844. if len(paramslist) > 0 && p != "" {
  1845. for _, value := range paramslist {
  1846. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1847. if tempv, exists := c.Get("jwt_username"); exists {
  1848. s_params = append(s_params, tempv.(string))
  1849. } else {
  1850. s_params = append(s_params, "")
  1851. }
  1852. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1853. ids, err := setting.SnowIds.NextId()
  1854. if err != nil {
  1855. ids = time.Now().UnixNano()
  1856. logging.Info("create SnowIds err", err)
  1857. }
  1858. s_params = append(s_params, ids)
  1859. } else {
  1860. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1861. }
  1862. }
  1863. }
  1864. } else if fsion2.HasKey("params") {
  1865. params := fsion2.Get("params").Array()
  1866. //ids,err := setting.SnowIds.NextId()
  1867. //if err !=nil{
  1868. // ids = time.Now().UnixNano()
  1869. // logging.Info("create SnowIds err",err)
  1870. //}
  1871. //s_params = append(s_params, ids)
  1872. for _, v_params := range params {
  1873. s_params = append(s_params, v_params.ValueStr())
  1874. }
  1875. }
  1876. _, err := execDataBySql(sql, s_params)
  1877. if err != nil {
  1878. logging.Error("PostDataByName err: ", err)
  1879. errorm := make(map[string]interface{})
  1880. errorm["code"] = e.ERROR
  1881. errorm["message"] = err.Error()
  1882. errorm["param"] = s_params
  1883. queryData[fsion2.Get("name").ValueStr()] = errorm
  1884. continue
  1885. } else {
  1886. errorm := make(map[string]interface{})
  1887. errorm["code"] = e.SUCCESS
  1888. errorm["message"] = "success"
  1889. queryData[fsion2.Get("name").ValueStr()] = errorm
  1890. continue
  1891. }
  1892. } else {
  1893. errorm := make(map[string]interface{})
  1894. errorm["code"] = e.ERROR
  1895. errorm["message"] = "NO SQL"
  1896. errorm["param"] = ""
  1897. queryData[fsion2.Get("name").ValueStr()] = errorm
  1898. }
  1899. }
  1900. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1901. }
  1902. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1903. if offset > 0 {
  1904. offset = offset - 1
  1905. }
  1906. //if pagecount == 0 {
  1907. // pagecount = setting.AppSetting.PageSize
  1908. //}else if pagecount>setting.AppSetting.PageSize{
  1909. // pagecount = setting.AppSetting.PageSize
  1910. //}
  1911. if returntype == "list" {
  1912. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1913. return queryData, err
  1914. } else if returntype == "listlist" {
  1915. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1916. return queryData, err
  1917. } else {
  1918. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1919. return queryData, err
  1920. }
  1921. }
  1922. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1923. if offset > 0 {
  1924. offset = offset - 1
  1925. }
  1926. //if pagecount == 0 {
  1927. // pagecount = setting.AppSetting.PageSize
  1928. //}else if pagecount>setting.AppSetting.PageSize{
  1929. // pagecount = setting.AppSetting.PageSize
  1930. //}
  1931. if returntype == "list" {
  1932. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1933. return queryData, err
  1934. } else if returntype == "listlist" {
  1935. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1936. return queryData, err
  1937. } else {
  1938. fmt.Println(params)
  1939. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1940. return queryData, err
  1941. }
  1942. }
  1943. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1944. paramslist := strings.Split(Params, ",")
  1945. s_params := make([]interface{}, 0)
  1946. if isList {
  1947. for _, v_params := range thisParams["params"].([]interface{}) {
  1948. s_params = append(s_params, v_params)
  1949. }
  1950. } else {
  1951. paramslist := strings.Split(Params, ",")
  1952. if len(paramslist) > 0 && Params != "" {
  1953. for _, value := range paramslist {
  1954. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1955. }
  1956. }
  1957. }
  1958. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1959. for _, queryData_ := range queryData {
  1960. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1961. if isList {
  1962. if queryData_[idname] != nil {
  1963. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1964. }
  1965. } else {
  1966. if queryData_[idname] != nil {
  1967. thisParams[idname] = queryData_[idname].(interface{})
  1968. }
  1969. if len(paramslist) > 0 && Params != "" {
  1970. s_params = make([]interface{}, 0)
  1971. for _, value := range paramslist {
  1972. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1973. }
  1974. }
  1975. }
  1976. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1977. } else {
  1978. }
  1979. }
  1980. return queryData, err
  1981. }
  1982. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1983. queryData, err := restful.ExecQuery(sqlstr, params)
  1984. return queryData, err
  1985. }
  1986. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1987. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1988. return queryData, err
  1989. }
  1990. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1991. queryData, err := restful.ExecQuery(sqlstr, params)
  1992. return queryData, err
  1993. }
  1994. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1995. // @Tags ImportExcel
  1996. // @Accept json
  1997. // @Produce json
  1998. // @Param file query string true "文件名"
  1999. // @Param name header string true "执行sql的名字"
  2000. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2001. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2002. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2003. // @Router /data/ImportExcel [POST]
  2004. func ImportExcel(c *gin.Context) {
  2005. appG := app.Gin{C: c}
  2006. inputdata := ""
  2007. c.Request.ParseForm()
  2008. params := c.Request.Form
  2009. file, _, err := c.Request.FormFile("file")
  2010. if err != nil {
  2011. appG.Response(http.StatusOK, e.ERROR, err)
  2012. return
  2013. }
  2014. sqlnamestrs := params.Get("name")
  2015. sheetname := params.Get("sheetname")
  2016. pastureid := params.Get("pastureid")
  2017. //importParams := params.Get("importParams")
  2018. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2019. // 必输项参数 (字符串格式 "field1,field2,field3")
  2020. requiredParams := params.Get("requiredParams")
  2021. // 日期参数
  2022. dateParams := params.Get("dateParams")
  2023. // 数字参数
  2024. numParams := params.Get("numParams")
  2025. //将字符串分割开
  2026. dateParamslist := strings.Split(dateParams, ",")
  2027. requiredParamslist := strings.Split(requiredParams, ",")
  2028. numParamslist := strings.Split(numParams, ",")
  2029. queryData := make([]interface{}, 0)
  2030. sqlslist := strings.Split(sqlnamestrs, ",")
  2031. xlsx1, err := excelize.OpenReader(file)
  2032. if err != nil {
  2033. fmt.Println(err)
  2034. return
  2035. }
  2036. ok := 0
  2037. error := 0
  2038. isdone := true
  2039. rows := xlsx1.GetRows(sheetname)
  2040. // 限制10000条,多余的截取掉
  2041. if len(rows) > 10000 {
  2042. rows = rows[:10000]
  2043. }
  2044. for i, row := range rows {
  2045. if i > 0 {
  2046. entry := make(map[string]interface{})
  2047. outentry := make(map[string]interface{})
  2048. for j, colCell := range rows[0] {
  2049. for k, colCell1 := range row {
  2050. if j == k {
  2051. outentry[colCell] = colCell1
  2052. entry[colCell] = colCell1
  2053. }
  2054. }
  2055. }
  2056. inputdata = ""
  2057. a := ""
  2058. fmt.Println(outentry, entry)
  2059. //校验日期格式
  2060. for _, v := range dateParamslist {
  2061. if v == "" {
  2062. continue
  2063. }
  2064. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2065. dtime, err := TransfTime(d.(string))
  2066. if err != nil {
  2067. a = strings.Trim(v, " ")
  2068. break
  2069. }
  2070. outentry[strings.Trim(v, " ")] = dtime
  2071. }
  2072. }
  2073. if a != "" {
  2074. outentry["error_msg"] = a + " 格式错误"
  2075. error++
  2076. queryData = append(queryData, outentry)
  2077. continue
  2078. }
  2079. a = ""
  2080. //校验必填格式
  2081. for _, v := range requiredParamslist {
  2082. if v == "" {
  2083. continue
  2084. }
  2085. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2086. a = strings.Trim(v, " ")
  2087. break
  2088. }
  2089. }
  2090. if a != "" {
  2091. outentry["error_msg"] = a + " 未填或格式错误"
  2092. error++
  2093. queryData = append(queryData, outentry)
  2094. continue
  2095. }
  2096. a = ""
  2097. //校验数字格式
  2098. for _, v := range numParamslist {
  2099. if v == "" {
  2100. continue
  2101. }
  2102. d, ok := outentry[strings.Trim(v, " ")]
  2103. if !ok || d == "" {
  2104. outentry[strings.Trim(v, " ")] = 0
  2105. } else {
  2106. var fl float64
  2107. switch d.(type) {
  2108. case string:
  2109. fl, err = strconv.ParseFloat(d.(string), 64)
  2110. }
  2111. if err != nil || fl < 0 {
  2112. a = strings.Trim(v, " ")
  2113. break
  2114. }
  2115. }
  2116. }
  2117. if a != "" {
  2118. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2119. error++
  2120. queryData = append(queryData, outentry)
  2121. continue
  2122. }
  2123. tx := restful.Engine.NewSession()
  2124. err := tx.Begin()
  2125. for _, sqlnamestr := range sqlslist {
  2126. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2127. paramslist := strings.Split(paramslists, ",")
  2128. if len(paramslist) > 0 {
  2129. s_params := make([]interface{}, 0)
  2130. for _, value := range paramslist {
  2131. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2132. if tempv, exists := c.Get("jwt_username"); exists {
  2133. s_params = append(s_params, tempv.(string))
  2134. } else {
  2135. s_params = append(s_params, "")
  2136. }
  2137. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2138. s_params = append(s_params, pastureid)
  2139. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2140. ids, err := setting.SnowIds.NextId()
  2141. if err != nil {
  2142. ids = time.Now().UnixNano()
  2143. logging.Info("create SnowIds err", err)
  2144. }
  2145. s_params = append(s_params, ids)
  2146. } else {
  2147. if outentry[strings.Trim(value, " ")] == nil {
  2148. s_params = append(s_params, "")
  2149. } else {
  2150. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2151. }
  2152. }
  2153. }
  2154. outentry["input"] = inputdata
  2155. fmt.Println(sql, s_params)
  2156. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2157. if err != nil {
  2158. if tx != nil {
  2159. tx.Rollback()
  2160. }
  2161. if tx != nil {
  2162. tx.Close()
  2163. }
  2164. msg := geterrmsg(err.Error())
  2165. outentry["error_msg"] = msg
  2166. error++
  2167. queryData = append(queryData, outentry)
  2168. isdone = true
  2169. break
  2170. } else {
  2171. if len(returnmsgmap1) > 0 {
  2172. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2173. if tx != nil {
  2174. tx.Rollback()
  2175. }
  2176. if tx != nil {
  2177. tx.Close()
  2178. }
  2179. msg := geterrmsg(va.(string))
  2180. outentry["error_msg"] = msg
  2181. error++
  2182. queryData = append(queryData, outentry)
  2183. isdone = true
  2184. break
  2185. }
  2186. }
  2187. isdone = false
  2188. }
  2189. }
  2190. }
  2191. switch {
  2192. case err != nil:
  2193. if tx != nil {
  2194. tx.Rollback()
  2195. }
  2196. default:
  2197. if tx != nil {
  2198. err = tx.Commit()
  2199. }
  2200. }
  2201. if tx != nil {
  2202. tx.Close()
  2203. }
  2204. }
  2205. if !isdone {
  2206. ok++
  2207. isdone = true
  2208. }
  2209. }
  2210. data := make(map[string]interface{})
  2211. data["result"] = queryData
  2212. data["success"] = ok
  2213. data["err_count"] = error
  2214. appG.Response(http.StatusOK, e.SUCCESS, data)
  2215. }
  2216. func TransfTime(timestr string) (string, error) {
  2217. if timestr == "" {
  2218. return time.Now().Format("2006-01-02"), nil
  2219. }
  2220. days, err := strconv.Atoi(timestr)
  2221. if err != nil {
  2222. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2223. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2224. }
  2225. _, err := time.Parse("2006-01-02", timestr)
  2226. if err != nil {
  2227. t, err := time.Parse("2006/01/02", timestr)
  2228. if err != nil {
  2229. t, err := time.Parse("2006.01.02", timestr)
  2230. if err != nil {
  2231. return "", err
  2232. } else {
  2233. return t.Format("2006-01-02"), nil
  2234. }
  2235. } else {
  2236. return t.Format("2006-01-02"), nil
  2237. }
  2238. } else {
  2239. return timestr, nil
  2240. }
  2241. }
  2242. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2243. times = times.AddDate(0, 0, days)
  2244. return times.Format("2006-01-02"), nil
  2245. }
  2246. func Createchart(c *gin.Context) {
  2247. appG := app.Gin{C: c}
  2248. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2249. fsion := gofasion.NewFasion(string(dataByte))
  2250. chart_name := fsion.Get("chart_name").ValueStr()
  2251. desc := fsion.Get("desc").ValueStr()
  2252. pastureid := fsion.Get("pastureid").ValueStr()
  2253. source_id := fsion.Get("source_id").ValueStr()
  2254. emp := fsion.Get("emp").ValueStr()
  2255. content := fsion.Get("content").Json()
  2256. var mapResult map[string]interface{}
  2257. err1 := json.Unmarshal([]byte(content), &mapResult)
  2258. if err1 != nil {
  2259. fmt.Println("JsonToMapDemo err: ", err1)
  2260. }
  2261. tx := restful.Engine.NewSession()
  2262. err := tx.Begin()
  2263. defer func() {
  2264. switch {
  2265. case err != nil:
  2266. logging.Error("tx.Begin 事务启动失败__error:", err)
  2267. if tx != nil {
  2268. tx.Rollback()
  2269. }
  2270. default:
  2271. if tx != nil {
  2272. err = tx.Commit()
  2273. }
  2274. }
  2275. if tx != nil {
  2276. tx.Close()
  2277. }
  2278. }()
  2279. ids, err := setting.SnowIds.NextId()
  2280. if err != nil {
  2281. ids = time.Now().UnixNano()
  2282. logging.Info("create SnowIds err", err)
  2283. }
  2284. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2285. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2286. if err != nil {
  2287. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2288. } else {
  2289. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2290. }
  2291. }
  2292. func Updatedashboard(c *gin.Context) {
  2293. appG := app.Gin{C: c}
  2294. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2295. fsion := gofasion.NewFasion(string(dataByte))
  2296. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2297. pastureid := fsion.Get("pastureid").ValueStr()
  2298. content := fsion.Get("content").Json()
  2299. var mapResult map[string]interface{}
  2300. err1 := json.Unmarshal([]byte(content), &mapResult)
  2301. if err1 != nil {
  2302. fmt.Println("JsonToMapDemo err: ", err1)
  2303. }
  2304. layout := mapResult["layout"]
  2305. tx := restful.Engine.NewSession()
  2306. err := tx.Begin()
  2307. defer func() {
  2308. switch {
  2309. case err != nil:
  2310. logging.Error("tx.Begin 事务启动失败__error:", err)
  2311. if tx != nil {
  2312. tx.Rollback()
  2313. }
  2314. default:
  2315. if tx != nil {
  2316. err = tx.Commit()
  2317. }
  2318. }
  2319. if tx != nil {
  2320. tx.Close()
  2321. }
  2322. }()
  2323. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2324. if err != nil {
  2325. println("2", err.Error())
  2326. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2327. } else {
  2328. if exec != nil {
  2329. if exec[0]["content"] == nil {
  2330. mapR := make(map[string]interface{})
  2331. mapR["layout"] = layout
  2332. mjson, _ := json.Marshal(mapR)
  2333. mString := string(mjson)
  2334. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2335. if err3 != nil {
  2336. println("3", err3.Error())
  2337. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2338. } else {
  2339. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2340. }
  2341. } else {
  2342. var mapR map[string]interface{}
  2343. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2344. if err1 != nil {
  2345. fmt.Println("JsonToMapDemo err: ", err2)
  2346. }
  2347. mapR["layout"] = layout
  2348. mjson, _ := json.Marshal(mapR)
  2349. mString := string(mjson)
  2350. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2351. if err3 != nil {
  2352. println("3", err3.Error())
  2353. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2354. } else {
  2355. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2356. }
  2357. }
  2358. } else {
  2359. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2360. }
  2361. }
  2362. }
  2363. func ExecSQL(c *gin.Context) {
  2364. appG := app.Gin{C: c}
  2365. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2366. fsion := gofasion.NewFasion(string(dataByte))
  2367. content := fsion.Get("content").Json()
  2368. pastureid := fsion.Get("pastureid").ValueStr()
  2369. var mapResult map[string]interface{}
  2370. err1 := json.Unmarshal([]byte(content), &mapResult)
  2371. if err1 != nil {
  2372. fmt.Println("JsonToMapDemo err: ", err1)
  2373. }
  2374. sqlstr := "select "
  2375. groupstr := " GROUP BY "
  2376. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2377. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2378. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2379. }
  2380. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2381. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2382. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2383. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2384. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2385. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2386. sqlstr = sqlstr + tem + ","
  2387. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2388. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2389. sqlstr = sqlstr + tem + ","
  2390. } else {
  2391. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2392. sqlstr = sqlstr + tem + ","
  2393. }
  2394. }
  2395. if _, ok := mapResult["selectedCalcul2"]; ok {
  2396. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2397. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2398. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2399. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2400. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2401. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2402. sqlstr = sqlstr + tem + ","
  2403. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2404. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2405. sqlstr = sqlstr + tem + ","
  2406. } else {
  2407. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2408. sqlstr = sqlstr + tem + ","
  2409. }
  2410. }
  2411. }
  2412. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2413. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2414. sqlstr = sqlstr + " where pastureid=" + pastureid
  2415. if len(mapResult["filters"].([]interface{})) > 0 {
  2416. sqlstr = sqlstr + " and "
  2417. }
  2418. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2419. for _, value := range mapResult["filters"].([]interface{}) {
  2420. switch value.(map[string]interface{})["filterOperator"].(string) {
  2421. case ">", "=", "<", ">=", "<=", "!=", "like":
  2422. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + value.(map[string]interface{})["filterOperator"].(string) + " " + value.(map[string]interface{})["value"].(map[string]interface{})["value1"].(string) + " AND "
  2423. case "IN":
  2424. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2425. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2426. sqlstr = sqlstr + value1.(string) + ","
  2427. }
  2428. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2429. sqlstr = sqlstr + ")" + " AND "
  2430. case "BETWEEN":
  2431. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + " " + value.(map[string]interface{})["value"].(map[string]interface{})["value1"].(string) + " and " + value.(map[string]interface{})["value"].(map[string]interface{})["value2"].(string) + " AND "
  2432. }
  2433. }
  2434. if len(mapResult["filters"].([]interface{})) > 0 {
  2435. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2436. }
  2437. //
  2438. groupstr = groupstr[0 : len(groupstr)-1]
  2439. sqlstr = sqlstr + groupstr + " "
  2440. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2441. sqlstr = sqlstr + " order by "
  2442. }
  2443. //
  2444. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2445. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2446. sqlstr = sqlstr + value.(string) + " "
  2447. } else {
  2448. sqlstr = sqlstr + value.(string) + ","
  2449. }
  2450. }
  2451. //
  2452. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2453. tx := restful.Engine.NewSession()
  2454. err := tx.Begin()
  2455. defer func() {
  2456. switch {
  2457. case err != nil:
  2458. logging.Error("tx.Begin 事务启动失败__error:", err)
  2459. if tx != nil {
  2460. tx.Rollback()
  2461. }
  2462. default:
  2463. if tx != nil {
  2464. err = tx.Commit()
  2465. }
  2466. }
  2467. if tx != nil {
  2468. tx.Close()
  2469. }
  2470. }()
  2471. exec, err := tx.SQL(sqlstr).Query().List()
  2472. if err != nil {
  2473. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2474. } else {
  2475. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2476. }
  2477. }
  2478. func Dashboards(c *gin.Context) {
  2479. appG := app.Gin{C: c}
  2480. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2481. fsion := gofasion.NewFasion(string(dataByte))
  2482. sqlnamestr := fsion.Get("name").ValueStr()
  2483. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2484. offset := fsion.Get("offset").ValueDefaultInt(0)
  2485. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2486. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2487. month := fsion.Get("month").ValueDefaultStr("map")
  2488. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2489. tx := restful.Engine.NewSession()
  2490. err := tx.Begin()
  2491. defer func() {
  2492. switch {
  2493. case err != nil:
  2494. if tx != nil {
  2495. tx.Rollback()
  2496. }
  2497. default:
  2498. if tx != nil {
  2499. err = tx.Commit()
  2500. }
  2501. }
  2502. if tx != nil {
  2503. tx.Close()
  2504. }
  2505. }()
  2506. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2507. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2508. if sql != "" {
  2509. s_params := make([]interface{}, 0)
  2510. if fsion.HasKey("parammaps") {
  2511. parammaps := fsion.Get("parammaps")
  2512. paramslist := strings.Split(p, ",")
  2513. if len(paramslist) > 0 && p != "" {
  2514. for _, value := range paramslist {
  2515. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2516. if tempv, exists := c.Get("jwt_username"); exists {
  2517. s_params = append(s_params, tempv.(string))
  2518. } else {
  2519. s_params = append(s_params, "")
  2520. }
  2521. } else {
  2522. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2523. }
  2524. }
  2525. }
  2526. }
  2527. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2528. if err != nil {
  2529. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2530. } else {
  2531. //paramslist1 := strings.Split(p1, ",")
  2532. dids := make([]interface{}, 0)
  2533. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2534. var mapResult map[string]interface{}
  2535. dids = append(dids, value["dashboard_id"])
  2536. if value["content"] != nil {
  2537. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2538. if err1 != nil {
  2539. println("JsonToMapDemo1 err: ", err1)
  2540. }
  2541. temap := make(map[string]interface{})
  2542. tem := mapResult["layout"].([]interface{})
  2543. if v, ok := value["chartids"]; ok {
  2544. chartids := strings.Split(v.(string), ",")
  2545. for _, va := range chartids {
  2546. a := false
  2547. for _, v2 := range tem {
  2548. if v2.(map[string]interface{})["id"].(string) == va {
  2549. a = true
  2550. //println("va1======",va)
  2551. }
  2552. }
  2553. if !a {
  2554. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2555. va + "\",\"id\":\"" + va +
  2556. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2557. var mapTem map[string]interface{}
  2558. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2559. if err1 != nil {
  2560. println("JsonToMapDemo err: ", err1)
  2561. }
  2562. tem = append(tem, mapTem)
  2563. }
  2564. }
  2565. temap["layout"] = tem
  2566. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2567. }
  2568. } else {
  2569. temap := make(map[string]interface{})
  2570. tem := make([]interface{}, 0)
  2571. if v, ok := value["chartids"]; ok {
  2572. chartids := strings.Split(v.(string), ",")
  2573. for _, va := range chartids {
  2574. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2575. va + "\",\"id\":\"" + va +
  2576. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2577. var mapTem map[string]interface{}
  2578. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2579. if err1 != nil {
  2580. println("JsonToMapDemo err: ", err1)
  2581. }
  2582. tem = append(tem, mapTem)
  2583. }
  2584. temap["layout"] = tem
  2585. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2586. }
  2587. }
  2588. }
  2589. queryData.(map[string]interface{})["order"] = dids
  2590. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2591. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2592. }
  2593. } else {
  2594. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2595. }
  2596. }
  2597. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2598. fsion := gofasion.NewFasion(parammaps)
  2599. sqlnamestr := fsion.Get("name").ValueStr()
  2600. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2601. offset := fsion.Get("offset").ValueDefaultInt(0)
  2602. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2603. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2604. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2605. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2606. body := []byte("")
  2607. if sql != "" {
  2608. s_params := make([]interface{}, 0)
  2609. if fsion.HasKey("parammaps") {
  2610. parammaps := fsion.Get("parammaps")
  2611. paramslist := strings.Split(p, ",")
  2612. if len(paramslist) > 0 && p != "" {
  2613. for _, value := range paramslist {
  2614. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2615. }
  2616. }
  2617. }
  2618. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2619. if err != nil {
  2620. } else {
  2621. paramslist1 := strings.Split(p1, ",")
  2622. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2623. s_params1 := make([]interface{}, 0)
  2624. if len(paramslist1) > 0 && p1 != "" {
  2625. for _, v := range paramslist1 {
  2626. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2627. }
  2628. }
  2629. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2630. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2631. body, _ = json.Marshal(queryData)
  2632. }
  2633. }
  2634. }
  2635. bs := bytes.NewBuffer(body)
  2636. client := &http.Client{}
  2637. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2638. req, err := http.NewRequest(RequestMethod,
  2639. url,
  2640. bs,
  2641. )
  2642. if err != nil {
  2643. }
  2644. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2645. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2646. if err != nil {
  2647. // handle error
  2648. }
  2649. resp, err := client.Do(req)
  2650. if err != nil {
  2651. return ""
  2652. }
  2653. defer resp.Body.Close()
  2654. result_body, err := ioutil.ReadAll(resp.Body)
  2655. if err != nil {
  2656. return ""
  2657. }
  2658. fmt.Println(string(result_body))
  2659. return ""
  2660. }
  2661. func GetSummary(c *gin.Context) {
  2662. appG := app.Gin{C: c}
  2663. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2664. fsion := gofasion.NewFasion(string(dataByte))
  2665. offset := fsion.Get("offset").ValueDefaultInt(0)
  2666. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2667. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2668. parammaps := fsion.Get("parammaps")
  2669. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2670. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2671. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2672. tx := restful.Engine.NewSession()
  2673. defer tx.Close()
  2674. sqlnamestr := ""
  2675. if genre == "0" {
  2676. if status == "0" {
  2677. sqlnamestr = "getAccuracyJSY"
  2678. } else if status == "1" {
  2679. sqlnamestr = "getAccuracyHFT"
  2680. } else if status == "2" {
  2681. sqlnamestr = "getAccuracyHNS"
  2682. } else if status == "3" {
  2683. sqlnamestr = "getAccuracyHSC"
  2684. } else if status == "4" {
  2685. sqlnamestr = "getAccuracyHCC"
  2686. } else if status == "5" {
  2687. sqlnamestr = "getAccuracyMC"
  2688. } else if status == "6" {
  2689. sqlnamestr = "getAccuracyFeedHL"
  2690. } else if status == "7" {
  2691. sqlnamestr = "getAccuracyRT"
  2692. }
  2693. } else {
  2694. if status == "0" {
  2695. sqlnamestr = "getAccuracySCCJSY"
  2696. } else if status == "1" {
  2697. sqlnamestr = "getAccuracySFT"
  2698. } else if status == "2" {
  2699. sqlnamestr = "getAccuracySNS"
  2700. } else if status == "3" {
  2701. sqlnamestr = "getAccuracySSC"
  2702. } else if status == "4" {
  2703. sqlnamestr = "getAccuracySCC"
  2704. } else if status == "5" {
  2705. sqlnamestr = "getAccuracySLCL"
  2706. } else if status == "7" {
  2707. sqlnamestr = "getAccuracySCCRT"
  2708. }
  2709. }
  2710. if isDate == "1" {
  2711. sqlnamestr += "Date"
  2712. }
  2713. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2714. // fmt.Println(sqlnamestr, sql)
  2715. if sql != "" {
  2716. s_params := make([]interface{}, 0)
  2717. // if fsion.HasKey("parammaps") {
  2718. fmt.Println(s_params, "222", p)
  2719. paramslist := strings.Split(p, ",")
  2720. if len(paramslist) > 0 && p != "" {
  2721. for _, value := range paramslist {
  2722. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2723. if tempv, exists := c.Get("jwt_username"); exists {
  2724. s_params = append(s_params, tempv.(string))
  2725. } else {
  2726. s_params = append(s_params, "")
  2727. }
  2728. } else {
  2729. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2730. }
  2731. }
  2732. }
  2733. if returntype == "xlsx" {
  2734. var xlsxfile *xlsx.File
  2735. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2736. //c.File("c:/dd.xlsx")
  2737. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2738. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2739. c.Header("Content-Transfer-Encoding", "binary")
  2740. _ = xlsxfile.Write(c.Writer)
  2741. } else {
  2742. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2743. if err != nil {
  2744. logging.Error("GetDataByName err: ", err)
  2745. msg := geterrmsg(err.Error())
  2746. appG.Response(http.StatusOK, e.ERROR, msg)
  2747. } else {
  2748. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2749. }
  2750. }
  2751. } else {
  2752. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2753. }
  2754. }
  2755. // type lpplanStruct struct {
  2756. // Id int64 `xorm:"id"`
  2757. // Tmrname string `xorm:"tmrname"`
  2758. // Tmrid int64 `xorm:"tmrid"`
  2759. // Sort int64 `xorm:"sort"`
  2760. // Sel int64 `xorm:"sel"`
  2761. // Times int64 `xorm:"times"`
  2762. // Ftname string `xorm:"ftname"`
  2763. // Ftid int64 `xorm:"ftid"`
  2764. // Maxweight float64 `xorm:"maxweight"`
  2765. // Sumweight float64 `xorm:"sumweight"`
  2766. // Sumcowcount int64 `xorm:"sumcowcount"`
  2767. // Pastureid string `xorm:"pastureid"`
  2768. // Display string `xorm:"display"`
  2769. // Issplit int64 `xorm:"issplit"`
  2770. // BeginTime string `xorm:"begintime"`
  2771. // }
  2772. func UpdateFTdetail(c *gin.Context) {
  2773. appG := app.Gin{C: c}
  2774. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2775. tempval_ := make(map[string]interface{})
  2776. tempCommon := make(map[string]interface{})
  2777. tempval := make([]map[string]interface{}, 0)
  2778. fTChange := make(map[string]interface{}, 0)
  2779. fpdOldDataList := make([]map[string]interface{}, 0)
  2780. fpdDataList := make([]map[string]interface{}, 0)
  2781. fsion := gofasion.NewFasion(string(dataByte))
  2782. // parammaps := fsion.Get("parammaps")
  2783. createdate := time.Now().Format("2006-01-02 15:04:05")
  2784. err := json.Unmarshal(dataByte, &tempval_)
  2785. if err != nil {
  2786. appG.Response(http.StatusOK, e.ERROR, false)
  2787. return
  2788. }
  2789. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2790. tx := restful.Engine.NewSession()
  2791. if v, ok := tempval_["data"].([]interface{}); ok {
  2792. for _, Tvalue := range v {
  2793. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2794. if v1["name"] == "updateFPbyFTChange" {
  2795. fTChange = v1
  2796. continue
  2797. }
  2798. tempval = append(tempval, v1)
  2799. }
  2800. }
  2801. }
  2802. parammaps := fTChange["parammaps"].(map[string]interface{})
  2803. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2804. // if err != nil {
  2805. // logs.Error(err)
  2806. // appG.Response(http.StatusOK, e.ERROR, false)
  2807. // return
  2808. // }
  2809. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2810. // if err != nil {
  2811. // logs.Error(err)
  2812. // appG.Response(http.StatusOK, e.ERROR, false)
  2813. // return
  2814. // }
  2815. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2816. // if err != nil {
  2817. // logs.Error(err)
  2818. // appG.Response(http.StatusOK, e.ERROR, false)
  2819. // return
  2820. // }
  2821. err = tx.Begin()
  2822. if err != nil {
  2823. logging.Error("tx.Begin 事务启动失败__error:", err)
  2824. }
  2825. defer func() {
  2826. if err != nil {
  2827. if tx != nil {
  2828. tx.Rollback()
  2829. }
  2830. }
  2831. if tx != nil {
  2832. tx.Close()
  2833. }
  2834. }()
  2835. if err != nil {
  2836. } else {
  2837. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2838. tempCommon = v
  2839. }
  2840. fpdOldDataList, err = tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  2841. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2842. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2843. UNION
  2844. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  2845. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2846. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2847. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2848. if err == nil {
  2849. if tempv, exists := c.Get("jwt_username"); exists {
  2850. tempCommon["jwt_username"] = tempv.(string)
  2851. }
  2852. for _, paramvalue := range tempval {
  2853. if _, ok := paramvalue["resultname"]; !ok {
  2854. paramvalue["resultname"] = paramvalue["name"]
  2855. }
  2856. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2857. if err != nil {
  2858. logging.Error("ExecDataParam error:", err)
  2859. break
  2860. }
  2861. }
  2862. if err != nil {
  2863. msg := geterrmsg(err.Error())
  2864. appG.Response(http.StatusOK, e.ERROR, msg)
  2865. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2866. }
  2867. }
  2868. }
  2869. tx.Commit()
  2870. // go func() {
  2871. if fTChange != nil {
  2872. parammaps := fTChange["parammaps"].(map[string]interface{})
  2873. if parammaps["type"].(float64) == 1 {
  2874. _, err = tx.SQL(`UPDATE feedp fp
  2875. set
  2876. ccountratio = ccount *(ratio /100 ),
  2877. fp.ftweight= IFNULL(IF(
  2878. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2879. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2880. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2881. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2882. ),0),fp.feedweight = IFNULL(IF(
  2883. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2884. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2885. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2886. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2887. ),0) +ifnull(fp.supplyweight,0)
  2888. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2889. _, err = tx.SQL(`UPDATE fpdetail fpd
  2890. INNER JOIN feedp fp
  2891. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2892. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2893. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2894. } else {
  2895. _, err = tx.SQL(`UPDATE feedp fp
  2896. SET ccountratio = ccount *(ratio /100 ),
  2897. fp.supplyweight= IFNULL(IF(
  2898. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2899. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2900. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2901. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2902. ),0),fp.feedweight = IFNULL(IF(
  2903. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2904. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2905. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2906. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2907. ),0) +ifnull(fp.supplyweight,0)
  2908. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2909. _, err = tx.SQL(`UPDATE fpdetail fpd
  2910. INNER JOIN feedp fp
  2911. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2912. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2913. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2914. }
  2915. fpdDataList, err = tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
  2916. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2917. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2918. UNION
  2919. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
  2920. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2921. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2922. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2923. lpplanList := make([]*lpplanStruct, 0)
  2924. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2925. if err != nil {
  2926. logs.Error(err, 1)
  2927. return
  2928. }
  2929. lppidlist := []string{}
  2930. for _, lpp := range lpplanList {
  2931. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2932. }
  2933. if len(lppidlist) <= 0 {
  2934. appG.Response(http.StatusOK, e.SUCCESS, true)
  2935. return
  2936. }
  2937. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2938. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2939. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2940. if err != nil {
  2941. // tx.Rollback()
  2942. logs.Error(err, 2, parammaps["pastureid"])
  2943. return
  2944. }
  2945. var wg sync.WaitGroup
  2946. for _, old := range fpdOldDataList {
  2947. for _, fpd := range fpdDataList {
  2948. wg.Add(1)
  2949. go func(old, fpd map[string]interface{}) {
  2950. updateLppandList := make([]*lpplandtl1, 0)
  2951. defer wg.Done()
  2952. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2953. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2954. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2955. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2956. // if weight > oldweight {
  2957. // return
  2958. // }
  2959. var w float64
  2960. var status int
  2961. if weight < oldweight {
  2962. if weight >= 0 {
  2963. return
  2964. }
  2965. w = weight
  2966. status = 0
  2967. } else {
  2968. if oldweight > 0 {
  2969. return
  2970. }
  2971. w = weight
  2972. status = 1
  2973. }
  2974. // fweight = w
  2975. for _, lpp := range lpplanList {
  2976. var fweight float64
  2977. var lweight float64
  2978. lpplandtl1List := make([]*lpplandtl1, 0)
  2979. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2980. for _, lppland := range lpplandtl1AllList {
  2981. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2982. lpplandtl1List = append(lpplandtl1List, lppland)
  2983. }
  2984. }
  2985. if len(lpplandtl1List) == 0 {
  2986. continue
  2987. }
  2988. for _, lppland := range lpplandtl1List {
  2989. lweight += lppland.Lweight
  2990. }
  2991. if status == 0 {
  2992. if lweight <= 0 {
  2993. continue
  2994. }
  2995. } else {
  2996. if lpp.Maxweight <= lweight {
  2997. continue
  2998. }
  2999. }
  3000. for _, lppland := range lpplandtl1List {
  3001. if fpdid == lppland.Fpdid {
  3002. if status == 1 {
  3003. // if w <= lppland.Lweight {
  3004. if lpp.Maxweight <= lweight {
  3005. continue
  3006. }
  3007. if w+lweight <= lpp.Maxweight {
  3008. lppland.Lweight += w
  3009. lweight += w
  3010. fweight += w
  3011. w = 0
  3012. } else {
  3013. w = w - (lpp.Maxweight - lweight)
  3014. n := (lpp.Maxweight - lweight)
  3015. lppland.Lweight = lppland.Lweight + n
  3016. lweight += n
  3017. fweight += n
  3018. }
  3019. } else {
  3020. if lppland.Lweight == 0 {
  3021. continue
  3022. }
  3023. if w+lppland.Lweight >= 0 {
  3024. lppland.Lweight = lppland.Lweight + w
  3025. lweight = lweight + w
  3026. fweight = fweight + w
  3027. w = 0
  3028. } else {
  3029. w = w + lppland.Lweight
  3030. lweight = lweight - lppland.Lweight
  3031. fweight = fweight - lppland.Lweight
  3032. lppland.Lweight = 0
  3033. }
  3034. }
  3035. updateLppandList = append(updateLppandList, lppland)
  3036. break
  3037. }
  3038. }
  3039. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3040. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3041. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3042. if err != nil {
  3043. // tx.Rollback()
  3044. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3045. return
  3046. }
  3047. for _, lppland := range updateLppandList {
  3048. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3049. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3050. if err != nil {
  3051. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3052. // tx.Rollback()
  3053. logs.Error(err, 3)
  3054. return
  3055. }
  3056. // defer wg.Done()
  3057. }
  3058. updateLppandList = []*lpplandtl1{}
  3059. if w == 0 {
  3060. break
  3061. }
  3062. }
  3063. }
  3064. }(old, fpd)
  3065. }
  3066. }
  3067. wg.Wait()
  3068. }
  3069. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3070. if err != nil {
  3071. logs.Error(err)
  3072. appG.Response(http.StatusOK, e.ERROR, false)
  3073. return
  3074. }
  3075. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3076. if err != nil {
  3077. logs.Error(err)
  3078. appG.Response(http.StatusOK, e.ERROR, false)
  3079. return
  3080. }
  3081. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3082. if err != nil {
  3083. logs.Error(err)
  3084. appG.Response(http.StatusOK, e.ERROR, false)
  3085. return
  3086. }
  3087. now := createdate
  3088. // for _, oldFpd := range oldFpdDataList {
  3089. for _, newFpd := range newFpdDataList {
  3090. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3091. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3092. // go func() {
  3093. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3094. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3095. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3096. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3097. if err != nil {
  3098. logs.Error(err)
  3099. appG.Response(http.StatusOK, e.ERROR, false)
  3100. return
  3101. }
  3102. // }()
  3103. }
  3104. // break
  3105. // }
  3106. // }
  3107. // }
  3108. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3109. for _, newLpplandtl1 := range newLpplandtl1List {
  3110. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3111. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3112. // go func() {
  3113. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3114. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3115. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3116. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3117. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3118. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3119. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3120. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3121. if err != nil {
  3122. logs.Error(err)
  3123. appG.Response(http.StatusOK, e.ERROR, false)
  3124. return
  3125. }
  3126. // }()
  3127. // }
  3128. // break
  3129. // }
  3130. // }
  3131. }
  3132. // for _, oldFeedp := range oldFeedpList {
  3133. for _, newFeedp := range newFeedpList {
  3134. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3135. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3136. // go func() {
  3137. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3138. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3139. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3140. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3141. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3142. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3143. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3144. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3145. if err != nil {
  3146. logs.Error(err)
  3147. appG.Response(http.StatusOK, e.ERROR, false)
  3148. return
  3149. }
  3150. }
  3151. appG.Response(http.StatusOK, e.SUCCESS, true)
  3152. }
  3153. type lpplandtlInfo struct {
  3154. Id int64 `xorm:"id"`
  3155. Pastureid int64 `xorm:"pastureid"`
  3156. Lppid int64 `xorm:"lppid"`
  3157. Barid int64 `xorm:"barid"`
  3158. Barname string `xorm:"barname"`
  3159. Fpdid int64 `xorm:"fpdid"`
  3160. Fttype int64 `xorm:"fttype"`
  3161. Lweight float64 `xorm:"lweight"`
  3162. Sort int64 `xorm:"sort"`
  3163. Tmrid int64 `xorm:"tmrid"`
  3164. Tmrname string `xorm:"tmrname"`
  3165. Cowcount int64 `xorm:"cowcount"`
  3166. Ccountradio float64 `xorm:"ccountradio"`
  3167. Background string `xorm:"background"`
  3168. Lweighthis float64 `xorm:"lweighthis"`
  3169. Maxweight float64 `xorm:"maxweight"`
  3170. }
  3171. func UpdateFpdetailBar(c *gin.Context) {
  3172. appG := app.Gin{C: c}
  3173. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3174. fsion := gofasion.NewFasion(string(dataByte))
  3175. pastureid := fsion.Get("pastureid").ValueStr()
  3176. id := fsion.Get("id").ValueStr()
  3177. tx := restful.Engine.NewSession()
  3178. tx.Begin()
  3179. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse from fpdetail where pastureid = ? and barid = (select barid from feedp where id = ? ) order by times `,
  3180. pastureid, id).Query().List()
  3181. if err != nil {
  3182. logs.Error(err)
  3183. }
  3184. for _, fpd := range fpdList {
  3185. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3186. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3187. pastureid, fpd["id"]).Query().List()
  3188. if err != nil {
  3189. tx.Rollback()
  3190. logs.Error(err)
  3191. appG.Response(http.StatusOK, e.ERROR, false)
  3192. return
  3193. }
  3194. var lweight float64
  3195. for _, lppland := range lpplandList {
  3196. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3197. lweight += lweight1
  3198. }
  3199. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3200. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3201. if fpdweight >= ptuse && lweight == ptuse {
  3202. continue
  3203. } else {
  3204. if lweight <= fpdweight {
  3205. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3206. if err != nil {
  3207. tx.Rollback()
  3208. logs.Error(err)
  3209. appG.Response(http.StatusOK, e.ERROR, false)
  3210. return
  3211. }
  3212. } else {
  3213. weight := fpdweight - lweight
  3214. for _, lppland := range lpplandList {
  3215. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3216. if weight >= lpplandlweight {
  3217. weight = weight - lpplandlweight
  3218. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3219. if err != nil {
  3220. tx.Rollback()
  3221. logs.Error(err)
  3222. appG.Response(http.StatusOK, e.ERROR, false)
  3223. return
  3224. }
  3225. } else {
  3226. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3227. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3228. // if err != nil {
  3229. // tx.Rollback()
  3230. // logs.Error(err)
  3231. // appG.Response(http.StatusOK, e.ERROR, false)
  3232. // return
  3233. // }
  3234. weight = 0
  3235. break
  3236. }
  3237. }
  3238. }
  3239. }
  3240. }
  3241. fsionData := fsion.Get("data").Array()
  3242. for _, list := range fsionData {
  3243. ftmap := make(map[string]interface{})
  3244. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3245. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3246. ftmap["times"] = list.Get("times").ValueInt64()
  3247. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3248. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3249. // fmt.Println(ftmap)
  3250. fpdDataList, err := tx.SQL(`
  3251. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ifnull(ptsid,-1) ) ptsid ,
  3252. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3253. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3254. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3255. if err != nil {
  3256. tx.Rollback()
  3257. logs.Error(err)
  3258. }
  3259. for _, fpd := range fpdDataList {
  3260. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3261. fttype := -1
  3262. if fpd["fttype"].(string) == "1" {
  3263. fttype = 1
  3264. }
  3265. var fweight float64
  3266. var lweight float64
  3267. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3268. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3269. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3270. join tmr t on t.id = lpp.tmrid
  3271. where lppland.fpdid =?
  3272. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3273. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3274. if err != nil {
  3275. tx.Rollback()
  3276. logs.Error(err)
  3277. }
  3278. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3279. var w float64
  3280. var status int
  3281. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3282. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3283. if weight >= 0 {
  3284. continue
  3285. }
  3286. w = weight
  3287. status = 0
  3288. } else {
  3289. // continue
  3290. if weight <= 0 {
  3291. continue
  3292. }
  3293. w = weight
  3294. status = 1
  3295. }
  3296. // for _, lppland := range lpplandtl1List {
  3297. // lweight += lppland.Lweight
  3298. // }
  3299. for _, lppland := range lpplandtl1List {
  3300. lpplandInfo := new(lpplandtlInfo)
  3301. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3302. lweight = lpplandInfo.Lweight
  3303. if status == 1 {
  3304. // if w <= lppland.Lweight {
  3305. if lppland.Maxweight <= lweight {
  3306. continue
  3307. }
  3308. if w+lweight <= lppland.Maxweight {
  3309. lppland.Lweight += w
  3310. lweight += w
  3311. fweight += w
  3312. w = 0
  3313. } else {
  3314. w = w - (lppland.Maxweight - lweight)
  3315. n := (lppland.Maxweight - lweight)
  3316. lppland.Lweight = lppland.Lweight + n
  3317. lweight += n
  3318. fweight += n
  3319. }
  3320. } else {
  3321. if lppland.Lweight == 0 {
  3322. continue
  3323. }
  3324. if w+lppland.Lweight >= 0 {
  3325. lppland.Lweight = lppland.Lweight + w
  3326. lweight = lweight + w
  3327. fweight = fweight + w
  3328. w = 0
  3329. } else {
  3330. w = w + lppland.Lweight
  3331. lweight = lweight - lppland.Lweight
  3332. fweight = fweight - lppland.Lweight
  3333. lppland.Lweight = 0
  3334. }
  3335. }
  3336. if lppland.Lweight > 0 {
  3337. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3338. if err != nil {
  3339. tx.Rollback()
  3340. logs.Error(err)
  3341. return
  3342. }
  3343. } else {
  3344. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3345. if err != nil {
  3346. tx.Rollback()
  3347. logs.Error(err)
  3348. return
  3349. }
  3350. }
  3351. if w == 0 {
  3352. break
  3353. }
  3354. // break
  3355. }
  3356. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3357. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3358. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3359. if err != nil {
  3360. tx.Rollback()
  3361. logs.Error(err)
  3362. }
  3363. if w == 0 {
  3364. break
  3365. }
  3366. }
  3367. }
  3368. }
  3369. tx.Commit()
  3370. now := time.Now()
  3371. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3372. if err != nil {
  3373. logs.Error(err)
  3374. appG.Response(http.StatusOK, e.ERROR, false)
  3375. return
  3376. }
  3377. for _, newLpplandtl1 := range newLpplandtl1List {
  3378. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3379. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3380. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3381. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3382. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3383. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3384. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3385. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3386. if err != nil {
  3387. logs.Error(err)
  3388. appG.Response(http.StatusOK, e.ERROR, false)
  3389. return
  3390. }
  3391. }
  3392. appG.Response(http.StatusOK, e.SUCCESS, true)
  3393. }
  3394. func GetProcessAnalysis(c *gin.Context) {
  3395. appG := app.Gin{C: c}
  3396. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3397. fsion := gofasion.NewFasion(string(dataByte))
  3398. sqlnamestr := fsion.Get("name").ValueStr()
  3399. offset := fsion.Get("offset").ValueDefaultInt(0)
  3400. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3401. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3402. parammaps := fsion.Get("parammaps")
  3403. tx := restful.Engine.NewSession()
  3404. err := tx.Begin()
  3405. defer func() {
  3406. switch {
  3407. case err != nil:
  3408. logging.Error("tx.Begin 事务启动失败__error:", err)
  3409. if tx != nil {
  3410. tx.Rollback()
  3411. }
  3412. default:
  3413. if tx != nil {
  3414. err = tx.Commit()
  3415. }
  3416. }
  3417. if tx != nil {
  3418. tx.Close()
  3419. }
  3420. }()
  3421. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3422. s_params := make([]interface{}, 0)
  3423. paramslist := strings.Split(p, ",")
  3424. if len(paramslist) > 0 && p != "" {
  3425. for _, value := range paramslist {
  3426. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3427. if tempv, exists := c.Get("jwt_username"); exists {
  3428. s_params = append(s_params, tempv.(string))
  3429. } else {
  3430. s_params = append(s_params, "")
  3431. }
  3432. } else {
  3433. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3434. }
  3435. }
  3436. }
  3437. tmrtnameStr := ""
  3438. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3439. if len(tmrtnameStr) == 0 {
  3440. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3441. } else {
  3442. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3443. }
  3444. }
  3445. if len(tmrtnameStr) > 0 {
  3446. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3447. }
  3448. sql += " ORDER BY d.intime"
  3449. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3450. if err != nil {
  3451. logging.Error("GetDataByName err: ", err)
  3452. msg := geterrmsg(err.Error())
  3453. appG.Response(http.StatusOK, e.ERROR, msg)
  3454. } else {
  3455. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3456. }
  3457. }
  3458. func UpdateFeedtempletStatus(c *gin.Context) {
  3459. appG := app.Gin{C: c}
  3460. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3461. fsion := gofasion.NewFasion(string(dataByte))
  3462. parammaps := fsion.Get("parammaps")
  3463. tx := restful.Engine.NewSession()
  3464. tx.Begin()
  3465. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3466. if err != nil {
  3467. tx.Rollback()
  3468. logs.Error(err)
  3469. appG.Response(http.StatusOK, e.ERROR, err)
  3470. return
  3471. }
  3472. tx.Commit()
  3473. appG.Response(http.StatusOK, e.SUCCESS, true)
  3474. }
  3475. func AddFtdry(c *gin.Context) {
  3476. appG := app.Gin{C: c}
  3477. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3478. fsion := gofasion.NewFasion(string(dataByte))
  3479. sqlnamestr := fsion.Get("name").ValueStr()
  3480. s_params := make([]interface{}, 0)
  3481. tx := restful.Engine.NewSession()
  3482. err := tx.Begin()
  3483. defer func() {
  3484. switch {
  3485. case err != nil:
  3486. if tx != nil {
  3487. tx.Rollback()
  3488. }
  3489. default:
  3490. if tx != nil {
  3491. err = tx.Commit()
  3492. }
  3493. }
  3494. if tx != nil {
  3495. tx.Close()
  3496. }
  3497. }()
  3498. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3499. if sql != "" {
  3500. parammaps := fsion.Get("parammaps")
  3501. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3502. paramslist := strings.Split(p, ",")
  3503. if len(paramslist) > 0 && p != "" {
  3504. for _, value := range paramslist {
  3505. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3506. if tempv, exists := c.Get("jwt_username"); exists {
  3507. s_params = append(s_params, tempv.(string))
  3508. } else {
  3509. s_params = append(s_params, "")
  3510. }
  3511. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3512. ids, err := setting.SnowIds.NextId()
  3513. if err != nil {
  3514. ids = time.Now().UnixNano()
  3515. logging.Info("create SnowIds err", err)
  3516. }
  3517. s_params = append(s_params, ids)
  3518. } else {
  3519. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3520. }
  3521. }
  3522. }
  3523. var actweight float64
  3524. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3525. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3526. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3527. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3528. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3529. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3530. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("operatetime").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3531. if err != nil {
  3532. logging.Error("AddFtdry err: ", err)
  3533. msg := geterrmsg(err.Error())
  3534. appG.Response(http.StatusOK, e.ERROR, msg)
  3535. }
  3536. if len(actweightList) > 0 {
  3537. for _, item := range actweightList {
  3538. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3539. if err != nil {
  3540. logging.Error("AddFtdry err: ", err)
  3541. msg := geterrmsg(err.Error())
  3542. appG.Response(http.StatusOK, e.ERROR, msg)
  3543. }
  3544. actweight = fl
  3545. }
  3546. } else {
  3547. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3548. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3549. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3550. if err != nil {
  3551. logging.Error("AddFtdry err: ", err)
  3552. msg := geterrmsg(err.Error())
  3553. appG.Response(http.StatusOK, e.ERROR, msg)
  3554. }
  3555. for _, item := range dryList {
  3556. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3557. if err != nil {
  3558. logging.Error("AddFtdry err: ", err)
  3559. msg := geterrmsg(err.Error())
  3560. appG.Response(http.StatusOK, e.ERROR, msg)
  3561. }
  3562. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3563. }
  3564. }
  3565. if sqlnamestr == "insertFtdry" {
  3566. s_params = append(s_params, actweight)
  3567. } else if sqlnamestr == "updateFtdry" {
  3568. sql = fmt.Sprintf(sql, actweight)
  3569. }
  3570. queryData, err := execDataBySqlT(sql, s_params, tx)
  3571. if err != nil {
  3572. logging.Error("AddFtdry err: ", err)
  3573. msg := geterrmsg(err.Error())
  3574. appG.Response(http.StatusOK, e.ERROR, msg)
  3575. } else {
  3576. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3577. }
  3578. } else {
  3579. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3580. }
  3581. }
  3582. func CheckDates(c *gin.Context) {
  3583. tx := restful.Engine.NewSession()
  3584. defer tx.Close()
  3585. appG := app.Gin{C: c}
  3586. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3587. tempval_ := make(map[string]interface{})
  3588. tempCommon := make(map[string]interface{})
  3589. tempval := make([]map[string]interface{}, 0)
  3590. err := json.Unmarshal(dataByte, &tempval_)
  3591. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3592. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3593. if err != nil {
  3594. } else {
  3595. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3596. tempCommon = v
  3597. }
  3598. if v, ok := tempval_["data"].([]interface{}); ok {
  3599. for _, Tvalue := range v {
  3600. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3601. tempval = append(tempval, v1)
  3602. }
  3603. }
  3604. }
  3605. if err == nil {
  3606. if tempv, exists := c.Get("jwt_username"); exists {
  3607. tempCommon["jwt_username"] = tempv.(string)
  3608. }
  3609. for _, paramvalue := range tempval {
  3610. if _, ok := paramvalue["resultname"]; !ok {
  3611. paramvalue["resultname"] = paramvalue["name"]
  3612. }
  3613. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3614. if err != nil {
  3615. logging.Error("ExecDataParam error:", err)
  3616. }
  3617. }
  3618. if err == nil {
  3619. vmsg := ""
  3620. for _, item := range tempval {
  3621. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3622. for _, childrenList := range list.([]interface{}) {
  3623. for k, children := range childrenList.(map[string]interface{}) {
  3624. if k != "children" {
  3625. continue
  3626. }
  3627. for _, v := range children.([]map[string]interface{}) {
  3628. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3629. if k1 == "list" {
  3630. for _, v2 := range v1.([]map[string]interface{}) {
  3631. if v2["vmsg"].(string) != "1" {
  3632. if len(vmsg) == 0 {
  3633. vmsg = v2["vmsg"].(string)
  3634. } else {
  3635. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3636. }
  3637. }
  3638. }
  3639. }
  3640. }
  3641. }
  3642. }
  3643. }
  3644. }
  3645. }
  3646. if len(vmsg) > 0 {
  3647. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3648. } else {
  3649. appG.Response(http.StatusOK, e.SUCCESS, true)
  3650. }
  3651. } else {
  3652. msg := geterrmsg(err.Error())
  3653. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3654. }
  3655. }
  3656. }
  3657. if err != nil {
  3658. msg := geterrmsg(err.Error())
  3659. appG.Response(http.StatusOK, e.ERROR, msg)
  3660. }
  3661. }
  3662. func ExecDataQuery(fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, ParentParamMap map[string]interface{}, sameParamMap []map[string]interface{}, tx *xorm.Session) (interface{}, error) {
  3663. sqlname := fasion["name"].(string)
  3664. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3665. if v, ok := fasion["type"]; ok {
  3666. sqltype = v.(string)
  3667. }
  3668. sql := ""
  3669. p := ""
  3670. s_params := make([]interface{}, 0)
  3671. if sqltype != "" {
  3672. sql, p = restful.GetSqlByName(sqlname, tx)
  3673. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3674. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3675. paramslist := strings.Split(p, ",")
  3676. if len(paramslist) > 0 && p != "" {
  3677. for _, value := range paramslist {
  3678. ss := ""
  3679. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3680. ids, err := setting.SnowIds.NextId()
  3681. if err != nil {
  3682. ids = time.Now().UnixNano()
  3683. logging.Info("create SnowIds err", err)
  3684. }
  3685. s_params = append(s_params, ids)
  3686. } else {
  3687. if ss == "" && CommonParamMap != nil {
  3688. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3689. ss = valuestring
  3690. tempstrb := strings.IndexAny(valuestring, "@")
  3691. tempstre := strings.IndexAny(valuestring, ".")
  3692. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3693. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3694. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3695. }
  3696. } else {
  3697. ss = ""
  3698. }
  3699. }
  3700. }
  3701. if ss == "" && ParentParamMap != nil {
  3702. ss = getParamValue_(v, value, ParentParamMap)
  3703. }
  3704. if ss == "" && sameParamMap != nil {
  3705. ss = getParamValue(v, value, sameParamMap)
  3706. }
  3707. if ss == "" && ParamMap != nil {
  3708. ss = getParamValue(v, value, ParamMap)
  3709. }
  3710. s_params = append(s_params, ss)
  3711. }
  3712. }
  3713. }
  3714. }
  3715. }
  3716. if sql == "" {
  3717. sqltype = ""
  3718. }
  3719. if sql != "" {
  3720. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3721. if err != nil {
  3722. return nil, err
  3723. }
  3724. // fmt.Println(tempValParam)
  3725. return tempValParam.(map[string]interface{}), nil
  3726. } else {
  3727. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3728. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3729. if err != nil {
  3730. return nil, err
  3731. }
  3732. return nil, err
  3733. }
  3734. }
  3735. return nil, nil
  3736. }
  3737. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3738. var err error
  3739. subarray, ok := fasion["children"]
  3740. if ok {
  3741. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3742. tempVal_arrary := make([]map[string]interface{}, 0)
  3743. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3744. tempVal_ := make(map[string]interface{})
  3745. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3746. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3747. } else {
  3748. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3749. }
  3750. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3751. if err != nil {
  3752. return err
  3753. }
  3754. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3755. }
  3756. v.(map[string]interface{})["children"] = tempVal_arrary
  3757. }
  3758. }
  3759. return nil
  3760. }
  3761. func FpdImportExcel(c *gin.Context) {
  3762. appG := app.Gin{C: c}
  3763. inputdata := ""
  3764. c.Request.ParseForm()
  3765. params := c.Request.Form
  3766. file, _, err := c.Request.FormFile("file")
  3767. if err != nil {
  3768. appG.Response(http.StatusOK, e.ERROR, err)
  3769. return
  3770. }
  3771. sqlnamestrs := params.Get("name")
  3772. sheetname := params.Get("sheetname")
  3773. pastureid := params.Get("pastureid")
  3774. // importParams := params.Get("importParams")
  3775. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3776. // 必输项参数 (字符串格式 "field1,field2,field3")
  3777. requiredParams := params.Get("requiredParams")
  3778. // 日期参数
  3779. dateParams := params.Get("dateParams")
  3780. // 数字参数
  3781. numParams := params.Get("numParams")
  3782. //将字符串分割开
  3783. dateParamslist := strings.Split(dateParams, ",")
  3784. requiredParamslist := strings.Split(requiredParams, ",")
  3785. numParamslist := strings.Split(numParams, ",")
  3786. queryData := make([]interface{}, 0)
  3787. sqlslist := strings.Split(sqlnamestrs, ",")
  3788. xlsx1, err := excelize.OpenReader(file)
  3789. if err != nil {
  3790. fmt.Println(err)
  3791. return
  3792. }
  3793. ok := 0
  3794. error := 0
  3795. isdone := true
  3796. tx := restful.Engine.NewSession()
  3797. defer tx.Close()
  3798. oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  3799. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3800. if err != nil {
  3801. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3802. return
  3803. }
  3804. rows := xlsx1.GetRows(sheetname)
  3805. // 限制10000条,多余的截取掉
  3806. if len(rows) > 10000 {
  3807. rows = rows[:10000]
  3808. }
  3809. dataList := make(map[string][]*upFpdetail, 0)
  3810. for i, row := range rows {
  3811. if i > 0 {
  3812. entry := make(map[string]interface{})
  3813. outentry := make(map[string]interface{})
  3814. for j, colCell := range rows[0] {
  3815. for k, colCell1 := range row {
  3816. if j == k {
  3817. outentry[colCell] = colCell1
  3818. entry[colCell] = colCell1
  3819. }
  3820. }
  3821. }
  3822. inputdata = ""
  3823. a := ""
  3824. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3825. //校验日期格式
  3826. for _, v := range dateParamslist {
  3827. if v == "" {
  3828. continue
  3829. }
  3830. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3831. dtime, err := TransfTime(d.(string))
  3832. if err != nil {
  3833. a = strings.Trim(v, " ")
  3834. break
  3835. }
  3836. outentry[strings.Trim(v, " ")] = dtime
  3837. }
  3838. }
  3839. if a != "" {
  3840. outentry["error_msg"] = a + " 格式错误"
  3841. error++
  3842. queryData = append(queryData, outentry)
  3843. continue
  3844. }
  3845. a = ""
  3846. //校验必填格式
  3847. for _, v := range requiredParamslist {
  3848. if v == "" {
  3849. continue
  3850. }
  3851. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3852. a = strings.Trim(v, " ")
  3853. break
  3854. }
  3855. }
  3856. if a != "" {
  3857. outentry["error_msg"] = a + " 未填或格式错误"
  3858. error++
  3859. queryData = append(queryData, outentry)
  3860. continue
  3861. }
  3862. a = ""
  3863. //校验数字格式
  3864. for _, v := range numParamslist {
  3865. if v == "" {
  3866. continue
  3867. }
  3868. d, ok := outentry[strings.Trim(v, " ")]
  3869. if !ok || d == "" {
  3870. outentry[strings.Trim(v, " ")] = 0
  3871. } else {
  3872. var fl float64
  3873. switch d.(type) {
  3874. case string:
  3875. fl, err = strconv.ParseFloat(d.(string), 64)
  3876. }
  3877. if err != nil || fl < 0 {
  3878. a = strings.Trim(v, " ")
  3879. break
  3880. }
  3881. }
  3882. }
  3883. if a != "" {
  3884. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3885. error++
  3886. queryData = append(queryData, outentry)
  3887. continue
  3888. }
  3889. errExist := false
  3890. for _, sqlnamestr := range sqlslist {
  3891. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3892. paramslist := strings.Split(paramslists, ",")
  3893. if len(paramslist) > 0 {
  3894. s_params := make([]interface{}, 0)
  3895. for _, value := range paramslist {
  3896. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3897. if tempv, exists := c.Get("jwt_username"); exists {
  3898. s_params = append(s_params, tempv.(string))
  3899. } else {
  3900. s_params = append(s_params, "")
  3901. }
  3902. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3903. s_params = append(s_params, pastureid)
  3904. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3905. ids, err := setting.SnowIds.NextId()
  3906. if err != nil {
  3907. ids = time.Now().UnixNano()
  3908. logging.Info("create SnowIds err", err)
  3909. }
  3910. s_params = append(s_params, ids)
  3911. } else {
  3912. if outentry[strings.Trim(value, " ")] == nil {
  3913. s_params = append(s_params, "")
  3914. } else {
  3915. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3916. }
  3917. }
  3918. }
  3919. outentry["input"] = inputdata
  3920. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3921. if err != nil {
  3922. errExist = true
  3923. // if tx != nil {
  3924. // tx.Rollback()
  3925. // }
  3926. // if tx != nil {
  3927. // tx.Close()
  3928. // }
  3929. msg := geterrmsg(err.Error())
  3930. outentry["error_msg"] = msg
  3931. error++
  3932. queryData = append(queryData, outentry)
  3933. isdone = true
  3934. break
  3935. } else {
  3936. if len(returnmsgmap1) > 0 {
  3937. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3938. // if tx != nil {
  3939. // tx.Rollback()
  3940. // }
  3941. // if tx != nil {
  3942. // tx.Close()
  3943. // }
  3944. msg := geterrmsg(va.(string))
  3945. outentry["error_msg"] = msg
  3946. error++
  3947. queryData = append(queryData, outentry)
  3948. isdone = true
  3949. break
  3950. }
  3951. }
  3952. isdone = false
  3953. }
  3954. }
  3955. }
  3956. if !errExist {
  3957. dataexcel := make(map[string]interface{}, 0)
  3958. if _, ok := outentry["栏舍名称"]; ok {
  3959. dataexcel["barname"] = outentry["栏舍名称"]
  3960. }
  3961. if _, ok := outentry["实际牛头数"]; ok {
  3962. dataexcel["ccount"] = outentry["实际牛头数"]
  3963. }
  3964. if _, ok := outentry["系数(%)"]; ok {
  3965. dataexcel["ratio"] = outentry["系数(%)"]
  3966. }
  3967. if _, ok := outentry["配方模板"]; ok {
  3968. dataexcel["ftname"] = outentry["配方模板"]
  3969. }
  3970. if _, ok := outentry["补料配方"]; ok {
  3971. dataexcel["ptsfname"] = outentry["补料配方"]
  3972. }
  3973. if _, ok := outentry["第一班比例(%)"]; ok {
  3974. dataexcel["1"] = outentry["第一班比例(%)"]
  3975. }
  3976. if _, ok := outentry["第二班比例(%)"]; ok {
  3977. dataexcel["2"] = outentry["第二班比例(%)"]
  3978. }
  3979. if _, ok := outentry["第三班比例(%)"]; ok {
  3980. dataexcel["3"] = outentry["第三班比例(%)"]
  3981. }
  3982. if _, ok := outentry["第四班比例(%)"]; ok {
  3983. dataexcel["4"] = outentry["第四班比例(%)"]
  3984. }
  3985. if _, ok := outentry["第五班比例(%)"]; ok {
  3986. dataexcel["5"] = outentry["第五班比例(%)"]
  3987. }
  3988. if _, ok := outentry["第六班比例(%)"]; ok {
  3989. dataexcel["6"] = outentry["第六班比例(%)"]
  3990. }
  3991. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3992. if err != nil {
  3993. logs.Error(err)
  3994. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3995. return
  3996. }
  3997. if !existbar {
  3998. continue
  3999. }
  4000. _, err = tx.SQL(` update feedp fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
  4001. if err != nil {
  4002. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4003. return
  4004. }
  4005. _, err = tx.SQL(` update fpdetail fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
  4006. if err != nil {
  4007. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4008. return
  4009. }
  4010. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4011. if err != nil {
  4012. logs.Error(err)
  4013. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4014. return
  4015. }
  4016. if !existft {
  4017. continue
  4018. }
  4019. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4020. if err != nil {
  4021. logs.Error(err)
  4022. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4023. return
  4024. }
  4025. if !ftexist {
  4026. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4027. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4028. if err != nil {
  4029. logs.Error(err)
  4030. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4031. return
  4032. }
  4033. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4034. if err != nil {
  4035. logs.Error(err)
  4036. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4037. return
  4038. }
  4039. }
  4040. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4041. if err != nil {
  4042. logs.Error(err)
  4043. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4044. return
  4045. }
  4046. if !exist {
  4047. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4048. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4049. if err != nil {
  4050. logs.Error(err)
  4051. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4052. return
  4053. }
  4054. }
  4055. var feedpargs []interface{}
  4056. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4057. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4058. if _, ok := dataexcel["ftname"]; ok {
  4059. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4060. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4061. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4062. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4063. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4064. } else {
  4065. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4066. }
  4067. if _, ok := dataexcel["ptsfname"]; ok {
  4068. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4069. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4070. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4071. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4072. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4073. } else {
  4074. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4075. }
  4076. upFeedpSql += " where barname = ? and pastureid = ? "
  4077. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4078. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4079. if err != nil {
  4080. logs.Error(err)
  4081. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4082. return
  4083. }
  4084. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4085. if err != nil {
  4086. logs.Error(err)
  4087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4088. return
  4089. }
  4090. if !exist1 {
  4091. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  4092. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4093. if err != nil {
  4094. logs.Error(err)
  4095. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4096. return
  4097. }
  4098. }
  4099. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4100. if err != nil {
  4101. logs.Error(err)
  4102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4103. return
  4104. }
  4105. if !exist2 {
  4106. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  4107. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4108. if err != nil {
  4109. logs.Error(err)
  4110. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4111. return
  4112. }
  4113. }
  4114. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4115. if err != nil {
  4116. logs.Error(err)
  4117. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4118. return
  4119. }
  4120. if !exist3 {
  4121. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  4122. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4123. if err != nil {
  4124. logs.Error(err)
  4125. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4126. return
  4127. }
  4128. }
  4129. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4130. if err != nil {
  4131. logs.Error(err)
  4132. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4133. return
  4134. }
  4135. if !exist4 {
  4136. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  4137. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4138. if err != nil {
  4139. logs.Error(err)
  4140. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4141. return
  4142. }
  4143. }
  4144. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4145. if err != nil {
  4146. logs.Error(err)
  4147. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4148. return
  4149. }
  4150. if !exist5 {
  4151. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  4152. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4153. if err != nil {
  4154. logs.Error(err)
  4155. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4156. return
  4157. }
  4158. }
  4159. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4160. if err != nil {
  4161. logs.Error(err)
  4162. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4163. return
  4164. }
  4165. if !exist6 {
  4166. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  4167. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4168. if err != nil {
  4169. logs.Error(err)
  4170. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4171. return
  4172. }
  4173. }
  4174. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4175. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4176. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4177. and pastureid = ? and times = ?`
  4178. var fpdargs1 []interface{}
  4179. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4180. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4181. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4182. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4183. if err != nil {
  4184. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4185. return
  4186. }
  4187. var fpdargs2 []interface{}
  4188. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4189. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4190. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4191. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4192. if err != nil {
  4193. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4194. return
  4195. }
  4196. var fpdargs3 []interface{}
  4197. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4198. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4199. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4200. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4201. if err != nil {
  4202. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4203. return
  4204. }
  4205. var fpdargs4 []interface{}
  4206. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4207. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4208. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4209. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4210. if err != nil {
  4211. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4212. return
  4213. }
  4214. var fpdargs5 []interface{}
  4215. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4216. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4217. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4218. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4219. if err != nil {
  4220. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4221. return
  4222. }
  4223. var fpdargs6 []interface{}
  4224. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4225. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4226. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4227. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4228. if err != nil {
  4229. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4230. return
  4231. }
  4232. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4233. newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  4234. if err != nil {
  4235. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4236. return
  4237. }
  4238. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4239. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4240. upFpdetailList := make([]*upFpdetail, 0)
  4241. for _, newfpd := range newList {
  4242. for _, oldfpd := range oldFpdList {
  4243. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4244. var oldweight, newweight float64
  4245. if oldfpd["weight"] != nil {
  4246. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4247. }
  4248. if newfpd["weight"] != nil {
  4249. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4250. }
  4251. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4252. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4253. Old: oldweight,
  4254. New: newweight,
  4255. Times: newfpd["times"].(int64),
  4256. Ptid: newfpd["ptid"].(int64),
  4257. Fweight: fweight,
  4258. Id: oldfpd["id"].(int64),
  4259. })
  4260. break
  4261. }
  4262. }
  4263. }
  4264. // fmt.Println(dataexcel["barname"])
  4265. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4266. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4267. }
  4268. }
  4269. if !isdone {
  4270. ok++
  4271. isdone = true
  4272. }
  4273. }
  4274. for barname, v := range dataList {
  4275. updateFpdetailByBar(pastureid, barname, v)
  4276. }
  4277. data := make(map[string]interface{})
  4278. data["result"] = queryData
  4279. data["success"] = ok
  4280. data["err_count"] = error
  4281. appG.Response(http.StatusOK, e.SUCCESS, data)
  4282. }
  4283. type upFpdetail struct {
  4284. Old float64
  4285. New float64
  4286. Times int64
  4287. Ptid int64
  4288. Fweight float64
  4289. Id int64
  4290. // Ptsid string
  4291. }
  4292. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4293. tx := restful.Engine.NewSession()
  4294. defer tx.Close()
  4295. tx.Begin()
  4296. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ifnull(ptsrate,0))*weight,2),"") weight,ptuse,times from fpdetail where pastureid = ? and barname = ? order by times `,
  4297. pastureid, barname).Query().List()
  4298. if err != nil {
  4299. logs.Error(err)
  4300. }
  4301. for _, fpd := range fpdList {
  4302. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4303. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4304. pastureid, fpd["id"], fpd["times"]).Query().List()
  4305. if err != nil {
  4306. tx.Rollback()
  4307. logs.Error(err)
  4308. return err
  4309. }
  4310. var lweight float64
  4311. for _, lppland := range lpplandList {
  4312. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4313. lweight += lweight1
  4314. }
  4315. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4316. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4317. if fpdweight >= ptuse && lweight == ptuse {
  4318. continue
  4319. } else {
  4320. if lweight <= fpdweight {
  4321. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4322. if err != nil {
  4323. tx.Rollback()
  4324. logs.Error(err)
  4325. return err
  4326. }
  4327. } else {
  4328. weight := lweight - fpdweight
  4329. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4330. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4331. if err != nil {
  4332. tx.Rollback()
  4333. logs.Error(err)
  4334. return err
  4335. }
  4336. for _, lppland := range lpplandList {
  4337. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4338. if weight >= lpplandlweight {
  4339. weight = weight - lpplandlweight
  4340. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4341. if err != nil {
  4342. tx.Rollback()
  4343. logs.Error(err)
  4344. return err
  4345. }
  4346. } else {
  4347. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4348. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4349. if err != nil {
  4350. tx.Rollback()
  4351. logs.Error(err)
  4352. return err
  4353. }
  4354. weight = 0
  4355. break
  4356. }
  4357. }
  4358. }
  4359. }
  4360. }
  4361. for _, list := range dataList {
  4362. ftmap := make(map[string]interface{})
  4363. ftmap["old"] = list.Old
  4364. ftmap["new"] = list.New
  4365. ftmap["times"] = list.Times
  4366. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4367. ftmap["ptsid"] = ""
  4368. // fmt.Println(ftmap)
  4369. // select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  4370. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4371. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4372. // UNION
  4373. fpdDataList, err := tx.SQL(`
  4374. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  4375. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4376. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  4377. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4378. if err != nil {
  4379. tx.Rollback()
  4380. logs.Error(err)
  4381. }
  4382. for _, fpd := range fpdDataList {
  4383. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4384. // fttype := -1
  4385. // if fpd["fttype"].(string) == "1" {
  4386. fttype := 1
  4387. // }
  4388. var fweight float64
  4389. var lweight float64
  4390. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4391. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  4392. join lpplandtl1 lppland on lpp.id = lppland.lppid
  4393. join tmr t on t.id = lpp.tmrid
  4394. where lppland.fpdid =?
  4395. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4396. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4397. if err != nil {
  4398. tx.Rollback()
  4399. logs.Error(err)
  4400. }
  4401. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  4402. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  4403. // barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:1 id:4828050527277810688 isfill:0 pastureid:1705635208 ptid:83 ptsid:-1 times:1 tratio:48.000 weight:32.0
  4404. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4405. var w float64
  4406. var status int
  4407. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  4408. if weight >= 0 {
  4409. continue
  4410. }
  4411. w = weight
  4412. status = 0
  4413. } else {
  4414. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4415. // continue
  4416. // }
  4417. w = weight
  4418. status = 1
  4419. }
  4420. // for _, lppland := range lpplandtl1List {
  4421. // lweight += lppland.Lweight
  4422. // }
  4423. for _, lppland := range lpplandtl1List {
  4424. lpplandInfo := new(lpplandtlInfo)
  4425. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  4426. lweight = lpplandInfo.Lweight
  4427. if status == 1 {
  4428. // if w <= lppland.Lweight {
  4429. if lppland.Maxweight <= lweight {
  4430. continue
  4431. }
  4432. if w+lweight <= lppland.Maxweight {
  4433. lppland.Lweight += w
  4434. lweight += w
  4435. fweight += w
  4436. w = 0
  4437. } else {
  4438. w = w - (lppland.Maxweight - lweight)
  4439. n := (lppland.Maxweight - lweight)
  4440. lppland.Lweight = lppland.Lweight + n
  4441. lweight += n
  4442. fweight += n
  4443. }
  4444. } else {
  4445. if lppland.Lweight == 0 {
  4446. continue
  4447. }
  4448. if w+lppland.Lweight >= 0 {
  4449. lppland.Lweight = lppland.Lweight + w
  4450. lweight = lweight + w
  4451. fweight = fweight + w
  4452. w = 0
  4453. } else {
  4454. w = w + lppland.Lweight
  4455. lweight = lweight - lppland.Lweight
  4456. fweight = fweight - lppland.Lweight
  4457. lppland.Lweight = 0
  4458. }
  4459. }
  4460. if lppland.Lweight > 0 {
  4461. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4462. if err != nil {
  4463. tx.Rollback()
  4464. logs.Error(err)
  4465. return err
  4466. }
  4467. } else {
  4468. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  4469. if err != nil {
  4470. tx.Rollback()
  4471. logs.Error(err)
  4472. return err
  4473. }
  4474. }
  4475. if w == 0 {
  4476. break
  4477. }
  4478. }
  4479. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4480. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4481. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4482. if err != nil {
  4483. tx.Rollback()
  4484. logs.Error(err)
  4485. }
  4486. if w == 0 {
  4487. break
  4488. }
  4489. }
  4490. }
  4491. }
  4492. // for _, data := range dataList {
  4493. // fttype := -1
  4494. // if data.Ptid != -1 {
  4495. // fttype = 1
  4496. // }
  4497. // var fweight float64
  4498. // var lweight float64
  4499. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4500. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4501. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4502. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4503. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4504. // if err != nil {
  4505. // tx.Rollback()
  4506. // logs.Error(err)
  4507. // return err
  4508. // }
  4509. // weight := data.Fweight
  4510. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4511. // var w float64
  4512. // var status int
  4513. // if data.New < data.Old {
  4514. // if weight >= 0 {
  4515. // continue
  4516. // }
  4517. // w = weight
  4518. // status = 0
  4519. // } else {
  4520. // // if weight-(data.New-data.Old) > 0 {
  4521. // // continue
  4522. // // }
  4523. // w = data.New - data.Old
  4524. // status = 1
  4525. // }
  4526. // for _, lppland := range lpplandtl1List {
  4527. // var lppdata lpplandtlInfo
  4528. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4529. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4530. // if err != nil {
  4531. // tx.Rollback()
  4532. // logs.Error(err)
  4533. // return err
  4534. // }
  4535. // lweight = lppdata.Lweight
  4536. // if status == 1 {
  4537. // // if w <= lppland.Lweight {
  4538. // if lppland.Maxweight <= lweight {
  4539. // continue
  4540. // }
  4541. // if w+lweight <= lppland.Maxweight {
  4542. // lppland.Lweight += w
  4543. // lweight += w
  4544. // fweight += w
  4545. // w = 0
  4546. // } else {
  4547. // w = w - (lppland.Maxweight - lweight)
  4548. // n := (lppland.Maxweight - lweight)
  4549. // lppland.Lweight = lppland.Lweight + n
  4550. // lweight += n
  4551. // fweight += n
  4552. // }
  4553. // } else {
  4554. // if lppland.Lweight == 0 {
  4555. // continue
  4556. // }
  4557. // if w+lppland.Lweight >= 0 {
  4558. // lppland.Lweight = lppland.Lweight + w
  4559. // lweight = lweight + w
  4560. // fweight = fweight + w
  4561. // w = 0
  4562. // } else {
  4563. // w = w + lppland.Lweight
  4564. // lweight = lweight - lppland.Lweight
  4565. // fweight = fweight - lppland.Lweight
  4566. // lppland.Lweight = 0
  4567. // }
  4568. // }
  4569. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4570. // if err != nil {
  4571. // tx.Rollback()
  4572. // logs.Error(err)
  4573. // return err
  4574. // }
  4575. // break
  4576. // }
  4577. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4578. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4579. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4580. // if err != nil {
  4581. // tx.Rollback()
  4582. // logs.Error(err)
  4583. // return err
  4584. // }
  4585. // // if w == 0 {
  4586. // // break
  4587. // // }
  4588. // // }
  4589. // }
  4590. err = tx.Commit()
  4591. if err != nil {
  4592. logs.Error(err)
  4593. tx.Rollback()
  4594. return err
  4595. }
  4596. now := time.Now()
  4597. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4598. if err != nil {
  4599. logs.Error(err)
  4600. return nil
  4601. }
  4602. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4603. if err != nil {
  4604. logs.Error(err)
  4605. return nil
  4606. }
  4607. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4608. if err != nil {
  4609. logs.Error(err)
  4610. return nil
  4611. }
  4612. for _, newLpplandtl1 := range newLpplandtl1List {
  4613. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4614. background,cowcount,ccountradio,lweighthis,createdate)
  4615. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4616. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4617. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4618. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4619. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4620. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4621. if err != nil {
  4622. logs.Error(err)
  4623. // appG.Response(http.StatusOK, e.ERROR, false)
  4624. return err
  4625. }
  4626. }
  4627. for _, newFpd := range newFpdDataList {
  4628. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4629. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4630. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4631. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4632. if err != nil {
  4633. logs.Error(err)
  4634. // appG.Response(http.StatusOK, e.ERROR, false)
  4635. return err
  4636. }
  4637. }
  4638. for _, newFeedp := range newFeedpList {
  4639. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4640. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4641. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4642. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4643. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4644. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4645. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4646. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4647. if err != nil {
  4648. logs.Error(err)
  4649. // appG.Response(http.StatusOK, e.ERROR, false)
  4650. return err
  4651. }
  4652. }
  4653. return nil
  4654. }
  4655. func DeleteFTdetail(c *gin.Context) {
  4656. appG := app.Gin{C: c}
  4657. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4658. fsion := gofasion.NewFasion(string(dataByte))
  4659. parammaps := fsion.Get("parammaps")
  4660. pastureid := parammaps.Get("pastureid").ValueStr()
  4661. ftid := parammaps.Get("ftid").ValueStr()
  4662. tx := restful.Engine.NewSession()
  4663. defer tx.Close()
  4664. tx.Begin()
  4665. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4666. if err != nil {
  4667. tx.Rollback()
  4668. logs.Error(err)
  4669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4670. return
  4671. }
  4672. if parammaps.Get("type").ValueStr() == "1" {
  4673. _, err := tx.SQL(`UPDATE feedp fp
  4674. set
  4675. fp.ftweight= IFNULL(IF(
  4676. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4677. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4678. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4679. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4680. ),0),fp.feedweight = IFNULL(IF(
  4681. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4682. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4683. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4684. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4685. ),0) +ifnull(fp.supplyweight,0)
  4686. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4687. if err != nil {
  4688. tx.Rollback()
  4689. logs.Error(err)
  4690. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4691. return
  4692. }
  4693. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4694. _, err = tx.SQL(`
  4695. UPDATE fpdetail fpd
  4696. INNER JOIN feedp fp
  4697. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4698. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4699. ptuse= 0
  4700. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4701. if err != nil {
  4702. tx.Rollback()
  4703. logs.Error(err)
  4704. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4705. return
  4706. }
  4707. } else {
  4708. _, err := tx.SQL(`UPDATE feedp fp
  4709. SET
  4710. fp.supplyweight= IFNULL(IF(
  4711. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4712. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4713. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4714. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4715. ),0),fp.feedweight = IFNULL(IF(
  4716. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4717. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4718. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4719. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4720. ),0) + ifnull(fp.supplyweight,0)
  4721. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4722. if err != nil {
  4723. tx.Rollback()
  4724. logs.Error(err)
  4725. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4726. return
  4727. }
  4728. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4729. _, err = tx.SQL(`
  4730. UPDATE fpdetail fpd
  4731. INNER JOIN feedp fp
  4732. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4733. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4734. ptsrate = 0
  4735. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4736. if err != nil {
  4737. tx.Rollback()
  4738. logs.Error(err)
  4739. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4740. return
  4741. }
  4742. }
  4743. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4744. if err != nil {
  4745. tx.Rollback()
  4746. logs.Error(err)
  4747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4748. return
  4749. }
  4750. err = tx.Commit()
  4751. if err != nil {
  4752. tx.Rollback()
  4753. logs.Error(err)
  4754. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4755. return
  4756. }
  4757. appG.Response(http.StatusOK, e.SUCCESS, true)
  4758. }
  4759. func DeleteSpillageAll(c *gin.Context) {
  4760. appG := app.Gin{C: c}
  4761. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4762. fsion := gofasion.NewFasion(string(dataByte))
  4763. parammaps := fsion.Get("parammaps")
  4764. pastureid := parammaps.Get("pastureid").ValueStr()
  4765. times := parammaps.Get("times").ValueStr()
  4766. barid := parammaps.Get("barid").ValueStr()
  4767. tx := restful.Engine.NewSession()
  4768. defer tx.Close()
  4769. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4770. if err != nil {
  4771. logs.Error(err)
  4772. appG.Response(http.StatusOK, e.ERROR, false)
  4773. return
  4774. }
  4775. now := time.Now()
  4776. for _, item := range lpplandtl1List {
  4777. go func(item map[string]interface{}) {
  4778. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4779. background,cowcount,ccountradio,lweighthis,createdate)
  4780. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4781. item["pastureid"], item["lppid"], item["barid"],
  4782. item["barname"], item["fpdid"], item["fttype"],
  4783. item["lweight"], item["sort"], item["tmrid"],
  4784. item["tmrname"], item["background"], item["cowcount"],
  4785. item["ccountradio"], item["lweighthis"], now).Execute()
  4786. if err != nil {
  4787. logs.Error(err)
  4788. appG.Response(http.StatusOK, e.ERROR, false)
  4789. return
  4790. }
  4791. }(item)
  4792. }
  4793. tx.Begin()
  4794. _, err = tx.SQL(` delete from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ?) and find_in_set(barid,?) `, pastureid, pastureid, times, barid).Execute()
  4795. if err != nil {
  4796. tx.Rollback()
  4797. logs.Error(err)
  4798. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4799. return
  4800. }
  4801. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4802. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4803. if err != nil {
  4804. tx.Rollback()
  4805. logs.Error(err)
  4806. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4807. return
  4808. }
  4809. err = tx.Commit()
  4810. if err != nil {
  4811. tx.Rollback()
  4812. logs.Error(err)
  4813. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4814. return
  4815. }
  4816. appG.Response(http.StatusOK, e.SUCCESS, true)
  4817. }
  4818. func GetTMRListEnableTypeAll(c *gin.Context) {
  4819. appG := app.Gin{C: c}
  4820. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4821. fsion := gofasion.NewFasion(string(dataByte))
  4822. parammaps := fsion.Get("parammaps")
  4823. pastureid := parammaps.Get("pastureid").ValueStr()
  4824. tx := restful.Engine.NewSession()
  4825. defer tx.Close()
  4826. dataList, err := tx.SQL(`SELECT
  4827. eqcode,
  4828. tname,
  4829. datacaptureno,
  4830. trim(tclassid) tclassid,
  4831. concat(tname,' / ',eqcode) tmrmix,
  4832. d.label tclassname,
  4833. maxstirfeed,
  4834. remark,
  4835. tmr.enable,
  4836. TRIM(tmr.id) id,
  4837. TRIM(tmr.pastureid)pastureid
  4838. FROM
  4839. tmr
  4840. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4841. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4842. ORDER BY id DESC`, pastureid).Query().List()
  4843. if err != nil {
  4844. logs.Error(err)
  4845. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4846. return
  4847. }
  4848. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4849. if err != nil {
  4850. logs.Error(err)
  4851. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4852. return
  4853. }
  4854. var carNum int64
  4855. for _, sysopt := range sysoptData {
  4856. if sysopt["inforvalue"] == nil {
  4857. carNum = 1
  4858. } else {
  4859. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4860. }
  4861. }
  4862. id := 200
  4863. n := 0
  4864. for i := carNum; i > 0; i-- {
  4865. id++
  4866. n++
  4867. data := make(map[string]interface{}, 0)
  4868. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4869. data["tname"] = fmt.Sprintf("任意车%d", n)
  4870. data["datacaptureno"] = -2
  4871. data["tclassid"] = -2
  4872. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4873. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4874. data["maxstirfeed"] = 100000
  4875. data["remark"] = fmt.Sprintf("任意车%d", n)
  4876. data["enable"] = 1
  4877. data["id"] = fmt.Sprintf("%d", id)
  4878. data["pastureid"] = pastureid
  4879. dataList = append(dataList, data)
  4880. }
  4881. // UNION ALL
  4882. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4883. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4884. }
  4885. func GetFeedpHistory(c *gin.Context) {
  4886. appG := app.Gin{C: c}
  4887. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4888. fsion := gofasion.NewFasion(string(dataByte))
  4889. // parammaps := fsion.Get("parammaps")
  4890. bar := fsion.Get("barname").ValueStr()
  4891. startDate := fsion.Get("startDate").ValueStr()
  4892. endDate := fsion.Get("endDate").ValueStr()
  4893. tx := restful.Engine.NewSession()
  4894. defer tx.Close()
  4895. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4896. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  4897. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4898. if err != nil {
  4899. logs.Error(err)
  4900. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4901. return
  4902. }
  4903. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  4904. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  4905. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4906. if err != nil {
  4907. logs.Error(err)
  4908. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4909. return
  4910. }
  4911. for _, feedp := range feedpList {
  4912. // LastftList, err := tx.SQL(` select tname ,id
  4913. // from feedtemplethistory where id = ?
  4914. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4915. // if err != nil {
  4916. // logs.Error(err)
  4917. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4918. // return
  4919. // }
  4920. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4921. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4922. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4923. if err != nil {
  4924. logs.Error(err)
  4925. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4926. return
  4927. }
  4928. var ftname interface{}
  4929. ftnamestatus := 0
  4930. ftname = feedp["ftname"]
  4931. var lastftid int64
  4932. if len(nextfeedpList) > 0 {
  4933. for _, ft := range nextfeedpList {
  4934. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4935. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4936. lastftid = ft["ftid"].(int64)
  4937. ftnamestatus = 1
  4938. break
  4939. }
  4940. }
  4941. }
  4942. for i, fpd := range fpdList {
  4943. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4944. fpd["weightstatus"] = 0
  4945. fpd["tratiostatus"] = 0
  4946. fpd["ftnamestatus"] = ftnamestatus
  4947. for k, fpd2 := range fpdList {
  4948. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4949. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4950. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4951. fpd["weightstatus"] = 1
  4952. }
  4953. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4954. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4955. fpd["tratiostatus"] = 1
  4956. }
  4957. break
  4958. }
  4959. }
  4960. fpd["barid"] = feedp["barid"]
  4961. fpd["barname"] = feedp["barname"]
  4962. fpd["ccount"] = feedp["ccount"]
  4963. fpd["ratio"] = feedp["ratio"]
  4964. fpd["ccountratio"] = feedp["ccountratio"]
  4965. fpd["ftid"] = feedp["ftid"]
  4966. fpd["ftname"] = ftname
  4967. fpd["ccountstatus"] = 0
  4968. fpd["ccountratiostatus"] = 0
  4969. fpd["ratiostatus"] = 0
  4970. fpd["ftnamestatus"] = 0
  4971. fpd["lastftid"] = lastftid
  4972. for _, next := range nextfeedpList {
  4973. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4974. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4975. fpd["ccountstatus"] = 1
  4976. }
  4977. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4978. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4979. fpd["ccountratiostatus"] = 1
  4980. }
  4981. if next["ratio"].(string) != fpd["ratio"].(string) {
  4982. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4983. fpd["ratiostatus"] = 1
  4984. }
  4985. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4986. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4987. // fpd["ftnamestatus"] = 1
  4988. // }
  4989. }
  4990. }
  4991. }
  4992. }
  4993. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4994. }
  4995. // func GetLpplandtl1History(c *gin.Context) {
  4996. // appG := app.Gin{C: c}
  4997. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4998. // fsion := gofasion.NewFasion(string(dataByte))
  4999. // // parammaps := fsion.Get("parammaps")
  5000. // barid := fsion.Get("barid").ValueStr()
  5001. // startDate := fsion.Get("startDate").ValueStr()
  5002. // endDate := fsion.Get("endDate").ValueStr()
  5003. // tx := restful.Engine.NewSession()
  5004. // defer tx.Close()
  5005. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5006. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5007. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5008. // // if err != nil {
  5009. // // logs.Error(err)
  5010. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5011. // // return
  5012. // // }
  5013. // // for _, feedp := range feedpList {
  5014. // // fmt.Println(feedp)
  5015. // // for i, fpd := range fpdList {
  5016. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5017. // // for k, fpd2 := range fpdList {
  5018. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5019. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5020. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5021. // // }
  5022. // // break
  5023. // // }
  5024. // // }
  5025. // // fpd["barid"] = feedp["barid"]
  5026. // // fpd["barname"] = feedp["barname"]
  5027. // // fpd["ccount"] = feedp["ccount"]
  5028. // // fpd["ratio"] = feedp["ratio"]
  5029. // // fpd["ccountratio"] = feedp["ccountratio"]
  5030. // // fpd["ftid"] = feedp["ftid"]
  5031. // // fpd["ftname"] = feedp["ftname"]
  5032. // // }
  5033. // // }
  5034. // // }
  5035. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5036. // }
  5037. func GetRemind(c *gin.Context) {
  5038. appG := app.Gin{C: c}
  5039. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5040. fsion := gofasion.NewFasion(string(dataByte))
  5041. parammaps := fsion.Get("parammaps")
  5042. pastureid := parammaps.Get("pastureid").ValueStr()
  5043. tx := restful.Engine.NewSession()
  5044. defer tx.Close()
  5045. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5046. if err != nil {
  5047. logs.Error(err)
  5048. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5049. return
  5050. }
  5051. // pastureid = "3"
  5052. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5053. if err != nil {
  5054. logs.Error(err)
  5055. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5056. return
  5057. }
  5058. defer resp.Body.Close()
  5059. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5060. buf.ReadFrom(resp.Body)
  5061. fmt.Println(string(buf.Bytes()))
  5062. respMap := make(map[string]interface{}, 0)
  5063. err = json.Unmarshal(buf.Bytes(), &respMap)
  5064. if err != nil {
  5065. logs.Error(err)
  5066. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5067. return
  5068. }
  5069. for _, data := range dataList {
  5070. r := make(map[string]interface{}, 0)
  5071. r["sys_name"] = ""
  5072. r["service_id"] = ""
  5073. r["pasture_id"] = ""
  5074. r["type_name"] = ""
  5075. r["remind_type_id"] = ""
  5076. r["remind_type"] = ""
  5077. r["push_date"] = ""
  5078. r["push_time"] = ""
  5079. r["interval_time"] = ""
  5080. r["push_limit"] = ""
  5081. r["template_id"] = ""
  5082. r["roles_id"] = ""
  5083. r["users_id"] = ""
  5084. r["date_type"] = ""
  5085. r["cycle_type"] = ""
  5086. data["data"] = r
  5087. for _, resp := range respMap["data"].([]interface{}) {
  5088. resp1 := resp.(map[string]interface{})
  5089. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5090. if resp1["push_time"] == nil {
  5091. resp1["push_time"] = ""
  5092. }
  5093. data["data"] = resp1
  5094. break
  5095. }
  5096. }
  5097. }
  5098. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5099. }
  5100. type NoticeMsgtype struct {
  5101. SysName string `json:"sys_name"`
  5102. PastureId int64 `json:"pasture_id"`
  5103. ServiceId int64 `json:"service_id"`
  5104. TypeName string `json:"type_name"`
  5105. RemindType int64 `json:"remind_type"`
  5106. PushDate int64 `json:"push_date"`
  5107. PushTime string `json:"push_time"`
  5108. IntervalTime int64 `json:"interval_time"`
  5109. PushLimit int64 `json:"push_limit"`
  5110. TemplateId string `json:"template_id"`
  5111. UsersId string `json:"users_id"`
  5112. DateType int64 `json:"date_type"`
  5113. CycleType int64 `json:"cycle_type"`
  5114. DelayTime int64 `json:"delay_time"`
  5115. Status int64 `json:"status"`
  5116. }
  5117. func UpdateRemind(c *gin.Context) {
  5118. appG := app.Gin{C: c}
  5119. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5120. parammaps := gofasion.NewFasion(string(dataByte))
  5121. // parammaps := fsion.Get("parammaps")
  5122. // user := parammaps.Get("user").ValueStr()
  5123. id := parammaps.Get("id").ValueInt64()
  5124. noticeMsgtype := new(NoticeMsgtype)
  5125. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5126. noticeMsgtype.ServiceId = id
  5127. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5128. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5129. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5130. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5131. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5132. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5133. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5134. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5135. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5136. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5137. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5138. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5139. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5140. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5141. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5142. //TODO
  5143. noticeMsgtype.SysName = "tmrWatch"
  5144. userList := parammaps.Get("user").Array()
  5145. var userstr []string
  5146. for _, user := range userList {
  5147. userstr = append(userstr, user.ValueStr())
  5148. }
  5149. tx := restful.Engine.NewSession()
  5150. defer tx.Close()
  5151. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5152. if err != nil {
  5153. logs.Error(err)
  5154. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5155. return
  5156. }
  5157. // var jsonStr = []byte(noticeMsgtype
  5158. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5159. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5160. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5161. req.Header.Set("Content-Type", "application/json")
  5162. client := &http.Client{}
  5163. resp, err := client.Do(req)
  5164. if err != nil {
  5165. logs.Error(err)
  5166. }
  5167. defer resp.Body.Close()
  5168. body, _ := ioutil.ReadAll(resp.Body)
  5169. fmt.Println("response Body:", string(body))
  5170. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5171. if err != nil {
  5172. logs.Error(err)
  5173. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5174. return
  5175. }
  5176. defer getresp.Body.Close()
  5177. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5178. buf.ReadFrom(getresp.Body)
  5179. // fmt.Println(string(buf.Bytes()))
  5180. respMap := make(map[string]interface{}, 0)
  5181. err = json.Unmarshal(buf.Bytes(), &respMap)
  5182. if err != nil {
  5183. logs.Error(err)
  5184. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5185. return
  5186. }
  5187. for _, resp := range respMap["data"].([]interface{}) {
  5188. resp1 := resp.(map[string]interface{})
  5189. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5190. if err != nil {
  5191. logs.Error(err)
  5192. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5193. return
  5194. }
  5195. }
  5196. appG.Response(http.StatusOK, e.SUCCESS, true)
  5197. }
  5198. func GetSpillageallHistory(c *gin.Context) {
  5199. appG := app.Gin{C: c}
  5200. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5201. parammaps := gofasion.NewFasion(string(dataByte))
  5202. barname := parammaps.Get("barname").ValueStr()
  5203. pastureid := parammaps.Get("pastureid").ValueStr()
  5204. startdate := parammaps.Get("startDate").ValueStr()
  5205. enddate := parammaps.Get("endDate").ValueStr()
  5206. tx := restful.Engine.NewSession()
  5207. defer tx.Close()
  5208. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate from lpplandtl1history lppland
  5209. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5210. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5211. if err != nil {
  5212. logs.Error(err)
  5213. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5214. return
  5215. }
  5216. respMap := make([]map[string]interface{}, 0)
  5217. data := make(map[interface{}]interface{})
  5218. for _, history := range historyList {
  5219. data[history["createdate"]] = history["createdate"]
  5220. }
  5221. createList := []string{}
  5222. for _, v := range data {
  5223. createList = append(createList, v.(string))
  5224. }
  5225. // sort.Sort()
  5226. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5227. sort.Slice(createList, func(i, j int) bool {
  5228. return createList[i] > createList[j]
  5229. })
  5230. for _, v := range createList {
  5231. a := make(map[string]interface{})
  5232. a["createdate"] = data[v]
  5233. // createList = append(createList, v.(string))
  5234. respMap = append(respMap, a)
  5235. }
  5236. number := 0
  5237. dataMap := make([]interface{}, 0)
  5238. for k, resp := range respMap {
  5239. createdate := resp["createdate"].(string)
  5240. var nextcreatedate string
  5241. if len(respMap) > k+1 {
  5242. nextcreatedate = respMap[k+1]["createdate"].(string)
  5243. }
  5244. // dataList := make(map[string][]interface{})
  5245. // list := make(map[string]interface{})
  5246. times := make(map[interface{}]int)
  5247. for _, history := range historyList {
  5248. // List := make(map[interface{}][]interface{})
  5249. i := 0
  5250. if history["createdate"].(string) == createdate {
  5251. times[history["times"]]++
  5252. data := make(map[string]interface{})
  5253. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5254. // exist := false
  5255. if nextcreatedate != "" {
  5256. for _, history1 := range historyList {
  5257. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5258. history1["times"].(int64) == history["times"].(int64) {
  5259. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  5260. break
  5261. // exist = true
  5262. }
  5263. }
  5264. }
  5265. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5266. i++
  5267. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5268. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5269. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5270. // resp["times"] = history["times"]
  5271. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5272. data1 := make(map[string]interface{})
  5273. data1["times"] = history["times"]
  5274. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5275. data1["createdate"] = resp["createdate"]
  5276. // fmt.Println(dataList)
  5277. dataMap = append(dataMap, data1)
  5278. }
  5279. if i > number {
  5280. number = i
  5281. }
  5282. // respMap = append(respMap, dataList)
  5283. }
  5284. // for k, data := range dataList {
  5285. // resp[k] = data
  5286. // }
  5287. // resp["data"] = dataList
  5288. }
  5289. // resp := make(map[string]interface{})
  5290. // sort.Strings(createList)
  5291. //
  5292. // for _, create := range createList {
  5293. // for _, r := range respMap {
  5294. // if create == r["createdate"].(string) {
  5295. // resp[create] = r
  5296. // break
  5297. // }
  5298. // }
  5299. // }
  5300. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5301. var trainsList []interface{}
  5302. for i := 0; i < number; i++ {
  5303. trains := make(map[string]interface{})
  5304. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5305. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5306. trainsList = append(trainsList, trains)
  5307. }
  5308. respdata := make(map[string]interface{})
  5309. respdata["data"] = dataMap
  5310. respdata["trains"] = trainsList
  5311. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5312. }
  5313. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5314. appG := app.Gin{C: c}
  5315. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5316. parammaps := gofasion.NewFasion(string(dataByte))
  5317. ftid := parammaps.Get("ftid").ValueInt64()
  5318. lastftid := parammaps.Get("lastftid").ValueInt64()
  5319. pastureid := parammaps.Get("pastureid").ValueInt64()
  5320. // createdate := parammaps.Get("createdate").ValueStr()
  5321. tx := restful.Engine.NewSession()
  5322. defer tx.Close()
  5323. data := make(map[string]interface{})
  5324. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5325. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5326. if err != nil {
  5327. logs.Error(err)
  5328. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5329. return
  5330. }
  5331. feedtemplet := make(map[string]interface{})
  5332. for _, f := range feedtempletList {
  5333. feedtemplet = f
  5334. }
  5335. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5336. if err != nil {
  5337. logs.Error(err)
  5338. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5339. return
  5340. }
  5341. feedtemplet["fit"] = fitList
  5342. data["current"] = feedtemplet
  5343. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5344. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5345. if err != nil {
  5346. logs.Error(err)
  5347. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5348. return
  5349. }
  5350. lastfeedtemplet := make(map[string]interface{})
  5351. for _, f := range lastfeedtempletList {
  5352. lastfeedtemplet = f
  5353. }
  5354. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5355. if err != nil {
  5356. logs.Error(err)
  5357. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5358. return
  5359. }
  5360. lastfeedtemplet["fit"] = lastfitList
  5361. data["last"] = lastfeedtemplet
  5362. appG.Response(http.StatusOK, e.SUCCESS, data)
  5363. }
  5364. func GetFeedtempletHistory(c *gin.Context) {
  5365. appG := app.Gin{C: c}
  5366. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5367. parammaps := gofasion.NewFasion(string(dataByte))
  5368. ftid := parammaps.Get("ftid").ValueStr()
  5369. pastureid := parammaps.Get("pastureid").ValueInt64()
  5370. start := parammaps.Get("startdate").ValueStr()
  5371. end := parammaps.Get("enddate").ValueStr()
  5372. tx := restful.Engine.NewSession()
  5373. defer tx.Close()
  5374. ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1,(select empname from user where id = feedtemplethistory.userId) empname from feedtemplethistory where createdate between ? and ?
  5375. and id = ? and pastureid = ? order by createdate desc `,
  5376. start, end, ftid, pastureid).Query().List()
  5377. if err != nil {
  5378. logs.Error(err)
  5379. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5380. return
  5381. }
  5382. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5383. ftid, pastureid).Query().List()
  5384. if err != nil {
  5385. logs.Error(err)
  5386. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5387. return
  5388. }
  5389. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5390. for i, ft := range ftList {
  5391. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5392. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5393. (select empname from user where id = fit.userId) empname,
  5394. ifnull(fit.autosecond ,( select ft.autosecond from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as autosecond from fit_history fit
  5395. where fit.fitid = ?
  5396. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5397. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5398. if err != nil {
  5399. logs.Error(err)
  5400. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5401. return
  5402. }
  5403. ft["createdate"] = ft["createdate1"]
  5404. // data["tname"] = ft["tname"]
  5405. // data["tcode"] = ft["tcode"]
  5406. // data["tcolor"] = ft["tcolor"]
  5407. // data["fttype"] = ft["fttype"]
  5408. // data["ccname"] = ft["ccname"]
  5409. // data["source"] = ft["source"]
  5410. // data["version"] = ft["version"]
  5411. // data["remark"] = ft["remark"]
  5412. for n, ft2 := range ftList {
  5413. if i < n {
  5414. if ft["tname"].(string) != ft2["tname"].(string) {
  5415. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5416. }
  5417. if _, ok := ft["tcode"]; ok {
  5418. if _, ok := ft2["tcode"]; ok {
  5419. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5420. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5421. }
  5422. }
  5423. }
  5424. if _, ok := ft["tcolor"]; ok {
  5425. if _, ok := ft2["tcolor"]; ok {
  5426. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5427. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5428. }
  5429. }
  5430. }
  5431. if _, ok := ft["fttype"]; ok {
  5432. if _, ok := ft2["fttype"]; ok {
  5433. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5434. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5435. }
  5436. }
  5437. }
  5438. if _, ok := ft["ccname"]; ok {
  5439. if _, ok := ft2["ccname"]; ok {
  5440. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5441. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5442. }
  5443. }
  5444. }
  5445. if _, ok := ft["source"]; ok {
  5446. if _, ok := ft2["source"]; ok {
  5447. if ft["source"].(string) != ft2["source"].(string) {
  5448. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5449. }
  5450. }
  5451. }
  5452. if _, ok := ft["version"]; ok {
  5453. if _, ok := ft2["version"]; ok {
  5454. if ft["version"].(int64) != ft2["version"].(int64) {
  5455. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5456. }
  5457. }
  5458. }
  5459. if _, ok := ft["remark"]; ok {
  5460. if _, ok := ft2["remark"]; ok {
  5461. if ft["remark"].(string) != ft2["remark"].(string) {
  5462. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5463. }
  5464. }
  5465. }
  5466. break
  5467. }
  5468. }
  5469. dataList := make([]map[string]interface{}, 0)
  5470. if len(fithisList) > 0 {
  5471. for _, fit := range fithisList {
  5472. data := make(map[string]interface{})
  5473. data["feedgroup"] = fit["feedgroup"]
  5474. data["fname"] = fit["fname"]
  5475. data["empname"] = fit["empname"]
  5476. if fit["Eweight"] != nil {
  5477. if fit["Eweight"].(string) != fit["weight"].(string) {
  5478. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5479. } else {
  5480. data["fweight"] = fit["Eweight"]
  5481. }
  5482. data["fweightstatus"] = 1
  5483. } else {
  5484. data["fweight"] = fit["weight"]
  5485. data["fweightstatus"] = 0
  5486. }
  5487. data["autosecond"] = fit["autosecond"]
  5488. // data["tname"] = ft["tname"]
  5489. // data["tcode"] = ft["tcode"]
  5490. // data["tcolor"] = ft["tcolor"]
  5491. // data["fttype"] = ft["fttype"]
  5492. // data["ccname"] = ft["ccname"]
  5493. // data["source"] = ft["source"]
  5494. // data["version"] = ft["version"]
  5495. // data["remark"] = ft["remark"]
  5496. // data["createdate"] = ft["createdate1"]
  5497. // ft["fit"] = data
  5498. dataList = append(dataList, data)
  5499. }
  5500. } else {
  5501. for _, fit := range ftdetailList {
  5502. data := make(map[string]interface{})
  5503. data["feedgroup"] = fit["feedgroup"]
  5504. data["fname"] = fit["fname"]
  5505. // if fit["Eweight"] != nil {
  5506. // data["weight"] = fit["Eweight"]
  5507. // } else {
  5508. data["fweight"] = fit["fweight"]
  5509. // }
  5510. data["autosecond"] = fit["autosecond"]
  5511. // ft["fit"] = data
  5512. dataList = append(dataList, data)
  5513. }
  5514. }
  5515. ft["fit"] = dataList
  5516. }
  5517. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5518. }
  5519. func UpdateMaterialTMR(c *gin.Context) {
  5520. appG := app.Gin{C: c}
  5521. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5522. parammaps := gofasion.NewFasion(string(dataByte))
  5523. tmrid := parammaps.Get("tmrid").ValueStr()
  5524. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5525. lppid := parammaps.Get("lppid").ValueStr()
  5526. times := parammaps.Get("times").ValueStr()
  5527. pastureid := parammaps.Get("pastureid").ValueStr()
  5528. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5529. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5530. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5531. tx := restful.Engine.NewSession()
  5532. defer tx.Close()
  5533. tx.Begin()
  5534. if tmrid != "1000" {
  5535. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5536. if err != nil {
  5537. logs.Error(err)
  5538. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5539. return
  5540. }
  5541. var maxstirfeed float64
  5542. for _, tmr := range tmrList {
  5543. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5544. }
  5545. if status == 0 {
  5546. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5547. if err != nil {
  5548. tx.Rollback()
  5549. logs.Error(err)
  5550. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5551. return
  5552. }
  5553. var lweight float64
  5554. for _, item := range lpplandtl1List {
  5555. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5556. lweight += fl
  5557. }
  5558. if lweight > maxstirfeed {
  5559. lweight = lweight - maxstirfeed
  5560. } else {
  5561. lweight = 0
  5562. }
  5563. if lweight > 0 {
  5564. lweight1 := lweight / float64(len(lpplandtl1List))
  5565. number := 0
  5566. for _, item := range lpplandtl1List {
  5567. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5568. if lweight1 >= fl {
  5569. number++
  5570. }
  5571. }
  5572. lweight := lweight / float64((len(lpplandtl1List) - number))
  5573. for _, item := range lpplandtl1List {
  5574. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5575. if lweight1 >= fl {
  5576. continue
  5577. }
  5578. if tmrtype == "1" {
  5579. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5580. if err != nil {
  5581. tx.Rollback()
  5582. logs.Error(err)
  5583. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5584. return
  5585. }
  5586. } else if tmrtype == "2" {
  5587. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5588. if err != nil {
  5589. tx.Rollback()
  5590. logs.Error(err)
  5591. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5592. return
  5593. }
  5594. }
  5595. if item["fttype"].(int64) == 0 {
  5596. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5597. if err != nil {
  5598. tx.Rollback()
  5599. logs.Error(err)
  5600. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5601. return
  5602. }
  5603. } else {
  5604. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5605. if err != nil {
  5606. tx.Rollback()
  5607. logs.Error(err)
  5608. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5609. return
  5610. }
  5611. }
  5612. }
  5613. } else {
  5614. for _, item := range lpplandtl1List {
  5615. // 自走式
  5616. if tmrtype == "1" {
  5617. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5618. if err != nil {
  5619. logs.Error(err)
  5620. tx.Rollback()
  5621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5622. return
  5623. }
  5624. } else if tmrtype == "2" {
  5625. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5626. if err != nil {
  5627. logs.Error(err)
  5628. tx.Rollback()
  5629. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5630. return
  5631. }
  5632. }
  5633. }
  5634. }
  5635. } else if status == 1 {
  5636. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5637. if err != nil {
  5638. logs.Error(err)
  5639. tx.Rollback()
  5640. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5641. return
  5642. }
  5643. var lweight float64
  5644. for _, item := range lpplandtl1List {
  5645. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5646. lweight += fl
  5647. }
  5648. if lweight > maxstirfeed {
  5649. lweight = lweight - maxstirfeed
  5650. } else {
  5651. lweight = 0
  5652. }
  5653. for _, item := range lpplandtl1List {
  5654. if lweight > 0 {
  5655. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5656. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5657. if fl >= lweight {
  5658. item["lweight"] = fl - lweight
  5659. lweight = 0
  5660. if tmrtype == "1" {
  5661. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5662. if err != nil {
  5663. logs.Error(err)
  5664. tx.Rollback()
  5665. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5666. return
  5667. }
  5668. } else if tmrtype == "2" {
  5669. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5670. if err != nil {
  5671. logs.Error(err)
  5672. tx.Rollback()
  5673. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5674. return
  5675. }
  5676. }
  5677. if item["fttype"].(int64) == 0 {
  5678. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5679. if err != nil {
  5680. logs.Error(err)
  5681. tx.Rollback()
  5682. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5683. return
  5684. }
  5685. } else {
  5686. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5687. if err != nil {
  5688. logs.Error(err)
  5689. tx.Rollback()
  5690. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5691. return
  5692. }
  5693. }
  5694. } else {
  5695. lweight = lweight - fl
  5696. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5697. if err != nil {
  5698. logs.Error(err)
  5699. tx.Rollback()
  5700. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5701. return
  5702. }
  5703. if item["fttype"].(int64) == 0 {
  5704. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5705. if err != nil {
  5706. logs.Error(err)
  5707. tx.Rollback()
  5708. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5709. return
  5710. }
  5711. } else {
  5712. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5713. if err != nil {
  5714. logs.Error(err)
  5715. tx.Rollback()
  5716. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5717. return
  5718. }
  5719. }
  5720. }
  5721. } else {
  5722. // 自走式
  5723. if tmrtype == "1" {
  5724. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5725. if err != nil {
  5726. logs.Error(err)
  5727. tx.Rollback()
  5728. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5729. return
  5730. }
  5731. } else if tmrtype == "2" {
  5732. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5733. if err != nil {
  5734. logs.Error(err)
  5735. tx.Rollback()
  5736. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5737. return
  5738. }
  5739. }
  5740. }
  5741. }
  5742. } else {
  5743. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5744. if err != nil {
  5745. logs.Error(err)
  5746. tx.Rollback()
  5747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5748. return
  5749. }
  5750. for _, item := range lpplandtl1List {
  5751. if item["fttype"].(int64) == 0 {
  5752. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5753. if err != nil {
  5754. logs.Error(err)
  5755. tx.Rollback()
  5756. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5757. return
  5758. }
  5759. } else {
  5760. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5761. if err != nil {
  5762. logs.Error(err)
  5763. tx.Rollback()
  5764. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5765. return
  5766. }
  5767. }
  5768. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5769. if err != nil {
  5770. logs.Error(err)
  5771. tx.Rollback()
  5772. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5773. return
  5774. }
  5775. }
  5776. }
  5777. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5778. if err != nil {
  5779. logs.Error(err)
  5780. tx.Rollback()
  5781. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5782. return
  5783. }
  5784. } else {
  5785. if status == 2 {
  5786. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5787. if err != nil {
  5788. logs.Error(err)
  5789. tx.Rollback()
  5790. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5791. return
  5792. }
  5793. for _, item := range lpplandtl1List {
  5794. if item["fttype"].(int64) == 0 {
  5795. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5796. if err != nil {
  5797. logs.Error(err)
  5798. tx.Rollback()
  5799. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5800. return
  5801. }
  5802. } else {
  5803. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5804. if err != nil {
  5805. logs.Error(err)
  5806. tx.Rollback()
  5807. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5808. return
  5809. }
  5810. }
  5811. }
  5812. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  5813. if err != nil {
  5814. logs.Error(err)
  5815. tx.Rollback()
  5816. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5817. return
  5818. }
  5819. } else {
  5820. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  5821. if err != nil {
  5822. logs.Error(err)
  5823. tx.Rollback()
  5824. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5825. return
  5826. }
  5827. }
  5828. }
  5829. err := tx.Commit()
  5830. if err != nil {
  5831. logs.Error(err)
  5832. tx.Rollback()
  5833. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5834. return
  5835. }
  5836. appG.Response(http.StatusOK, e.SUCCESS, true)
  5837. }
  5838. func UpdateMaterialTMRDate(c *gin.Context) {
  5839. appG := app.Gin{C: c}
  5840. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5841. parammaps := gofasion.NewFasion(string(dataByte))
  5842. tmrid := parammaps.Get("tmrid").ValueStr()
  5843. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5844. lppid := parammaps.Get("lppid").ValueStr()
  5845. times := parammaps.Get("times").ValueStr()
  5846. pastureid := parammaps.Get("pastureid").ValueStr()
  5847. date := parammaps.Get("date").ValueStr()
  5848. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5849. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5850. tx := restful.Engine.NewSession()
  5851. defer tx.Close()
  5852. tx.Begin()
  5853. if tmrid != "1000" {
  5854. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5855. if err != nil {
  5856. logs.Error(err)
  5857. tx.Rollback()
  5858. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5859. return
  5860. }
  5861. var maxstirfeed float64
  5862. for _, tmr := range tmrList {
  5863. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5864. }
  5865. if status == 0 {
  5866. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? order by sort desc ", lppid, pastureid, date).Query().List()
  5867. if err != nil {
  5868. logs.Error(err)
  5869. tx.Rollback()
  5870. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5871. return
  5872. }
  5873. var lweight float64
  5874. for _, item := range lpplandtl1List {
  5875. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5876. lweight += fl
  5877. }
  5878. if lweight > maxstirfeed {
  5879. lweight = lweight - maxstirfeed
  5880. } else {
  5881. lweight = 0
  5882. }
  5883. if lweight > 0 {
  5884. lweight1 := lweight / float64(len(lpplandtl1List))
  5885. number := 0
  5886. for _, item := range lpplandtl1List {
  5887. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5888. if lweight1 >= fl {
  5889. number++
  5890. }
  5891. }
  5892. lweight := lweight / float64((len(lpplandtl1List) - number))
  5893. for _, item := range lpplandtl1List {
  5894. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5895. if lweight1 >= fl {
  5896. continue
  5897. }
  5898. if tmrtype == "1" {
  5899. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? and date = ? ", tmrid, tmrid, lweight, item["id"], date).Execute()
  5900. if err != nil {
  5901. logs.Error(err)
  5902. tx.Rollback()
  5903. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5904. return
  5905. }
  5906. } else if tmrtype == "2" {
  5907. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5908. if err != nil {
  5909. logs.Error(err)
  5910. tx.Rollback()
  5911. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5912. return
  5913. }
  5914. }
  5915. if item["fttype"].(int64) == 0 {
  5916. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5917. if err != nil {
  5918. logs.Error(err)
  5919. tx.Rollback()
  5920. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5921. return
  5922. }
  5923. } else {
  5924. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5925. if err != nil {
  5926. logs.Error(err)
  5927. tx.Rollback()
  5928. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5929. return
  5930. }
  5931. }
  5932. }
  5933. } else {
  5934. for _, item := range lpplandtl1List {
  5935. // 自走式
  5936. if tmrtype == "1" {
  5937. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5938. if err != nil {
  5939. logs.Error(err)
  5940. tx.Rollback()
  5941. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5942. return
  5943. }
  5944. } else if tmrtype == "2" {
  5945. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5946. if err != nil {
  5947. logs.Error(err)
  5948. tx.Rollback()
  5949. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5950. return
  5951. }
  5952. }
  5953. }
  5954. }
  5955. } else if status == 1 {
  5956. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? order by sort desc ", lppid, pastureid, date).Query().List()
  5957. if err != nil {
  5958. logs.Error(err)
  5959. tx.Rollback()
  5960. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5961. return
  5962. }
  5963. var lweight float64
  5964. for _, item := range lpplandtl1List {
  5965. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5966. lweight += fl
  5967. }
  5968. if lweight > maxstirfeed {
  5969. lweight = lweight - maxstirfeed
  5970. } else {
  5971. lweight = 0
  5972. }
  5973. for _, item := range lpplandtl1List {
  5974. if lweight > 0 {
  5975. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5976. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5977. if fl >= lweight {
  5978. item["lweight"] = fl - lweight
  5979. lweight = 0
  5980. if tmrtype == "1" {
  5981. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? and date = ? ", tmrid, tmrid, item["lweight"], item["id"], date).Execute()
  5982. if err != nil {
  5983. logs.Error(err)
  5984. tx.Rollback()
  5985. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5986. return
  5987. }
  5988. } else if tmrtype == "2" {
  5989. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5990. if err != nil {
  5991. logs.Error(err)
  5992. tx.Rollback()
  5993. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5994. return
  5995. }
  5996. }
  5997. if item["fttype"].(int64) == 0 {
  5998. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5999. if err != nil {
  6000. logs.Error(err)
  6001. tx.Rollback()
  6002. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6003. return
  6004. }
  6005. } else {
  6006. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6007. if err != nil {
  6008. logs.Error(err)
  6009. tx.Rollback()
  6010. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6011. return
  6012. }
  6013. }
  6014. } else {
  6015. lweight = lweight - fl
  6016. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6017. if err != nil {
  6018. logs.Error(err)
  6019. tx.Rollback()
  6020. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6021. return
  6022. }
  6023. if item["fttype"].(int64) == 0 {
  6024. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6025. if err != nil {
  6026. logs.Error(err)
  6027. tx.Rollback()
  6028. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6029. return
  6030. }
  6031. } else {
  6032. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6033. if err != nil {
  6034. logs.Error(err)
  6035. tx.Rollback()
  6036. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6037. return
  6038. }
  6039. }
  6040. }
  6041. } else {
  6042. // 自走式
  6043. if tmrtype == "1" {
  6044. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6045. if err != nil {
  6046. logs.Error(err)
  6047. tx.Rollback()
  6048. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6049. return
  6050. }
  6051. } else if tmrtype == "2" {
  6052. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6053. if err != nil {
  6054. logs.Error(err)
  6055. tx.Rollback()
  6056. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6057. return
  6058. }
  6059. }
  6060. }
  6061. }
  6062. } else {
  6063. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6064. if err != nil {
  6065. logs.Error(err)
  6066. tx.Rollback()
  6067. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6068. return
  6069. }
  6070. for _, item := range lpplandtl1List {
  6071. if item["fttype"].(int64) == 0 {
  6072. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6073. if err != nil {
  6074. logs.Error(err)
  6075. tx.Rollback()
  6076. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6077. return
  6078. }
  6079. } else {
  6080. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6081. if err != nil {
  6082. logs.Error(err)
  6083. tx.Rollback()
  6084. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6085. return
  6086. }
  6087. }
  6088. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6089. if err != nil {
  6090. logs.Error(err)
  6091. tx.Rollback()
  6092. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6093. return
  6094. }
  6095. }
  6096. }
  6097. _, err = tx.SQL(" update lpplandate set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? and date = ?", tmrid, tmrid, maxstirfeed, lppid, date).Execute()
  6098. if err != nil {
  6099. logs.Error(err)
  6100. tx.Rollback()
  6101. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6102. return
  6103. }
  6104. } else {
  6105. if status == 2 {
  6106. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6107. if err != nil {
  6108. logs.Error(err)
  6109. tx.Rollback()
  6110. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6111. return
  6112. }
  6113. for _, item := range lpplandtl1List {
  6114. if item["fttype"].(int64) == 0 {
  6115. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6116. if err != nil {
  6117. logs.Error(err)
  6118. tx.Rollback()
  6119. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6120. return
  6121. }
  6122. } else {
  6123. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6124. if err != nil {
  6125. logs.Error(err)
  6126. tx.Rollback()
  6127. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6128. return
  6129. }
  6130. }
  6131. }
  6132. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6133. if err != nil {
  6134. logs.Error(err)
  6135. tx.Rollback()
  6136. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6137. return
  6138. }
  6139. } else {
  6140. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6141. if err != nil {
  6142. logs.Error(err)
  6143. tx.Rollback()
  6144. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6145. return
  6146. }
  6147. }
  6148. }
  6149. err := tx.Commit()
  6150. if err != nil {
  6151. logs.Error(err)
  6152. tx.Rollback()
  6153. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6154. return
  6155. }
  6156. appG.Response(http.StatusOK, e.SUCCESS, true)
  6157. }
  6158. func Decimal(value float64) float64 {
  6159. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6160. return value
  6161. }
  6162. func UpdateDailyData(c *gin.Context) {
  6163. appG := app.Gin{C: c}
  6164. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6165. parammaps := gofasion.NewFasion(string(dataByte))
  6166. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6167. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6168. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6169. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6170. date := parammaps.Get("date").ValueStr()
  6171. tx := restful.Engine.NewSession()
  6172. defer tx.Close()
  6173. count, err := tx.SQL(`select count(1) from downloadedplan where pid in(select pid from downloadedplan where id= ? ) and havebutton = 1 and mydate = ?`, pid, date).Count()
  6174. if err != nil {
  6175. logs.Error("UpdateDailyData-error-0:", err)
  6176. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6177. return
  6178. }
  6179. if count > 0 {
  6180. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6181. return
  6182. }
  6183. tx.Begin()
  6184. if location == 0 {
  6185. fid := parammaps.Get("fid").ValueStr()
  6186. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6187. if err != nil {
  6188. logs.Error("UpdateDailyData-error-1:", err)
  6189. tx.Rollback()
  6190. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6191. return
  6192. }
  6193. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6194. if err != nil {
  6195. logs.Error("UpdateDailyData-error-1:", err)
  6196. tx.Rollback()
  6197. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6198. return
  6199. }
  6200. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6201. if err != nil {
  6202. fmt.Println("Error:", err)
  6203. return
  6204. }
  6205. actualWeight := weight - num
  6206. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6207. if err != nil {
  6208. logs.Error("UpdateDailyData-error-2:", err)
  6209. tx.Rollback()
  6210. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6211. return
  6212. }
  6213. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6214. if err != nil {
  6215. logs.Error("UpdateDailyData-error-3:", err)
  6216. tx.Rollback()
  6217. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6218. return
  6219. }
  6220. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6221. if err != nil {
  6222. logs.Error("UpdateDailyData-error-4:", err)
  6223. tx.Rollback()
  6224. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6225. return
  6226. }
  6227. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6228. if err != nil {
  6229. logs.Error("UpdateDailyData-error-5:", err)
  6230. tx.Rollback()
  6231. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6232. return
  6233. }
  6234. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6235. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6236. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6237. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6238. if err != nil {
  6239. fmt.Println("Error:", err)
  6240. return
  6241. }
  6242. // actual := actualWeight / float64(len(downloadedplanList))
  6243. for _, item := range downloadedplanList {
  6244. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6245. if err != nil {
  6246. fmt.Println("Error:", err)
  6247. return
  6248. }
  6249. actual := itemLweight / lweight * actualWeight
  6250. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6251. if err != nil {
  6252. logs.Error("UpdateDailyData-error-6:", err)
  6253. tx.Rollback()
  6254. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6255. return
  6256. }
  6257. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6258. if err != nil {
  6259. logs.Error("UpdateDailyData-error-7:", err)
  6260. tx.Rollback()
  6261. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6262. return
  6263. }
  6264. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort ) where pid = ?`, item["id"]).Execute()
  6265. if err != nil {
  6266. logs.Error("UpdateDailyData-error-8:", err)
  6267. tx.Rollback()
  6268. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6269. return
  6270. }
  6271. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6272. if err != nil {
  6273. logs.Error("UpdateDailyData-error-9:", err)
  6274. tx.Rollback()
  6275. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6276. return
  6277. }
  6278. }
  6279. } else {
  6280. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6281. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6282. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6283. // if err != nil {
  6284. // fmt.Println("Error:", err)
  6285. // return
  6286. // }
  6287. for _, item := range downloadedplanList {
  6288. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6289. if err != nil {
  6290. logs.Error("UpdateDailyData-error-6:", err)
  6291. tx.Rollback()
  6292. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6293. return
  6294. }
  6295. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6296. item["lweight"], actualWeight, item["id"]).Execute()
  6297. if err != nil {
  6298. logs.Error("UpdateDailyData-error-7:", err)
  6299. tx.Rollback()
  6300. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6301. return
  6302. }
  6303. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6304. where pid = ?`, item["id"]).Execute()
  6305. if err != nil {
  6306. logs.Error("UpdateDailyData-error-8:", err)
  6307. tx.Rollback()
  6308. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6309. return
  6310. }
  6311. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6312. if err != nil {
  6313. logs.Error("UpdateDailyData-error-9:", err)
  6314. tx.Rollback()
  6315. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6316. return
  6317. }
  6318. }
  6319. }
  6320. } else {
  6321. fbarid := parammaps.Get("fbarid").ValueStr()
  6322. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6323. if err != nil {
  6324. logs.Error("UpdateDailyData-error-10:", err)
  6325. tx.Rollback()
  6326. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6327. return
  6328. }
  6329. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6330. if err != nil {
  6331. logs.Error("UpdateDailyData-error-1:", err)
  6332. tx.Rollback()
  6333. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6334. return
  6335. }
  6336. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6337. if err != nil {
  6338. fmt.Println("Error:", err)
  6339. return
  6340. }
  6341. actualWeight := weight - num
  6342. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6343. if err != nil {
  6344. logs.Error("UpdateDailyData-error-11:", err)
  6345. tx.Rollback()
  6346. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6347. return
  6348. }
  6349. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6350. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6351. if err != nil {
  6352. logs.Error("UpdateDailyData-error-12:", err)
  6353. tx.Rollback()
  6354. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6355. return
  6356. }
  6357. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6358. where pid = ? `, pid).Execute()
  6359. if err != nil {
  6360. logs.Error("UpdateDailyData-error-13:", err)
  6361. tx.Rollback()
  6362. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6363. return
  6364. }
  6365. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6366. if err != nil {
  6367. logs.Error("UpdateDailyData-error-14:", err)
  6368. tx.Rollback()
  6369. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6370. return
  6371. }
  6372. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6373. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6374. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6375. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6376. if err != nil {
  6377. fmt.Println("Error:", err)
  6378. return
  6379. }
  6380. for _, item := range downloadedplanList {
  6381. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6382. if err != nil {
  6383. fmt.Println("Error:", err)
  6384. return
  6385. }
  6386. actual := itemLweight / lweight * actualWeight
  6387. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6388. if err != nil {
  6389. logs.Error("UpdateDailyData-error-6:", err)
  6390. tx.Rollback()
  6391. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6392. return
  6393. }
  6394. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6395. if err != nil {
  6396. logs.Error("UpdateDailyData-error-7:", err)
  6397. tx.Rollback()
  6398. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6399. return
  6400. }
  6401. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort ) where pid = ?`, item["id"]).Execute()
  6402. if err != nil {
  6403. logs.Error("UpdateDailyData-error-8:", err)
  6404. tx.Rollback()
  6405. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6406. return
  6407. }
  6408. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6409. if err != nil {
  6410. logs.Error("UpdateDailyData-error-9:", err)
  6411. tx.Rollback()
  6412. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6413. return
  6414. }
  6415. }
  6416. } else {
  6417. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6418. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6419. for _, item := range downloadedplanList {
  6420. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6421. // if err != nil {
  6422. // fmt.Println("Error:", err)
  6423. // return
  6424. // }
  6425. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6426. if err != nil {
  6427. logs.Error("UpdateDailyData-error-6:", err)
  6428. tx.Rollback()
  6429. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6430. return
  6431. }
  6432. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6433. item["lweight"], actualWeight, item["id"]).Execute()
  6434. if err != nil {
  6435. logs.Error("UpdateDailyData-error-7:", err)
  6436. tx.Rollback()
  6437. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6438. return
  6439. }
  6440. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6441. where pid = ?`, item["id"]).Execute()
  6442. if err != nil {
  6443. logs.Error("UpdateDailyData-error-8:", err)
  6444. tx.Rollback()
  6445. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6446. return
  6447. }
  6448. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6449. if err != nil {
  6450. logs.Error("UpdateDailyData-error-9:", err)
  6451. tx.Rollback()
  6452. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6453. return
  6454. }
  6455. }
  6456. }
  6457. }
  6458. err = tx.Commit()
  6459. if err != nil {
  6460. logs.Error("UpdateDailyData-error-20:", err)
  6461. tx.Rollback()
  6462. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6463. return
  6464. }
  6465. appG.Response(http.StatusOK, e.SUCCESS, true)
  6466. }
  6467. func GetFormulaStatistics(c *gin.Context) {
  6468. appG := app.Gin{C: c}
  6469. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6470. parammaps := gofasion.NewFasion(string(dataByte))
  6471. startTime := parammaps.Get("startTime").ValueStr()
  6472. endTime := parammaps.Get("endTime").ValueStr()
  6473. pastureId := parammaps.Get("pastureId").ValueStr()
  6474. tx := restful.Engine.NewSession()
  6475. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6476. if err != nil {
  6477. logs.Error("GetFormulaStatistics-error-1:", err)
  6478. tx.Rollback()
  6479. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6480. return
  6481. }
  6482. var feedtemplet, dateList []string
  6483. for _, f := range feedtempletList {
  6484. feedtemplet = append(feedtemplet, f["tname"].(string))
  6485. }
  6486. layout := "2006-01-02"
  6487. // s := "2023-05-01"
  6488. // e := "2023-05-23"
  6489. start, err := time.Parse(layout, startTime)
  6490. if err != nil {
  6491. fmt.Println(err)
  6492. return
  6493. }
  6494. end, err := time.Parse(layout, endTime)
  6495. if err != nil {
  6496. fmt.Println(err)
  6497. return
  6498. }
  6499. end = end.AddDate(0, 0, 1)
  6500. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6501. dateList = append(dateList, d.Format("2006-01-02"))
  6502. }
  6503. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6504. join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  6505. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6506. if err != nil {
  6507. logs.Error("GetFormulaStatistics-error-2:", err)
  6508. tx.Rollback()
  6509. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6510. return
  6511. }
  6512. var data2 [][]interface{}
  6513. for _, f := range feedtemplet {
  6514. var data1 []interface{}
  6515. for _, date := range dateList {
  6516. exist := false
  6517. for _, item := range downloadedplanList {
  6518. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6519. data1 = append(data1, item["total"])
  6520. exist = true
  6521. break
  6522. }
  6523. }
  6524. if !exist {
  6525. data1 = append(data1, 0)
  6526. }
  6527. }
  6528. data2 = append(data2, data1)
  6529. }
  6530. //前端让加的
  6531. feedtemplet = append(feedtemplet, "")
  6532. {
  6533. var data1 []interface{}
  6534. for _, f := range dateList {
  6535. // f = f + "\n"
  6536. fmt.Println(f)
  6537. data1 = append(data1, 0)
  6538. }
  6539. data2 = append(data2, data1)
  6540. }
  6541. resp := make(map[string]interface{}, 0)
  6542. resp["xdata"] = dateList
  6543. resp["data1"] = feedtemplet
  6544. resp["data2"] = data2
  6545. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6546. }
  6547. func GetPlanData(c *gin.Context) {
  6548. appG := app.Gin{C: c}
  6549. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6550. fsion := gofasion.NewFasion(string(dataByte))
  6551. sqlnamestr := fsion.Get("name").ValueStr()
  6552. sqlnamestr1 := fsion.Get("name1").ValueStr()
  6553. offset := fsion.Get("offset").ValueDefaultInt(0)
  6554. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  6555. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6556. month := fsion.Get("month").ValueDefaultStr("map")
  6557. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  6558. tx := restful.Engine.NewSession()
  6559. err := tx.Begin()
  6560. defer func() {
  6561. switch {
  6562. case err != nil:
  6563. if tx != nil {
  6564. tx.Rollback()
  6565. }
  6566. default:
  6567. if tx != nil {
  6568. err = tx.Commit()
  6569. }
  6570. }
  6571. if tx != nil {
  6572. tx.Close()
  6573. }
  6574. }()
  6575. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6576. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  6577. if sql != "" {
  6578. s_params := make([]interface{}, 0)
  6579. if fsion.HasKey("parammaps") {
  6580. parammaps := fsion.Get("parammaps")
  6581. paramslist := strings.Split(p, ",")
  6582. if len(paramslist) > 0 && p != "" {
  6583. for _, value := range paramslist {
  6584. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6585. if tempv, exists := c.Get("jwt_username"); exists {
  6586. s_params = append(s_params, tempv.(string))
  6587. } else {
  6588. s_params = append(s_params, "")
  6589. }
  6590. } else {
  6591. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6592. }
  6593. }
  6594. }
  6595. }
  6596. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6597. if err != nil {
  6598. appG.Response(http.StatusOK, e.ERROR, err.Error())
  6599. } else {
  6600. paramslist1 := strings.Split(p1, ",")
  6601. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6602. s_params1 := make([]interface{}, 0)
  6603. if len(paramslist1) > 0 && p1 != "" {
  6604. for _, v := range paramslist1 {
  6605. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  6606. }
  6607. }
  6608. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  6609. for _, item := range arr {
  6610. trgaddressList := []string{}
  6611. if _, ok := item["trgaddress"]; ok {
  6612. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6613. for _, str := range trgaddressList1 {
  6614. if str != "" {
  6615. trgaddressList = append(trgaddressList, str)
  6616. }
  6617. }
  6618. }
  6619. item["trgaddressList"] = trgaddressList
  6620. }
  6621. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  6622. }
  6623. // var wg sync.WaitGroup
  6624. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6625. // wg.Add(1)
  6626. // go func(value map[string]interface{}) {
  6627. // defer wg.Done()
  6628. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  6629. // }(value)
  6630. // }
  6631. // wg.Wait()
  6632. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6633. }
  6634. } else {
  6635. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6636. }
  6637. }
  6638. func PostPlanData(c *gin.Context) {
  6639. appG := app.Gin{C: c}
  6640. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6641. fsion := gofasion.NewFasion(string(dataByte))
  6642. logging.Info("PostRJSBData err: ", string(dataByte))
  6643. s_params := make([]interface{}, 0)
  6644. tx := restful.Engine.NewSession()
  6645. err := tx.Begin()
  6646. defer func() {
  6647. switch {
  6648. case err != nil:
  6649. if tx != nil {
  6650. tx.Rollback()
  6651. }
  6652. default:
  6653. if tx != nil {
  6654. err = tx.Commit()
  6655. }
  6656. }
  6657. if tx != nil {
  6658. tx.Close()
  6659. }
  6660. }()
  6661. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  6662. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  6663. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  6664. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  6665. if !fsion.HasKey("parammaps") {
  6666. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  6667. return
  6668. }
  6669. parammaps := fsion.Get("parammaps")
  6670. // paramslist := strings.Split(p, ",")
  6671. // if len(paramslist) > 0 && p != "" {
  6672. // for _, value := range paramslist {
  6673. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6674. // }
  6675. // }
  6676. // _, err = tx.SQL(sql, s_params...).Execute()
  6677. // if err != nil {
  6678. // logging.Error("PostRJSBData err: ", err)
  6679. // msg := geterrmsg(err.Error())
  6680. // appG.Response(http.StatusOK, e.ERROR, msg)
  6681. // return
  6682. // }
  6683. s_params = make([]interface{}, 0)
  6684. paramslist := strings.Split(p1, ",")
  6685. if len(paramslist) > 0 && p1 != "" {
  6686. for _, value := range paramslist {
  6687. // if value == "ID" {
  6688. // id := parammaps.Get("ID").ValueStr()
  6689. // pastureid := parammaps.Get("pastureid").ValueStr()
  6690. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  6691. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6692. // if err != nil {
  6693. // logging.Error("PostRJSBData err: ", err)
  6694. // msg := geterrmsg(err.Error())
  6695. // appG.Response(http.StatusOK, e.ERROR, msg)
  6696. // return
  6697. // }
  6698. // for _, item := range datalist {
  6699. // id = item["id"]
  6700. // }
  6701. // s_params = append(s_params, id)
  6702. // } else {
  6703. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6704. // }
  6705. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6706. }
  6707. }
  6708. _, err = tx.SQL(sql1, s_params...).Execute()
  6709. if err != nil {
  6710. logging.Error("PostRJSBData1 err: ", err)
  6711. msg := geterrmsg(err.Error())
  6712. appG.Response(http.StatusOK, e.ERROR, msg)
  6713. return
  6714. }
  6715. s_params = make([]interface{}, 0)
  6716. paramslist = strings.Split(p2, ",")
  6717. if len(paramslist) > 0 && p2 != "" {
  6718. for _, value := range paramslist {
  6719. if value == "ID" {
  6720. id := parammaps.Get("ID").ValueStr()
  6721. pastureid := parammaps.Get("pastureid").ValueStr()
  6722. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  6723. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6724. if err != nil {
  6725. logging.Error("PostRJSBData err: ", err)
  6726. msg := geterrmsg(err.Error())
  6727. appG.Response(http.StatusOK, e.ERROR, msg)
  6728. return
  6729. }
  6730. for _, item := range datalist {
  6731. id = item["id"]
  6732. }
  6733. s_params = append(s_params, id)
  6734. } else {
  6735. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6736. }
  6737. }
  6738. }
  6739. _, err = tx.SQL(sql2, s_params...).Execute()
  6740. if err != nil {
  6741. logging.Error("PostRJSBData2 err: ", err)
  6742. msg := geterrmsg(err.Error())
  6743. appG.Response(http.StatusOK, e.ERROR, msg)
  6744. return
  6745. }
  6746. s_params = make([]interface{}, 0)
  6747. paramslist = strings.Split(p3, ",")
  6748. if len(paramslist) > 0 && p3 != "" {
  6749. for _, value := range paramslist {
  6750. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6751. }
  6752. }
  6753. _, err = tx.SQL(sql3, s_params...).Execute()
  6754. if err != nil {
  6755. logging.Error("PostRJSBData3 err: ", err)
  6756. msg := geterrmsg(err.Error())
  6757. appG.Response(http.StatusOK, e.ERROR, msg)
  6758. return
  6759. }
  6760. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6761. }
  6762. func CheckFeedTrgaddress(c *gin.Context) {
  6763. appG := app.Gin{C: c}
  6764. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6765. fsion := gofasion.NewFasion(string(dataByte))
  6766. fclassid := fsion.Get("fclassid").ValueStr()
  6767. feedId := fsion.Get("feedId").ValueStr()
  6768. backup1 := fsion.Get("backup1").ValueStr()
  6769. backup1List := strings.Split(backup1, ",")
  6770. tx := restful.Engine.NewSession()
  6771. defer tx.Close()
  6772. // if backup1 != "" {
  6773. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  6774. for _, feed := range feedList {
  6775. if feed["backup1"] == "" {
  6776. continue
  6777. }
  6778. feedbackupList := strings.Split(feed["backup1"], ",")
  6779. for _, feedbackup := range feedbackupList {
  6780. for _, backup := range backup1List {
  6781. if feedbackup == backup {
  6782. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  6783. return
  6784. }
  6785. }
  6786. }
  6787. }
  6788. // }
  6789. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6790. }
  6791. func ThiGetDataByName(c *gin.Context) {
  6792. appG := app.Gin{C: c}
  6793. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6794. fsion := gofasion.NewFasion(string(dataByte))
  6795. sqlnamestr := fsion.Get("name").ValueStr()
  6796. offset := fsion.Get("offset").ValueDefaultInt(0)
  6797. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  6798. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6799. tx := restful.Engine.NewSession()
  6800. err := tx.Begin()
  6801. defer func() {
  6802. switch {
  6803. case err != nil:
  6804. logging.Error("tx.Begin 事务启动失败__error:", err)
  6805. if tx != nil {
  6806. tx.Rollback()
  6807. }
  6808. default:
  6809. if tx != nil {
  6810. err = tx.Commit()
  6811. }
  6812. }
  6813. if tx != nil {
  6814. tx.Close()
  6815. }
  6816. }()
  6817. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6818. if sql != "" {
  6819. s_params := make([]interface{}, 0)
  6820. if fsion.HasKey("parammaps") {
  6821. parammaps := fsion.Get("parammaps")
  6822. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  6823. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  6824. }
  6825. paramslist := strings.Split(p, ",")
  6826. if len(paramslist) > 0 && p != "" {
  6827. for _, value := range paramslist {
  6828. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6829. if tempv, exists := c.Get("jwt_username"); exists {
  6830. s_params = append(s_params, tempv.(string))
  6831. } else {
  6832. s_params = append(s_params, "")
  6833. }
  6834. } else {
  6835. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6836. }
  6837. }
  6838. }
  6839. } else if fsion.HasKey("params") {
  6840. params := fsion.Get("params").Array()
  6841. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  6842. for _, v_params := range params {
  6843. s_params = append(s_params, v_params.ValueStr())
  6844. }
  6845. }
  6846. if returntype == "xlsx" {
  6847. var xlsxfile *xlsx.File
  6848. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  6849. //c.File("c:/dd.xlsx")
  6850. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  6851. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  6852. c.Header("Content-Transfer-Encoding", "binary")
  6853. _ = xlsxfile.Write(c.Writer)
  6854. } else {
  6855. if sqlnamestr == "getHomepageStr" {
  6856. parammaps := fsion.Get("parammaps")
  6857. pastureid := parammaps.Get("pastureid").ValueStr()
  6858. var montimeList []float64
  6859. var montime float64
  6860. var wg sync.WaitGroup
  6861. now := time.Now()
  6862. for i := 0; i < 30; i++ {
  6863. wg.Add(1)
  6864. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  6865. go func(nowstr string) {
  6866. defer wg.Done()
  6867. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  6868. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  6869. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  6870. montimeList = append(montimeList, m)
  6871. }(nowstr)
  6872. }
  6873. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6874. if err != nil {
  6875. logging.Error("GetDataByName err: ", err)
  6876. msg := geterrmsg(err.Error())
  6877. appG.Response(http.StatusOK, e.ERROR, msg)
  6878. }
  6879. wg.Wait()
  6880. for _, m := range montimeList {
  6881. montime += m
  6882. }
  6883. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  6884. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6885. return
  6886. }
  6887. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6888. if err != nil {
  6889. logging.Error("GetDataByName err: ", err)
  6890. msg := geterrmsg(err.Error())
  6891. appG.Response(http.StatusOK, e.ERROR, msg)
  6892. } else {
  6893. if sqlnamestr == "getFeedTrgaddressList" {
  6894. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6895. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6896. trgaddressList := []string{}
  6897. for _, str := range trgaddressList1 {
  6898. if str != "" {
  6899. trgaddressList = append(trgaddressList, str)
  6900. }
  6901. }
  6902. item["trgaddressList"] = trgaddressList
  6903. }
  6904. }
  6905. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6906. }
  6907. }
  6908. } else {
  6909. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6910. }
  6911. }
  6912. // func ToggleCcount(c *gin.Context) {
  6913. // appG := app.Gin{C: c}
  6914. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6915. // fsion := gofasion.NewFasion(string(dataByte))
  6916. // // 0 实际 1 软件
  6917. // status := fsion.Get("status").ValueDefaultInt64(0)
  6918. // pastureId := fsion.Get("pastureId").ValueStr()
  6919. // tx := restful.Engine.NewSession()
  6920. // err := tx.Begin()
  6921. // defer func() {
  6922. // switch {
  6923. // case err != nil:
  6924. // logging.Error("tx.Begin 事务启动失败__error:", err)
  6925. // if tx != nil {
  6926. // tx.Rollback()
  6927. // }
  6928. // default:
  6929. // if tx != nil {
  6930. // err = tx.Commit()
  6931. // }
  6932. // }
  6933. // if tx != nil {
  6934. // tx.Close()
  6935. // }
  6936. // }()
  6937. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  6938. // if err != nil {
  6939. // logs.Error(err)
  6940. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6941. // return
  6942. // }
  6943. // for _, bar := range barList {
  6944. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  6945. // if err != nil {
  6946. // logs.Error(err)
  6947. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6948. // return
  6949. // }
  6950. // if !exist {
  6951. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  6952. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  6953. // if err != nil {
  6954. // logs.Error(err)
  6955. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6956. // return
  6957. // }
  6958. // }
  6959. // }
  6960. // if status == 0 {
  6961. // tx.Exec(`update feedp set ccount = actualcount `)
  6962. // }else{
  6963. // tx.Exec(`update feedp set ccount = softccount `)
  6964. // }
  6965. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  6966. // if err != nil {
  6967. // logs.Error(err)
  6968. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6969. // return
  6970. // }
  6971. // for _, feedpData :=range feedpList{
  6972. // var feedpargs []interface{}
  6973. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  6974. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  6975. // if _, ok := feedpData["ftname"]; ok {
  6976. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  6977. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  6978. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  6979. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  6980. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6981. // } else {
  6982. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  6983. // }
  6984. // if _, ok := feedpData["ptsfname"]; ok {
  6985. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  6986. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  6987. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  6988. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  6989. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6990. // } else {
  6991. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  6992. // }
  6993. // upFeedpSql += " where barname = ? and pastureid = ? "
  6994. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  6995. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  6996. // if err != nil {
  6997. // logs.Error(err)
  6998. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6999. // return
  7000. // }
  7001. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7002. // if err != nil {
  7003. // logs.Error(err)
  7004. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7005. // return
  7006. // }
  7007. // if !exist1 {
  7008. // _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  7009. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7010. // if err != nil {
  7011. // logs.Error(err)
  7012. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7013. // return
  7014. // }
  7015. // }
  7016. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7017. // if err != nil {
  7018. // logs.Error(err)
  7019. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7020. // return
  7021. // }
  7022. // if !exist2 {
  7023. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  7024. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7025. // if err != nil {
  7026. // logs.Error(err)
  7027. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7028. // return
  7029. // }
  7030. // }
  7031. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7032. // if err != nil {
  7033. // logs.Error(err)
  7034. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7035. // return
  7036. // }
  7037. // if !exist3 {
  7038. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  7039. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7040. // if err != nil {
  7041. // logs.Error(err)
  7042. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7043. // return
  7044. // }
  7045. // }
  7046. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7047. // if err != nil {
  7048. // logs.Error(err)
  7049. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7050. // return
  7051. // }
  7052. // if !exist4 {
  7053. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  7054. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7055. // if err != nil {
  7056. // logs.Error(err)
  7057. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7058. // return
  7059. // }
  7060. // }
  7061. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7062. // if err != nil {
  7063. // logs.Error(err)
  7064. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7065. // return
  7066. // }
  7067. // if !exist5 {
  7068. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  7069. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7070. // if err != nil {
  7071. // logs.Error(err)
  7072. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7073. // return
  7074. // }
  7075. // }
  7076. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7077. // if err != nil {
  7078. // logs.Error(err)
  7079. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7080. // return
  7081. // }
  7082. // if !exist6 {
  7083. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  7084. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7085. // if err != nil {
  7086. // logs.Error(err)
  7087. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7088. // return
  7089. // }
  7090. // }
  7091. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7092. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7093. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7094. // and pastureid = ? and times = ?`
  7095. // var fpdargs1 []interface{}
  7096. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7097. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7098. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7099. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7100. // if err != nil {
  7101. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7102. // return
  7103. // }
  7104. // var fpdargs2 []interface{}
  7105. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7106. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7107. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7108. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7109. // if err != nil {
  7110. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7111. // return
  7112. // }
  7113. // var fpdargs3 []interface{}
  7114. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7115. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7116. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7117. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7118. // if err != nil {
  7119. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7120. // return
  7121. // }
  7122. // var fpdargs4 []interface{}
  7123. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7124. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7125. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7126. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7127. // if err != nil {
  7128. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7129. // return
  7130. // }
  7131. // var fpdargs5 []interface{}
  7132. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7133. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7134. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7135. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7136. // if err != nil {
  7137. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7138. // return
  7139. // }
  7140. // var fpdargs6 []interface{}
  7141. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7142. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7143. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7144. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7145. // if err != nil {
  7146. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7147. // return
  7148. // }
  7149. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7150. // newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  7151. // if err != nil {
  7152. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7153. // return
  7154. // }
  7155. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7156. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7157. // upFpdetailList := make([]*upFpdetail, 0)
  7158. // for _, newfpd := range newList {
  7159. // for _, oldfpd := range oldFpdList {
  7160. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7161. // var oldweight, newweight float64
  7162. // if oldfpd["weight"] != nil {
  7163. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7164. // }
  7165. // if newfpd["weight"] != nil {
  7166. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7167. // }
  7168. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7169. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7170. // Old: oldweight,
  7171. // New: newweight,
  7172. // Times: newfpd["times"].(int64),
  7173. // Ptid: newfpd["ptid"].(int64),
  7174. // Fweight: fweight,
  7175. // Id: oldfpd["id"].(int64),
  7176. // })
  7177. // break
  7178. // }
  7179. // }
  7180. // }
  7181. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7182. // }
  7183. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7184. // }
  7185. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7186. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7187. if err != nil {
  7188. return err
  7189. }
  7190. for _, item := range feedpList {
  7191. // if item["ftid"].(string) != data["ftid"].(string) {
  7192. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7193. if err != nil {
  7194. return err
  7195. }
  7196. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7197. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7198. if err != nil {
  7199. return err
  7200. }
  7201. // }
  7202. }
  7203. return nil
  7204. }
  7205. func PostPlanDatas(c *gin.Context) {
  7206. appG := app.Gin{C: c}
  7207. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7208. fsions := gofasion.NewFasion(string(dataByte))
  7209. logging.Info("PostRJSBDatas err: ", string(dataByte))
  7210. tx := restful.Engine.NewSession()
  7211. err := tx.Begin()
  7212. defer func() {
  7213. switch {
  7214. case err != nil:
  7215. if tx != nil {
  7216. tx.Rollback()
  7217. }
  7218. default:
  7219. if tx != nil {
  7220. err = tx.Commit()
  7221. }
  7222. }
  7223. if tx != nil {
  7224. tx.Close()
  7225. }
  7226. }()
  7227. pastureId := fsions.Get("pastureid").ValueStr()
  7228. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7229. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  7230. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  7231. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  7232. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7233. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7234. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7235. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7236. for _, parammaps := range fsions.Get("arrList").Array() {
  7237. fmt.Println(parammaps.Json())
  7238. if parammaps.Json() == "null" {
  7239. continue
  7240. }
  7241. // if !fsion.HasKey("arrList") {
  7242. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7243. // return
  7244. // continue
  7245. // }
  7246. // parammaps := fsion.Get("arrList")
  7247. s_params := make([]interface{}, 0)
  7248. // paramslist := strings.Split(p, ",")
  7249. // if len(paramslist) > 0 && p != "" {
  7250. // for _, value := range paramslist {
  7251. // if value == "pastureid" {
  7252. // s_params = append(s_params, pastureId)
  7253. // } else {
  7254. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7255. // }
  7256. // }
  7257. // }
  7258. // _, err = tx.SQL(sql, s_params...).Execute()
  7259. // if err != nil {
  7260. // logging.Error("PostRJSBData err: ", err)
  7261. // msg := geterrmsg(err.Error())
  7262. // appG.Response(http.StatusOK, e.ERROR, msg)
  7263. // return
  7264. // }
  7265. s_params = make([]interface{}, 0)
  7266. paramslist := strings.Split(p1, ",")
  7267. if len(paramslist) > 0 && p1 != "" {
  7268. for _, value := range paramslist {
  7269. // if value == "ID" {
  7270. // id := parammaps.Get("ID").ValueStr()
  7271. // pastureid := parammaps.Get("pastureid").ValueStr()
  7272. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  7273. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7274. // if err != nil {
  7275. // logging.Error("PostRJSBData err: ", err)
  7276. // msg := geterrmsg(err.Error())
  7277. // appG.Response(http.StatusOK, e.ERROR, msg)
  7278. // return
  7279. // }
  7280. // for _, item := range datalist {
  7281. // id = item["id"]
  7282. // }
  7283. // s_params = append(s_params, id)
  7284. // } else {
  7285. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7286. // }
  7287. if value == "pastureid" {
  7288. s_params = append(s_params, pastureId)
  7289. } else {
  7290. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7291. }
  7292. }
  7293. }
  7294. _, err = tx.SQL(sql1, s_params...).Execute()
  7295. if err != nil {
  7296. logging.Error("PostRJSBData1 err: ", err)
  7297. msg := geterrmsg(err.Error())
  7298. appG.Response(http.StatusOK, e.ERROR, msg)
  7299. return
  7300. }
  7301. s_params = make([]interface{}, 0)
  7302. paramslist = strings.Split(p2, ",")
  7303. if len(paramslist) > 0 && p2 != "" {
  7304. for _, value := range paramslist {
  7305. if value == "ID" {
  7306. id := parammaps.Get("ID").ValueStr()
  7307. pastureid := parammaps.Get("pastureid").ValueStr()
  7308. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  7309. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7310. if err != nil {
  7311. logging.Error("PostRJSBData err: ", err)
  7312. msg := geterrmsg(err.Error())
  7313. appG.Response(http.StatusOK, e.ERROR, msg)
  7314. return
  7315. }
  7316. for _, item := range datalist {
  7317. id = item["id"]
  7318. }
  7319. s_params = append(s_params, id)
  7320. } else if value == "pastureid" {
  7321. s_params = append(s_params, pastureId)
  7322. } else {
  7323. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7324. }
  7325. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7326. }
  7327. }
  7328. _, err = tx.SQL(sql2, s_params...).Execute()
  7329. if err != nil {
  7330. logging.Error("PostRJSBData2 err: ", err)
  7331. msg := geterrmsg(err.Error())
  7332. appG.Response(http.StatusOK, e.ERROR, msg)
  7333. return
  7334. }
  7335. s_params = make([]interface{}, 0)
  7336. paramslist = strings.Split(p3, ",")
  7337. if len(paramslist) > 0 && p3 != "" {
  7338. for _, value := range paramslist {
  7339. if value == "pastureid" {
  7340. s_params = append(s_params, pastureId)
  7341. } else {
  7342. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7343. }
  7344. }
  7345. }
  7346. _, err = tx.SQL(sql3, s_params...).Execute()
  7347. if err != nil {
  7348. logging.Error("PostRJSBData3 err: ", err)
  7349. msg := geterrmsg(err.Error())
  7350. appG.Response(http.StatusOK, e.ERROR, msg)
  7351. return
  7352. }
  7353. }
  7354. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7355. }
  7356. func FpdBatchEdit(c *gin.Context) {
  7357. appG := app.Gin{C: c}
  7358. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7359. fsions := gofasion.NewFasion(string(dataByte))
  7360. barList := fsions.Get("barList").Array()
  7361. pastureid := fsions.Get("pastureId").ValueStr()
  7362. tx := restful.Engine.NewSession()
  7363. defer tx.Close()
  7364. oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7365. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7366. if err != nil {
  7367. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7368. return
  7369. }
  7370. for _, barFsions := range barList {
  7371. dataexcel := make(map[string]interface{}, 0)
  7372. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  7373. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  7374. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  7375. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  7376. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  7377. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  7378. continue
  7379. }
  7380. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  7381. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  7382. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  7383. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  7384. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  7385. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  7386. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  7387. if err != nil {
  7388. logs.Error(err)
  7389. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7390. return
  7391. }
  7392. if !ftexist {
  7393. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  7394. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7395. if err != nil {
  7396. logs.Error(err)
  7397. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7398. return
  7399. }
  7400. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7401. if err != nil {
  7402. logs.Error(err)
  7403. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7404. return
  7405. }
  7406. }
  7407. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7408. if err != nil {
  7409. logs.Error(err)
  7410. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7411. return
  7412. }
  7413. if !exist {
  7414. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7415. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  7416. if err != nil {
  7417. logs.Error(err)
  7418. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7419. return
  7420. }
  7421. }
  7422. var feedpargs []interface{}
  7423. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7424. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  7425. if _, ok := dataexcel["ftname"]; ok {
  7426. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  7427. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7428. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7429. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7430. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  7431. } else {
  7432. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7433. }
  7434. if _, ok := dataexcel["ptsfname"]; ok {
  7435. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  7436. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7437. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7438. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7439. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  7440. } else {
  7441. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7442. }
  7443. upFeedpSql += " where barname = ? and pastureid = ? "
  7444. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  7445. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7446. if err != nil {
  7447. logs.Error(err)
  7448. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7449. return
  7450. }
  7451. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  7452. if err != nil {
  7453. logs.Error(err)
  7454. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7455. return
  7456. }
  7457. if !exist1 {
  7458. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  7459. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7460. if err != nil {
  7461. logs.Error(err)
  7462. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7463. return
  7464. }
  7465. }
  7466. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  7467. if err != nil {
  7468. logs.Error(err)
  7469. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7470. return
  7471. }
  7472. if !exist2 {
  7473. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  7474. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7475. if err != nil {
  7476. logs.Error(err)
  7477. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7478. return
  7479. }
  7480. }
  7481. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  7482. if err != nil {
  7483. logs.Error(err)
  7484. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7485. return
  7486. }
  7487. if !exist3 {
  7488. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  7489. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7490. if err != nil {
  7491. logs.Error(err)
  7492. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7493. return
  7494. }
  7495. }
  7496. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  7497. if err != nil {
  7498. logs.Error(err)
  7499. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7500. return
  7501. }
  7502. if !exist4 {
  7503. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  7504. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7505. if err != nil {
  7506. logs.Error(err)
  7507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7508. return
  7509. }
  7510. }
  7511. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  7512. if err != nil {
  7513. logs.Error(err)
  7514. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7515. return
  7516. }
  7517. if !exist5 {
  7518. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  7519. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7520. if err != nil {
  7521. logs.Error(err)
  7522. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7523. return
  7524. }
  7525. }
  7526. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  7527. if err != nil {
  7528. logs.Error(err)
  7529. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7530. return
  7531. }
  7532. if !exist6 {
  7533. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  7534. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7535. if err != nil {
  7536. logs.Error(err)
  7537. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7538. return
  7539. }
  7540. }
  7541. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7542. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7543. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7544. and pastureid = ? and times = ?`
  7545. var fpdargs1 []interface{}
  7546. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7547. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7548. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7549. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7550. if err != nil {
  7551. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7552. return
  7553. }
  7554. var fpdargs2 []interface{}
  7555. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7556. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7557. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7558. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7559. if err != nil {
  7560. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7561. return
  7562. }
  7563. var fpdargs3 []interface{}
  7564. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7565. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7566. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7567. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7568. if err != nil {
  7569. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7570. return
  7571. }
  7572. var fpdargs4 []interface{}
  7573. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7574. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7575. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7576. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7577. if err != nil {
  7578. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7579. return
  7580. }
  7581. var fpdargs5 []interface{}
  7582. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7583. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7584. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7585. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7586. if err != nil {
  7587. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7588. return
  7589. }
  7590. var fpdargs6 []interface{}
  7591. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7592. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7593. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7594. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7595. if err != nil {
  7596. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7597. return
  7598. }
  7599. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7600. newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  7601. if err != nil {
  7602. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7603. return
  7604. }
  7605. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7606. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7607. upFpdetailList := make([]*upFpdetail, 0)
  7608. for _, newfpd := range newList {
  7609. for _, oldfpd := range oldFpdList {
  7610. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7611. var oldweight, newweight float64
  7612. if oldfpd["weight"] != nil {
  7613. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7614. }
  7615. if newfpd["weight"] != nil {
  7616. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7617. }
  7618. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7619. upFpdetailList = append(upFpdetailList, &upFpdetail{
  7620. Old: oldweight,
  7621. New: newweight,
  7622. Times: newfpd["times"].(int64),
  7623. Ptid: newfpd["ptid"].(int64),
  7624. Fweight: fweight,
  7625. Id: oldfpd["id"].(int64),
  7626. })
  7627. break
  7628. }
  7629. }
  7630. }
  7631. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  7632. }
  7633. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7634. }
  7635. func UdBarSync(c *gin.Context) {
  7636. appG := app.Gin{C: c}
  7637. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7638. fsions := gofasion.NewFasion(string(dataByte))
  7639. pastureid := fsions.Get("pastureId").ValueStr()
  7640. tx := restful.Engine.NewSession()
  7641. defer tx.Close()
  7642. pastureinfo := new(udPastureInfo)
  7643. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  7644. if err != nil {
  7645. logs.Error(err)
  7646. return
  7647. }
  7648. gm.UdBarSync(pastureid, pastureinfo.Werks)
  7649. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7650. }
  7651. func UdFeedSync(c *gin.Context) {
  7652. appG := app.Gin{C: c}
  7653. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7654. fsions := gofasion.NewFasion(string(dataByte))
  7655. pastureid := fsions.Get("pastureId").ValueStr()
  7656. tx := restful.Engine.NewSession()
  7657. defer tx.Close()
  7658. pastureinfo := new(udPastureInfo)
  7659. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7660. if err != nil {
  7661. logs.Error(err)
  7662. return
  7663. }
  7664. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  7665. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7666. }
  7667. func UdFeedtempletPush(c *gin.Context) {
  7668. appG := app.Gin{C: c}
  7669. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7670. fsions := gofasion.NewFasion(string(dataByte))
  7671. pastureid := fsions.Get("pastureId").ValueStr()
  7672. date := fsions.Get("date").ValueStr()
  7673. tx := restful.Engine.NewSession()
  7674. defer tx.Close()
  7675. pastureinfo := new(udPastureInfo)
  7676. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7677. if err != nil {
  7678. logs.Error(err)
  7679. return
  7680. }
  7681. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  7682. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7683. }
  7684. func UdUtirPush(c *gin.Context) {
  7685. appG := app.Gin{C: c}
  7686. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7687. fsions := gofasion.NewFasion(string(dataByte))
  7688. pastureid := fsions.Get("pastureId").ValueStr()
  7689. date := fsions.Get("date").ValueStr()
  7690. tx := restful.Engine.NewSession()
  7691. defer tx.Close()
  7692. pastureinfo := new(udPastureInfo)
  7693. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7694. if err != nil {
  7695. logs.Error(err)
  7696. return
  7697. }
  7698. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  7699. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7700. }
  7701. func UdBarFeedRemainPush(c *gin.Context) {
  7702. appG := app.Gin{C: c}
  7703. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7704. fsions := gofasion.NewFasion(string(dataByte))
  7705. pastureid := fsions.Get("pastureId").ValueStr()
  7706. date := fsions.Get("date").ValueStr()
  7707. tx := restful.Engine.NewSession()
  7708. defer tx.Close()
  7709. pastureinfo := new(udPastureInfo)
  7710. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7711. if err != nil {
  7712. logs.Error(err)
  7713. return
  7714. }
  7715. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  7716. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7717. }
  7718. func UdMaterialIssuePush(c *gin.Context) {
  7719. appG := app.Gin{C: c}
  7720. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7721. fsions := gofasion.NewFasion(string(dataByte))
  7722. pastureid := fsions.Get("pastureId").ValueStr()
  7723. date := fsions.Get("date").ValueStr()
  7724. tx := restful.Engine.NewSession()
  7725. defer tx.Close()
  7726. pastureinfo := new(udPastureInfo)
  7727. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7728. if err != nil {
  7729. logs.Error(err)
  7730. return
  7731. }
  7732. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  7733. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7734. }
  7735. func DelFeedTemplet(c *gin.Context) {
  7736. appG := app.Gin{C: c}
  7737. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7738. fsions := gofasion.NewFasion(string(dataByte))
  7739. ftId := fsions.Get("ftId").ValueStr()
  7740. // userId := fsions.Get("userId").ValueStr()
  7741. tx := restful.Engine.NewSession()
  7742. defer tx.Close()
  7743. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  7744. if err != nil {
  7745. logs.Error(err)
  7746. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7747. return
  7748. }
  7749. // barIdList, err := tx.SQL(`select barid from feedp where ftid = ? `, ftId).QueryString()
  7750. // if err != nil {
  7751. // logs.Error(err)
  7752. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7753. // return
  7754. // }
  7755. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  7756. if err != nil {
  7757. logs.Error(err)
  7758. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  7759. return
  7760. }
  7761. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  7762. if err != nil {
  7763. logs.Error(err)
  7764. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  7765. return
  7766. }
  7767. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  7768. if count > 0 {
  7769. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  7770. if err != nil {
  7771. logs.Error(err)
  7772. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  7773. return
  7774. }
  7775. }
  7776. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  7777. if err != nil {
  7778. logs.Error(err)
  7779. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  7780. return
  7781. }
  7782. // var barIdStr []string
  7783. // for _, bar := range barIdList {
  7784. // barIdStr = append(barIdStr, bar["barid"])
  7785. // }
  7786. // if len(barIdStr) > 0 {
  7787. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  7788. // if err != nil {
  7789. // logs.Error(err)
  7790. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7791. // return
  7792. // }
  7793. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  7794. // if err != nil {
  7795. // logs.Error(err)
  7796. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7797. // return
  7798. // }
  7799. // now := time.Now()
  7800. // for _, newFpd := range newFpdDataList {
  7801. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  7802. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  7803. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  7804. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  7805. // if err != nil {
  7806. // logs.Error(err)
  7807. // appG.Response(http.StatusOK, e.ERROR, false)
  7808. // return
  7809. // }
  7810. // }
  7811. // for _, newFeedp := range newFeedpList {
  7812. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  7813. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  7814. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  7815. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  7816. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  7817. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  7818. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  7819. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  7820. // if err != nil {
  7821. // logs.Error(err)
  7822. // appG.Response(http.StatusOK, e.ERROR, false)
  7823. // return
  7824. // }
  7825. // }
  7826. // }
  7827. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7828. }
  7829. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  7830. data := fasion["parammaps"].(map[string]interface{})
  7831. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  7832. fmt.Println(err)
  7833. plancount1, err := tx.SQL(`SELECT
  7834. count( 1 )
  7835. FROM
  7836. (
  7837. SELECT
  7838. d.id
  7839. FROM
  7840. downloadedplan d
  7841. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  7842. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  7843. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  7844. WHERE
  7845. d.mydate = ?
  7846. AND d.havebutton = 0
  7847. AND lpplantype IN ( 0, 1, 2 )
  7848. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id ) =
  7849. ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.pid and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 )
  7850. GROUP BY
  7851. d.id
  7852. ) d
  7853. `,
  7854. data["startTime"]).Count()
  7855. fmt.Println(err)
  7856. if plancount != plancount1 && number < 10 {
  7857. number++
  7858. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  7859. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  7860. }
  7861. }
  7862. func EditPlanSort(c *gin.Context) {
  7863. appG := app.Gin{C: c}
  7864. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7865. fsions := gofasion.NewFasion(string(dataByte))
  7866. planIdStr := fsions.Get("planId").ValueStr()
  7867. mydate := fsions.Get("mydate").ValueStr()
  7868. sort := fsions.Get("sort").ValueStr()
  7869. tx := restful.Engine.NewSession()
  7870. defer tx.Close()
  7871. tx.Begin()
  7872. type downloadedplan struct {
  7873. Id int64 `xorm:"id"`
  7874. Sort int `xorm:"sort"`
  7875. Pid int64 `xorm:"pid"`
  7876. }
  7877. planInfo := new(downloadedplan)
  7878. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  7879. if err != nil {
  7880. logs.Error(err)
  7881. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7882. tx.Rollback()
  7883. return
  7884. }
  7885. sort1, _ := strconv.Atoi(sort)
  7886. if sort1 == planInfo.Sort {
  7887. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  7888. tx.Rollback()
  7889. return
  7890. }
  7891. count1, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and mydate = ? `, sort, mydate, mydate).Count()
  7892. if err != nil {
  7893. logs.Error(err)
  7894. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7895. tx.Rollback()
  7896. return
  7897. }
  7898. if count1 == 0 {
  7899. tx.Rollback()
  7900. logs.Error(err)
  7901. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  7902. return
  7903. }
  7904. count, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and havebutton = 1 and mydate = ? `, sort, mydate, mydate).Count()
  7905. if err != nil {
  7906. logs.Error(err)
  7907. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7908. tx.Rollback()
  7909. return
  7910. }
  7911. if count > 0 {
  7912. tx.Rollback()
  7913. logs.Error(err)
  7914. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  7915. return
  7916. }
  7917. if planInfo.Sort > sort1 {
  7918. minSortList, err := tx.SQL(`select min(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
  7919. if err != nil {
  7920. logs.Error(err)
  7921. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7922. tx.Rollback()
  7923. return
  7924. }
  7925. var minSort, pidCount int
  7926. for _, sort := range minSortList {
  7927. minSort, _ = strconv.Atoi(sort["sort"])
  7928. }
  7929. planList := make([]*downloadedplan, 0)
  7930. err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort >= ? order by sort`, mydate, minSort).Find(&planList)
  7931. if err != nil {
  7932. logs.Error(err)
  7933. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7934. tx.Rollback()
  7935. return
  7936. }
  7937. planPid := planInfo.Pid
  7938. planList1 := make([]*downloadedplan, 0)
  7939. planList2 := make([]*downloadedplan, 0)
  7940. for _, plan := range planList {
  7941. if plan.Pid == planPid {
  7942. pidCount++
  7943. planList1 = append(planList1, plan)
  7944. } else {
  7945. planList2 = append(planList2, plan)
  7946. }
  7947. }
  7948. planList1 = append(planList1, planList2...)
  7949. for i, plan := range planList1 {
  7950. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  7951. if err != nil {
  7952. logs.Error(err)
  7953. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  7954. tx.Rollback()
  7955. return
  7956. }
  7957. }
  7958. } else {
  7959. maxSortList, err := tx.SQL(`select max(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
  7960. if err != nil {
  7961. logs.Error(err)
  7962. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7963. tx.Rollback()
  7964. return
  7965. }
  7966. var maxSort int
  7967. for _, sort := range maxSortList {
  7968. maxSort, _ = strconv.Atoi(sort["sort"])
  7969. }
  7970. planList := make([]*downloadedplan, 0)
  7971. err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort <= ? order by sort`, mydate, maxSort).Find(&planList)
  7972. if err != nil {
  7973. logs.Error(err)
  7974. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7975. tx.Rollback()
  7976. return
  7977. }
  7978. planPid := planInfo.Pid
  7979. planList1 := make([]*downloadedplan, 0)
  7980. planList2 := make([]*downloadedplan, 0)
  7981. for _, plan := range planList {
  7982. if plan.Pid == planPid {
  7983. // pidCount++
  7984. planList1 = append(planList1, plan)
  7985. } else {
  7986. planList2 = append(planList2, plan)
  7987. }
  7988. }
  7989. planList2 = append(planList2, planList1...)
  7990. for i, plan := range planList2 {
  7991. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  7992. if err != nil {
  7993. logs.Error(err)
  7994. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  7995. tx.Rollback()
  7996. return
  7997. }
  7998. }
  7999. }
  8000. err = tx.Commit()
  8001. if err != nil {
  8002. logs.Error(err)
  8003. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8004. tx.Rollback()
  8005. return
  8006. }
  8007. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8008. }
  8009. func EditDownloadedplanArtificial(c *gin.Context) {
  8010. appG := app.Gin{C: c}
  8011. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8012. fsions := gofasion.NewFasion(string(dataByte))
  8013. planIdStr := fsions.Get("planId").ValueStr()
  8014. tx := restful.Engine.NewSession()
  8015. defer tx.Close()
  8016. tx.Begin()
  8017. planIdList := strings.Split(planIdStr, ",")
  8018. for _, planId := range planIdList {
  8019. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8020. if err != nil {
  8021. logs.Error(err)
  8022. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8023. tx.Rollback()
  8024. return
  8025. }
  8026. }
  8027. err := tx.Commit()
  8028. if err != nil {
  8029. logs.Error(err)
  8030. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8031. tx.Rollback()
  8032. return
  8033. }
  8034. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8035. }
  8036. type PlanRFID struct {
  8037. RFID string `json:"RFID"`
  8038. Lweight string `json:"lweight"`
  8039. Gear string `json:"gear"`
  8040. Speed string `json:"speed"`
  8041. }
  8042. func GetPlanRFID(c *gin.Context) {
  8043. appG := app.Gin{C: c}
  8044. RFIDStr := c.Query("RFID")
  8045. planRFIDList := make([]*PlanRFID, 0)
  8046. planRFIDList = append(planRFIDList, &PlanRFID{
  8047. RFID: RFIDStr,
  8048. Lweight: "1411.1",
  8049. Gear: "1",
  8050. Speed: "10",
  8051. })
  8052. planRFIDList = append(planRFIDList, &PlanRFID{
  8053. RFID: RFIDStr,
  8054. Lweight: "1322.1",
  8055. Gear: "1",
  8056. Speed: "10",
  8057. })
  8058. planRFIDList = append(planRFIDList, &PlanRFID{
  8059. RFID: RFIDStr,
  8060. Lweight: "1904.1",
  8061. Gear: "1",
  8062. Speed: "10",
  8063. })
  8064. planRFIDList = append(planRFIDList, &PlanRFID{
  8065. RFID: RFIDStr,
  8066. Lweight: "1870.1",
  8067. Gear: "1",
  8068. Speed: "10",
  8069. })
  8070. planRFIDList = append(planRFIDList, &PlanRFID{
  8071. RFID: RFIDStr,
  8072. Lweight: "2041.1",
  8073. Gear: "1",
  8074. Speed: "10",
  8075. })
  8076. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8077. }
  8078. type tmrEquipmentMuster struct {
  8079. A string
  8080. N string
  8081. }
  8082. func GetTmrEquipmentMuster(c *gin.Context) {
  8083. appG := app.Gin{C: c}
  8084. id := c.Query("id")
  8085. tx := restful.Engine.NewSession()
  8086. defer tx.Close()
  8087. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8088. if err != nil {
  8089. logs.Error(err)
  8090. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8091. return
  8092. }
  8093. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  8094. for _, data := range dataList {
  8095. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  8096. for _, g := range tmrEquipmentMusterList {
  8097. a, _ := strconv.ParseFloat(g.A, 64)
  8098. n, _ := strconv.ParseFloat(g.N, 64)
  8099. a1, n1 := ddmmtoddd(a, n)
  8100. g.A = fmt.Sprintf("%f", n1)
  8101. g.N = fmt.Sprintf("%f", a1)
  8102. }
  8103. }
  8104. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  8105. }
  8106. func ddmmtoddd(lng, lat float64) (float64, float64) {
  8107. lngDegree := fmt.Sprintf("%f", lng/100)
  8108. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  8109. lngDegreeInt := int(lngDegreefloat * 1000000)
  8110. dd := lngDegreeInt / 100 * 100 / 60
  8111. fmt.Println(dd)
  8112. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  8113. latDegree := fmt.Sprintf("%f", lat/100)
  8114. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  8115. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  8116. latDegreeInt := int(latDegreefloat * 1000000)
  8117. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  8118. a, _ := strconv.ParseFloat(lngStr, 64)
  8119. b, _ := strconv.ParseFloat(latStr, 64)
  8120. return coordtransform.WGS84toGCJ02(b, a)
  8121. }