ops.go 282 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354
  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/tealeg/xlsx"
  30. "github.com/xormplus/xorm"
  31. )
  32. // @Summary 根据SQL执行得到数据集
  33. // @Tags getData
  34. // @Accept json
  35. // @Produce json
  36. // @Param sql query string true "sql"
  37. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  38. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  39. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  40. // @Router /data/getdata [POST]
  41. func GetData(c *gin.Context) {
  42. appG := app.Gin{C: c}
  43. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  44. fsion := gofasion.NewFasion(string(dataByte))
  45. sqlstr := fsion.Get("sql").ValueStr()
  46. offset := fsion.Get("offset").ValueDefaultInt(0)
  47. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  48. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  49. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  50. if err != nil {
  51. appG.Response(http.StatusOK, e.ERROR, err.Error())
  52. } else {
  53. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  54. }
  55. }
  56. func Testpartitions(c *gin.Context) {
  57. appG := app.Gin{C: c}
  58. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  59. fsion := gofasion.NewFasion(string(dataByte))
  60. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  61. user := fsion.Get("user").ValueStr() //获取新数据库用户
  62. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  63. host := fsion.Get("host").ValueStr() //获取新数据库名称
  64. port := fsion.Get("port").ValueStr() //获取新数据库名称
  65. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  66. if sqls == nil || err1 != nil {
  67. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  68. }
  69. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  70. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  71. mydb, err := sql.Open("mysql", connecting) //连接新连接
  72. if err != nil {
  73. println("err1", err.Error())
  74. }
  75. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  76. if err != nil {
  77. println("err2", err.Error())
  78. }
  79. mydb.Close()
  80. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  81. mydb, err = sql.Open("mysql", connecting)
  82. if err != nil {
  83. println("err3", err.Error())
  84. }
  85. defer mydb.Close()
  86. if err == nil {
  87. mydb.SetMaxOpenConns(10)
  88. mydb.SetMaxIdleConns(10)
  89. }
  90. errmsg := ""
  91. if err == nil {
  92. //tx ,_ :=mydb.Begin()
  93. for _, sqlstr := range sqlstrs {
  94. //println("sqlstr---",sqlstr)
  95. if sqlstr == "" {
  96. continue
  97. }
  98. _, err = mydb.Exec(sqlstr)
  99. if err != nil {
  100. println("err4", err.Error())
  101. errmsg = err.Error()
  102. //err1 :=tx.Rollback()
  103. }
  104. }
  105. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  106. //err =tx.Commit()
  107. }
  108. if errmsg == "" {
  109. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  110. } else {
  111. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  112. }
  113. }
  114. func TestData(c *gin.Context) {
  115. appG := app.Gin{C: c}
  116. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  117. fsion := gofasion.NewFasion(string(dataByte))
  118. sqlstr := fsion.Get("sql").ValueStr()
  119. token := ""
  120. if tempv, exists := c.Get("jwt_username"); exists {
  121. token = tempv.(string)
  122. }
  123. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  124. }
  125. // @Summary 根据APISQL表中SQL执行得到数据集
  126. // @Tags GetDataByName
  127. // @Accept json
  128. // @Produce json
  129. // @Param sqlname body string true "sqlname"
  130. // @Param offset body int true "offset"
  131. // @Param pagecount body int true "pagecount"
  132. // @Param returntype body string true "returntype"
  133. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  134. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  135. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  136. // @Router /data/GetDataByName [POST]
  137. func GetDataByName(c *gin.Context) {
  138. appG := app.Gin{C: c}
  139. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  140. fsion := gofasion.NewFasion(string(dataByte))
  141. sqlnamestr := fsion.Get("name").ValueStr()
  142. offset := fsion.Get("offset").ValueDefaultInt(0)
  143. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  144. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  145. tx := restful.Engine.NewSession()
  146. err := tx.Begin()
  147. defer func() {
  148. switch {
  149. case err != nil:
  150. logging.Error("tx.Begin 事务启动失败__error:", err)
  151. if tx != nil {
  152. tx.Rollback()
  153. }
  154. default:
  155. if tx != nil {
  156. err = tx.Commit()
  157. }
  158. }
  159. if tx != nil {
  160. tx.Close()
  161. }
  162. }()
  163. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  164. if sql != "" {
  165. s_params := make([]interface{}, 0)
  166. if fsion.HasKey("parammaps") {
  167. parammaps := fsion.Get("parammaps")
  168. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  169. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  170. }
  171. paramslist := strings.Split(p, ",")
  172. if len(paramslist) > 0 && p != "" {
  173. for _, value := range paramslist {
  174. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  175. if tempv, exists := c.Get("jwt_username"); exists {
  176. s_params = append(s_params, tempv.(string))
  177. } else {
  178. s_params = append(s_params, "")
  179. }
  180. } else {
  181. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  182. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  183. // tmrNameList := []string{}
  184. // for _, tmr := range tmrArray {
  185. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  186. // }
  187. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  188. // } else {
  189. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  190. // }
  191. }
  192. }
  193. }
  194. } else if fsion.HasKey("params") {
  195. params := fsion.Get("params").Array()
  196. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  197. for _, v_params := range params {
  198. s_params = append(s_params, v_params.ValueStr())
  199. }
  200. }
  201. if returntype == "xlsx" {
  202. var xlsxfile *xlsx.File
  203. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  204. //c.File("c:/dd.xlsx")
  205. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  206. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  207. c.Header("Content-Transfer-Encoding", "binary")
  208. _ = xlsxfile.Write(c.Writer)
  209. } else {
  210. if sqlnamestr == "getHomepageStr" {
  211. parammaps := fsion.Get("parammaps")
  212. pastureid := parammaps.Get("pastureid").ValueStr()
  213. var montimeList []float64
  214. var montime float64
  215. var wg sync.WaitGroup
  216. now := time.Now()
  217. for i := 0; i < 30; i++ {
  218. wg.Add(1)
  219. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  220. go func(nowstr string) {
  221. defer wg.Done()
  222. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  223. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  224. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  225. montimeList = append(montimeList, m)
  226. }(nowstr)
  227. }
  228. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  229. if err != nil {
  230. logging.Error("GetDataByName err: ", err)
  231. msg := geterrmsg(err.Error())
  232. appG.Response(http.StatusOK, e.ERROR, msg)
  233. }
  234. wg.Wait()
  235. for _, m := range montimeList {
  236. montime += m
  237. }
  238. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  239. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  240. return
  241. }
  242. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  243. if err != nil {
  244. logging.Error("GetDataByName err: ", err)
  245. msg := geterrmsg(err.Error())
  246. appG.Response(http.StatusOK, e.ERROR, msg)
  247. } else {
  248. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  249. }
  250. }
  251. } else {
  252. appG.Response(http.StatusOK, e.SUCCESS, nil)
  253. }
  254. }
  255. // @Summary 根据APISQL表中SQL执行得到数据集
  256. // @Tags GetDataByName
  257. // @Accept json
  258. // @Produce json
  259. // @Param sqlname body string true "sqlname"
  260. // @Param offset body int true "offset"
  261. // @Param pagecount body int true "pagecount"
  262. // @Param returntype body string true "returntype"
  263. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  264. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  265. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  266. // @Router /data/GetDataByName [POST]
  267. func GetDataBySqlIN(c *gin.Context) {
  268. appG := app.Gin{C: c}
  269. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  270. fsion := gofasion.NewFasion(string(dataByte))
  271. sqlnamestr := fsion.Get("name").ValueStr()
  272. offset := fsion.Get("offset").ValueDefaultInt(0)
  273. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  274. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  275. tx := restful.Engine.NewSession()
  276. err := tx.Begin()
  277. defer func() {
  278. switch {
  279. case err != nil:
  280. logging.Error("tx.Begin 事务启动失败__error:", err)
  281. if tx != nil {
  282. tx.Rollback()
  283. }
  284. default:
  285. if tx != nil {
  286. err = tx.Commit()
  287. }
  288. }
  289. if tx != nil {
  290. tx.Close()
  291. }
  292. }()
  293. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  294. if sql != "" {
  295. s_params := make([]interface{}, 0)
  296. if fsion.HasKey("parammaps") {
  297. parammaps := fsion.Get("parammaps")
  298. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  299. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  300. }
  301. paramslist := strings.Split(p, ",")
  302. if len(paramslist) > 0 && p != "" {
  303. for _, value := range paramslist {
  304. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  305. if tempv, exists := c.Get("jwt_username"); exists {
  306. s_params = append(s_params, tempv.(string))
  307. } else {
  308. s_params = append(s_params, "")
  309. }
  310. } else {
  311. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  312. }
  313. }
  314. }
  315. } else if fsion.HasKey("params") {
  316. params := fsion.Get("params").Array()
  317. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  318. for _, v_params := range params {
  319. s_params = append(s_params, v_params.ValueStr())
  320. }
  321. }
  322. if returntype == "xlsx" {
  323. var xlsxfile *xlsx.File
  324. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  325. //c.File("c:/dd.xlsx")
  326. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  327. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  328. c.Header("Content-Transfer-Encoding", "binary")
  329. _ = xlsxfile.Write(c.Writer)
  330. } else {
  331. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  332. if err != nil {
  333. logging.Error("GetDataByName err: ", err)
  334. msg := geterrmsg(err.Error())
  335. appG.Response(http.StatusOK, e.ERROR, msg)
  336. } else {
  337. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  338. }
  339. }
  340. } else {
  341. appG.Response(http.StatusOK, e.SUCCESS, nil)
  342. }
  343. }
  344. // 错误处理
  345. // 将报错信息处理成汉字
  346. func geterrmsg(errstr string) (msgstr string) {
  347. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  348. rs := []rune(errstr)
  349. if hzRegexp.MatchString(string(rs[0])) {
  350. msgstr = errstr
  351. return
  352. }
  353. if strings.Contains(errstr, "Duplicate entry") {
  354. strs := strings.Split(errstr, ` key '`)
  355. if len(strs) > 1 {
  356. if len(strs[len(strs)-1]) > 1 {
  357. errstr = "Duplicate entry :" + strs[len(strs)-1]
  358. }
  359. }
  360. }
  361. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  362. if err != nil {
  363. msgstr = errstr
  364. return
  365. }
  366. if msg == nil || len(msg) == 0 {
  367. var param []interface{}
  368. param = append(param, errstr, errstr)
  369. go func() {
  370. tx := restful.Engine.NewSession()
  371. err := tx.Begin()
  372. defer func() {
  373. switch {
  374. case err != nil:
  375. logging.Error("tx.Begin 事务启动失败__error:", err)
  376. if tx != nil {
  377. tx.Rollback()
  378. }
  379. default:
  380. if tx != nil {
  381. err = tx.Commit()
  382. }
  383. }
  384. if tx != nil {
  385. tx.Close()
  386. }
  387. }()
  388. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  389. if err != nil {
  390. logging.Error("insert into err_msg(err,msg) err", err)
  391. }
  392. }()
  393. msgstr = errstr
  394. } else {
  395. msgstr = msg[0]["msg"]
  396. }
  397. return
  398. }
  399. // @Summary 根据APISQL表中SQL执行得到数据集
  400. // @Tags GetDataByNameForm
  401. // @Accept json
  402. // @Produce json
  403. // @Param sqlname body json true "sqlname"
  404. // @Param offset query int true "offset"
  405. // @Param pagecount query int true "pagecount"
  406. // @Param returntype query string true "returntype"
  407. // @Param s formData json true "ss"
  408. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  409. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  410. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  411. // @Router /data/GetDataByNameForm [POST]
  412. func GetDataByNameForm(c *gin.Context) {
  413. appG := app.Gin{C: c}
  414. //sqlnamestr := c.PostForm("measureNumber")
  415. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  416. //fsion := gofasion.NewFasion(string(dataByte))
  417. //sqlnamestr := fsion.Get("name").ValueStr()
  418. //offset := fsion.Get("offset").ValueInt()
  419. //pagecount := fsion.Get("pagecount").ValueInt()
  420. //returntype := fsion.Get("returntype").ValueStr()
  421. //params := fsion.Get("params").Array()
  422. c.Request.ParseForm()
  423. params := c.Request.Form
  424. offset := 0
  425. pageSize_ := 0
  426. returntype := params.Get("page")
  427. if returntype == "" {
  428. returntype = "0"
  429. }
  430. if tempv, exists := c.Get("jwt_username"); exists {
  431. params.Set("JwtUserName", tempv.(string))
  432. } else {
  433. params.Set("JwtUserName", "")
  434. }
  435. sqlnamestr := params.Get("name")
  436. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  437. s_params := make([]interface{}, 0)
  438. if returntype == "1" {
  439. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  440. if error != nil {
  441. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  442. }
  443. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  444. if error != nil {
  445. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  446. }
  447. pageSize_ = pageSize
  448. offset = pageNum
  449. }
  450. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  451. paramslist := strings.Split(p, ",")
  452. if len(paramslist) > 0 && p != "" {
  453. for _, value := range paramslist {
  454. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  455. }
  456. }
  457. if sql != "" {
  458. if returntype == "xlsx" {
  459. var xlsxfile *xlsx.File
  460. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  461. c.Header("Content-Type", "application/octet-stream")
  462. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  463. c.Header("Content-Transfer-Encoding", "binary")
  464. _ = xlsxfile.Write(c.Writer)
  465. } else {
  466. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  467. if err != nil {
  468. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  469. } else {
  470. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  471. }
  472. }
  473. } else {
  474. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  475. }
  476. }
  477. // @Summary 递归获取所有
  478. // @Tags menu
  479. // @Accept json
  480. // @Produce json
  481. // @Param Ton query string true "Ton"
  482. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  483. // @Router /authdata/GetRoleMenus [GET]
  484. func GetRecuDataByName(c *gin.Context) {
  485. appG := app.Gin{C: c}
  486. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  487. fsion := gofasion.NewFasion(string(dataByte))
  488. sqlnamestr := fsion.Get("name").ValueStr()
  489. parentidname := fsion.Get("idname").ValueStr()
  490. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  491. params := make(map[string]interface{})
  492. s_params := make([]interface{}, 0)
  493. if fsion.HasKey("params") {
  494. for _, v_params := range fsion.Get("params").Array() {
  495. s_params = append(s_params, v_params.ValueStr())
  496. }
  497. params["params"] = s_params
  498. } else {
  499. jparams := fsion.Get("parammaps")
  500. paramslist := strings.Split(p, ",")
  501. if len(paramslist) > 0 && p != "" {
  502. for _, value := range paramslist {
  503. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  504. if tempv, exists := c.Get("jwt_username"); exists {
  505. params[value] = tempv.(string)
  506. } else {
  507. params[value] = ""
  508. }
  509. } else {
  510. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  511. }
  512. }
  513. }
  514. }
  515. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  516. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  517. if err != nil {
  518. appG.Response(http.StatusOK, e.ERROR, err.Error())
  519. }
  520. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  521. }
  522. // @Summary 根据APISQL表中SQL执行得到数据集
  523. // @Tags GetDataByNames
  524. // @Accept json
  525. // @Produce json
  526. // @RequestBody sqlname query string true "sqlname"
  527. // @Param offset query int true "offset"
  528. // @Param pagecount query int true "pagecount"
  529. // @Param returntype query string true "returntype"
  530. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  531. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  532. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  533. // @Router /data/GetDataByNames [POST]
  534. func GetDataByNames(c *gin.Context) {
  535. appG := app.Gin{C: c}
  536. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  537. fsion := gofasion.NewFasion(string(dataByte))
  538. sqlParams := fsion.Array()
  539. queryData := make(map[string]interface{})
  540. for _, v := range sqlParams {
  541. fsion2 := gofasion.NewFasion(v.Json())
  542. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  543. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  544. if sql == "" {
  545. errorm := make(map[string]interface{})
  546. errorm["code"] = e.ERROR
  547. errorm["message"] = "sql没找到"
  548. queryData[fsion2.Get("name").ValueStr()] = errorm
  549. continue
  550. } else if sql != "" {
  551. offset := fsion2.Get("offset").ValueInt()
  552. pagecount := fsion2.Get("pagecount").ValueInt()
  553. returntype := fsion2.Get("returntype").ValueStr()
  554. s_params := make([]interface{}, 0)
  555. if fsion2.HasKey("parammaps") {
  556. parammaps := fsion2.Get("parammaps")
  557. paramslist := strings.Split(p, ",")
  558. if len(paramslist) > 0 && p != "" {
  559. for _, value := range paramslist {
  560. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  561. if tempv, exists := c.Get("jwt_username"); exists {
  562. s_params = append(s_params, tempv.(string))
  563. } else {
  564. s_params = append(s_params, "")
  565. }
  566. } else {
  567. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  568. }
  569. }
  570. }
  571. } else if fsion2.HasKey("params") {
  572. params := fsion2.Get("params").Array()
  573. for _, v_params := range params {
  574. s_params = append(s_params, v_params.ValueStr())
  575. }
  576. }
  577. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  578. if err != nil {
  579. errorm := make(map[string]interface{})
  580. errorm["code"] = e.ERROR
  581. errorm["message"] = err.Error()
  582. queryData[fsion2.Get("name").ValueStr()] = errorm
  583. logging.Error("GetDataByNames err: ", err)
  584. continue
  585. } else {
  586. queryData[fsion2.Get("name").ValueStr()] = queryData1
  587. }
  588. }
  589. }
  590. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  591. }
  592. // @Summary 根据APISQL表中SQL执行得到数据集
  593. // @Tags PostDataByNameForm
  594. // @Accept json
  595. // @Produce json
  596. // @Param sqlname query string true "sqlname"
  597. // @Param offset query int true "offset"
  598. // @Param pagecount query int true "pagecount"
  599. // @Param returntype query string true "returntype"
  600. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  601. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  602. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  603. // @Router /data/PostDataByNameForm [POST]
  604. func PostDataByNameForm(c *gin.Context) {
  605. appG := app.Gin{C: c}
  606. c.Request.ParseForm()
  607. params := c.Request.Form
  608. sqlnamestr := params.Get("name")
  609. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  610. s_params := make([]interface{}, 0)
  611. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  612. paramslist := strings.Split(p, ",")
  613. if len(paramslist) > 0 {
  614. for _, value := range paramslist {
  615. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  616. }
  617. }
  618. if sql != "" {
  619. queryData, err := execDataBySql(sql, s_params)
  620. if err != nil {
  621. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  622. } else {
  623. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  624. }
  625. } else {
  626. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  627. }
  628. }
  629. // GetReportform 将数据集转换格式
  630. // @Tags PostDataByNameForm
  631. // @Accept json
  632. // @Produce json
  633. // @Param sqlname query string true "sqlname"
  634. // @Param offset query int true "offset"
  635. // @Param pagecount query int true "pagecount"
  636. // @Param returntype query string true "returntype"
  637. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  638. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  639. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  640. func GetReportform(c *gin.Context) {
  641. appG := app.Gin{C: c}
  642. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  643. fsion := gofasion.NewFasion(string(dataByte))
  644. sqlnamestr := fsion.Get("name").ValueStr()
  645. checked := fsion.Get("checked").ValueStr()
  646. offset := fsion.Get("offset").ValueDefaultInt(0)
  647. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  648. parammaps := fsion.Get("parammaps")
  649. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  650. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  651. tx := restful.Engine.NewSession()
  652. err := tx.Begin()
  653. defer func() {
  654. switch {
  655. case err != nil:
  656. if tx != nil {
  657. tx.Rollback()
  658. }
  659. default:
  660. if tx != nil {
  661. err = tx.Commit()
  662. }
  663. }
  664. if tx != nil {
  665. tx.Close()
  666. }
  667. }()
  668. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea)
  669. if err != nil {
  670. appG.Response(http.StatusOK, e.ERROR, err.Error())
  671. } else {
  672. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  673. }
  674. }
  675. // GetUpkeepPlan 保养计划
  676. func GetUpkeepPlan(c *gin.Context) {
  677. appG := app.Gin{C: c}
  678. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  679. fsion := gofasion.NewFasion(string(dataByte))
  680. sqlnamestr := fsion.Get("name").ValueStr()
  681. offset := fsion.Get("offset").ValueDefaultInt(0)
  682. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  683. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  684. month := fsion.Get("month").ValueDefaultStr("map")
  685. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  686. tx := restful.Engine.NewSession()
  687. err := tx.Begin()
  688. defer func() {
  689. switch {
  690. case err != nil:
  691. if tx != nil {
  692. tx.Rollback()
  693. }
  694. default:
  695. if tx != nil {
  696. err = tx.Commit()
  697. }
  698. }
  699. if tx != nil {
  700. tx.Close()
  701. }
  702. }()
  703. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  704. if sql != "" {
  705. s_params := make([]interface{}, 0)
  706. if fsion.HasKey("parammaps") {
  707. parammaps := fsion.Get("parammaps")
  708. paramslist := strings.Split(p, ",")
  709. if len(paramslist) > 0 && p != "" {
  710. for _, value := range paramslist {
  711. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  712. if tempv, exists := c.Get("jwt_username"); exists {
  713. s_params = append(s_params, tempv.(string))
  714. } else {
  715. s_params = append(s_params, "")
  716. }
  717. } else {
  718. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  719. }
  720. }
  721. }
  722. } else if fsion.HasKey("params") {
  723. params := fsion.Get("params").Array()
  724. for _, v_params := range params {
  725. s_params = append(s_params, v_params.ValueStr())
  726. }
  727. }
  728. if returntype == "xlsx" {
  729. var xlsxfile *xlsx.File
  730. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  731. //c.File("c:/dd.xlsx")
  732. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  733. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  734. c.Header("Content-Transfer-Encoding", "binary")
  735. _ = xlsxfile.Write(c.Writer)
  736. } else {
  737. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  738. if err != nil {
  739. appG.Response(http.StatusOK, e.ERROR, err.Error())
  740. } else {
  741. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  742. if v, ok := value["id"]; ok {
  743. //month = "2020-03"
  744. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  745. if seviceplans != nil {
  746. for _, va := range seviceplans { //根据保养计划获取保养单
  747. //day,_ :=strconv.Atoi(va["day"])
  748. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  749. //buk := make(map[string]map[string]string)
  750. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  751. jstr := ""
  752. if bu["plantime"][8:9] == "0" {
  753. jstr = "m" + bu["plantime"][9:]
  754. } else {
  755. jstr = "m" + bu["plantime"][8:]
  756. }
  757. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  758. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  759. } else {
  760. if bu["flowCompeleted"] >= "2" {
  761. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  762. } else {
  763. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  764. }
  765. }
  766. }
  767. }
  768. }
  769. }
  770. }
  771. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  772. }
  773. }
  774. } else {
  775. appG.Response(http.StatusOK, e.SUCCESS, nil)
  776. }
  777. }
  778. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  779. // todo 优化性能 children统一查询
  780. // @Tags PostDataByNameForm
  781. // @Accept json
  782. // @Produce json
  783. // @Param sqlname query string true "sqlname"
  784. // @Param offset query int true "offset"
  785. // @Param pagecount query int true "pagecount"
  786. // @Param returntype query string true "returntype"
  787. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  788. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  789. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  790. func GetArrList(c *gin.Context) {
  791. appG := app.Gin{C: c}
  792. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  793. fsion := gofasion.NewFasion(string(dataByte))
  794. sqlnamestr := fsion.Get("name").ValueStr()
  795. sqlnamestr1 := fsion.Get("name1").ValueStr()
  796. offset := fsion.Get("offset").ValueDefaultInt(0)
  797. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  798. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  799. month := fsion.Get("month").ValueDefaultStr("map")
  800. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  801. tx := restful.Engine.NewSession()
  802. err := tx.Begin()
  803. defer func() {
  804. switch {
  805. case err != nil:
  806. if tx != nil {
  807. tx.Rollback()
  808. }
  809. default:
  810. if tx != nil {
  811. err = tx.Commit()
  812. }
  813. }
  814. if tx != nil {
  815. tx.Close()
  816. }
  817. }()
  818. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  819. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  820. if sql != "" {
  821. s_params := make([]interface{}, 0)
  822. if fsion.HasKey("parammaps") {
  823. parammaps := fsion.Get("parammaps")
  824. paramslist := strings.Split(p, ",")
  825. if len(paramslist) > 0 && p != "" {
  826. for _, value := range paramslist {
  827. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  828. if tempv, exists := c.Get("jwt_username"); exists {
  829. s_params = append(s_params, tempv.(string))
  830. } else {
  831. s_params = append(s_params, "")
  832. }
  833. } else {
  834. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  835. }
  836. }
  837. }
  838. }
  839. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  840. if err != nil {
  841. appG.Response(http.StatusOK, e.ERROR, err.Error())
  842. } else {
  843. paramslist1 := strings.Split(p1, ",")
  844. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  845. s_params1 := make([]interface{}, 0)
  846. if len(paramslist1) > 0 && p1 != "" {
  847. for _, v := range paramslist1 {
  848. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  849. }
  850. }
  851. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  852. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  853. }
  854. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  855. }
  856. } else {
  857. appG.Response(http.StatusOK, e.SUCCESS, nil)
  858. }
  859. }
  860. func GetAccount(c *gin.Context) {
  861. appG := app.Gin{C: c}
  862. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  863. fsion := gofasion.NewFasion(string(dataByte))
  864. sqlnamestr := fsion.Get("name").ValueStr()
  865. offset := fsion.Get("offset").ValueDefaultInt(0)
  866. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  867. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  868. tx := restful.Engine.NewSession()
  869. err := tx.Begin()
  870. defer func() {
  871. switch {
  872. case err != nil:
  873. logging.Error("tx.Begin 事务启动失败__error:", err)
  874. if tx != nil {
  875. tx.Rollback()
  876. }
  877. default:
  878. if tx != nil {
  879. err = tx.Commit()
  880. }
  881. }
  882. if tx != nil {
  883. tx.Close()
  884. }
  885. }()
  886. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  887. if sql != "" {
  888. s_params := make([]interface{}, 0)
  889. if fsion.HasKey("parammaps") {
  890. parammaps := fsion.Get("parammaps")
  891. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  892. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  893. }
  894. paramslist := strings.Split(p, ",")
  895. if len(paramslist) > 0 && p != "" {
  896. for _, value := range paramslist {
  897. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  898. if tempv, exists := c.Get("jwt_username"); exists {
  899. s_params = append(s_params, tempv.(string))
  900. } else {
  901. s_params = append(s_params, "")
  902. }
  903. } else {
  904. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  905. }
  906. }
  907. }
  908. } else if fsion.HasKey("params") {
  909. params := fsion.Get("params").Array()
  910. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  911. for _, v_params := range params {
  912. s_params = append(s_params, v_params.ValueStr())
  913. }
  914. }
  915. if returntype == "xlsx" {
  916. var xlsxfile *xlsx.File
  917. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  918. //c.File("c:/dd.xlsx")
  919. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  920. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  921. c.Header("Content-Transfer-Encoding", "binary")
  922. _ = xlsxfile.Write(c.Writer)
  923. } else {
  924. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  925. if err != nil {
  926. logging.Error("GetDataByName err: ", err)
  927. msg := geterrmsg(err.Error())
  928. appG.Response(http.StatusOK, e.ERROR, msg)
  929. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  930. } else {
  931. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  932. }
  933. }
  934. } else {
  935. appG.Response(http.StatusOK, e.SUCCESS, nil)
  936. }
  937. }
  938. // PostDataByName 根据APISQL表中SQL执行得到数据集
  939. // @Accept json
  940. // @Produce json
  941. // @Param sqlname query string true "sqlname"
  942. // @Param offset query int true "offset"
  943. // @Param pagecount query int true "pagecount"
  944. // @Param returntype query string true "returntype"
  945. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  946. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  947. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  948. // @Router /data/PostDataByName [POST]
  949. func PostDataByName(c *gin.Context) {
  950. appG := app.Gin{C: c}
  951. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  952. fsion := gofasion.NewFasion(string(dataByte))
  953. var err error
  954. queryData, err := module.PostDataByName(c, fsion)
  955. if err != nil {
  956. appG.Response(http.StatusOK, e.ERROR, err)
  957. return
  958. }
  959. var (
  960. keyWord string
  961. )
  962. switch fsion.Get("name").ValueStr() {
  963. case "insertFeedclass":
  964. keyWord = "feed"
  965. err = module.GroupCategorySync(keyWord, fsion)
  966. case "deleteFeedclass":
  967. keyWord = "feed_delete"
  968. err = module.GroupCategoryDelete(keyWord, fsion)
  969. case "insertCowclass":
  970. keyWord = "cow"
  971. err = module.GroupCategorySync(keyWord, fsion)
  972. case "deleteCowclass":
  973. keyWord = "cow_delete"
  974. err = module.GroupCategoryDelete(keyWord, fsion)
  975. default:
  976. }
  977. if err != nil {
  978. logging.Error(keyWord, err)
  979. }
  980. if queryData != nil {
  981. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  982. return
  983. }
  984. appG.Response(http.StatusOK, e.SUCCESS, nil)
  985. }
  986. //人脸识别/格润富德接口
  987. func GetRJSBData(c *gin.Context) {
  988. appG := app.Gin{C: c}
  989. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  990. fsion := gofasion.NewFasion(string(dataByte))
  991. sqlnamestr := fsion.Get("name").ValueStr()
  992. sqlnamestr1 := fsion.Get("name1").ValueStr()
  993. offset := fsion.Get("offset").ValueDefaultInt(0)
  994. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  995. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  996. month := fsion.Get("month").ValueDefaultStr("map")
  997. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  998. tx := restful.Engine.NewSession()
  999. err := tx.Begin()
  1000. defer func() {
  1001. switch {
  1002. case err != nil:
  1003. if tx != nil {
  1004. tx.Rollback()
  1005. }
  1006. default:
  1007. if tx != nil {
  1008. err = tx.Commit()
  1009. }
  1010. }
  1011. if tx != nil {
  1012. tx.Close()
  1013. }
  1014. }()
  1015. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1016. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1017. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1018. if sql != "" {
  1019. s_params := make([]interface{}, 0)
  1020. if fsion.HasKey("parammaps") {
  1021. parammaps := fsion.Get("parammaps")
  1022. paramslist := strings.Split(p, ",")
  1023. if len(paramslist) > 0 && p != "" {
  1024. for _, value := range paramslist {
  1025. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1026. if tempv, exists := c.Get("jwt_username"); exists {
  1027. s_params = append(s_params, tempv.(string))
  1028. } else {
  1029. s_params = append(s_params, "")
  1030. }
  1031. } else {
  1032. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1033. }
  1034. }
  1035. }
  1036. }
  1037. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1038. if err != nil {
  1039. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1040. } else {
  1041. paramslist1 := strings.Split(p1, ",")
  1042. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1043. s_params1 := make([]interface{}, 0)
  1044. if len(paramslist1) > 0 && p1 != "" {
  1045. for _, v := range paramslist1 {
  1046. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1047. }
  1048. }
  1049. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1050. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1051. }
  1052. // var wg sync.WaitGroup
  1053. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1054. // wg.Add(1)
  1055. // go func(value map[string]interface{}) {
  1056. // defer wg.Done()
  1057. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1058. // }(value)
  1059. // }
  1060. // wg.Wait()
  1061. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1062. }
  1063. } else {
  1064. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1065. }
  1066. }
  1067. func PostRJSBData(c *gin.Context) {
  1068. appG := app.Gin{C: c}
  1069. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1070. fsion := gofasion.NewFasion(string(dataByte))
  1071. logging.Info("PostRJSBData err: ", string(dataByte))
  1072. s_params := make([]interface{}, 0)
  1073. tx := restful.Engine.NewSession()
  1074. err := tx.Begin()
  1075. defer func() {
  1076. switch {
  1077. case err != nil:
  1078. if tx != nil {
  1079. tx.Rollback()
  1080. }
  1081. default:
  1082. if tx != nil {
  1083. err = tx.Commit()
  1084. }
  1085. }
  1086. if tx != nil {
  1087. tx.Close()
  1088. }
  1089. }()
  1090. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1091. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1092. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1093. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1094. if !fsion.HasKey("parammaps") {
  1095. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1096. return
  1097. }
  1098. parammaps := fsion.Get("parammaps")
  1099. paramslist := strings.Split(p, ",")
  1100. if len(paramslist) > 0 && p != "" {
  1101. for _, value := range paramslist {
  1102. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1103. }
  1104. }
  1105. _, err = tx.SQL(sql, s_params...).Execute()
  1106. if err != nil {
  1107. logging.Error("PostRJSBData err: ", err)
  1108. msg := geterrmsg(err.Error())
  1109. appG.Response(http.StatusOK, e.ERROR, msg)
  1110. return
  1111. }
  1112. s_params = make([]interface{}, 0)
  1113. paramslist = strings.Split(p1, ",")
  1114. if len(paramslist) > 0 && p1 != "" {
  1115. for _, value := range paramslist {
  1116. // if value == "ID" {
  1117. // id := parammaps.Get("ID").ValueStr()
  1118. // pastureid := parammaps.Get("pastureid").ValueStr()
  1119. // 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
  1120. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1121. // if err != nil {
  1122. // logging.Error("PostRJSBData err: ", err)
  1123. // msg := geterrmsg(err.Error())
  1124. // appG.Response(http.StatusOK, e.ERROR, msg)
  1125. // return
  1126. // }
  1127. // for _, item := range datalist {
  1128. // id = item["id"]
  1129. // }
  1130. // s_params = append(s_params, id)
  1131. // } else {
  1132. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1133. // }
  1134. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1135. }
  1136. }
  1137. _, err = tx.SQL(sql1, s_params...).Execute()
  1138. if err != nil {
  1139. logging.Error("PostRJSBData1 err: ", err)
  1140. msg := geterrmsg(err.Error())
  1141. appG.Response(http.StatusOK, e.ERROR, msg)
  1142. return
  1143. }
  1144. s_params = make([]interface{}, 0)
  1145. paramslist = strings.Split(p2, ",")
  1146. if len(paramslist) > 0 && p2 != "" {
  1147. for _, value := range paramslist {
  1148. if value == "ID" {
  1149. id := parammaps.Get("ID").ValueStr()
  1150. pastureid := parammaps.Get("pastureid").ValueStr()
  1151. 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
  1152. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1153. if err != nil {
  1154. logging.Error("PostRJSBData err: ", err)
  1155. msg := geterrmsg(err.Error())
  1156. appG.Response(http.StatusOK, e.ERROR, msg)
  1157. return
  1158. }
  1159. for _, item := range datalist {
  1160. id = item["id"]
  1161. }
  1162. s_params = append(s_params, id)
  1163. } else {
  1164. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1165. }
  1166. }
  1167. }
  1168. _, err = tx.SQL(sql2, s_params...).Execute()
  1169. if err != nil {
  1170. logging.Error("PostRJSBData2 err: ", err)
  1171. msg := geterrmsg(err.Error())
  1172. appG.Response(http.StatusOK, e.ERROR, msg)
  1173. return
  1174. }
  1175. s_params = make([]interface{}, 0)
  1176. paramslist = strings.Split(p3, ",")
  1177. if len(paramslist) > 0 && p3 != "" {
  1178. for _, value := range paramslist {
  1179. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1180. }
  1181. }
  1182. _, err = tx.SQL(sql3, s_params...).Execute()
  1183. if err != nil {
  1184. logging.Error("PostRJSBData3 err: ", err)
  1185. msg := geterrmsg(err.Error())
  1186. appG.Response(http.StatusOK, e.ERROR, msg)
  1187. return
  1188. }
  1189. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1190. }
  1191. func PostRJSBDatas(c *gin.Context) {
  1192. appG := app.Gin{C: c}
  1193. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1194. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1195. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1196. tx := restful.Engine.NewSession()
  1197. err := tx.Begin()
  1198. defer func() {
  1199. switch {
  1200. case err != nil:
  1201. if tx != nil {
  1202. tx.Rollback()
  1203. }
  1204. default:
  1205. if tx != nil {
  1206. err = tx.Commit()
  1207. }
  1208. }
  1209. if tx != nil {
  1210. tx.Close()
  1211. }
  1212. }()
  1213. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1214. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1215. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1216. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1217. for _, fsion := range fsions {
  1218. if !fsion.HasKey("parammaps") {
  1219. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1220. return
  1221. }
  1222. parammaps := fsion.Get("parammaps")
  1223. s_params := make([]interface{}, 0)
  1224. paramslist := strings.Split(p, ",")
  1225. if len(paramslist) > 0 && p != "" {
  1226. for _, value := range paramslist {
  1227. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1228. }
  1229. }
  1230. _, err = tx.SQL(sql, s_params...).Execute()
  1231. if err != nil {
  1232. logging.Error("PostRJSBData err: ", err)
  1233. msg := geterrmsg(err.Error())
  1234. appG.Response(http.StatusOK, e.ERROR, msg)
  1235. return
  1236. }
  1237. s_params = make([]interface{}, 0)
  1238. paramslist = strings.Split(p1, ",")
  1239. if len(paramslist) > 0 && p1 != "" {
  1240. for _, value := range paramslist {
  1241. // if value == "ID" {
  1242. // id := parammaps.Get("ID").ValueStr()
  1243. // pastureid := parammaps.Get("pastureid").ValueStr()
  1244. // 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
  1245. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1246. // if err != nil {
  1247. // logging.Error("PostRJSBData err: ", err)
  1248. // msg := geterrmsg(err.Error())
  1249. // appG.Response(http.StatusOK, e.ERROR, msg)
  1250. // return
  1251. // }
  1252. // for _, item := range datalist {
  1253. // id = item["id"]
  1254. // }
  1255. // s_params = append(s_params, id)
  1256. // } else {
  1257. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1258. // }
  1259. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1260. }
  1261. }
  1262. _, err = tx.SQL(sql1, s_params...).Execute()
  1263. if err != nil {
  1264. logging.Error("PostRJSBData1 err: ", err)
  1265. msg := geterrmsg(err.Error())
  1266. appG.Response(http.StatusOK, e.ERROR, msg)
  1267. return
  1268. }
  1269. s_params = make([]interface{}, 0)
  1270. paramslist = strings.Split(p2, ",")
  1271. if len(paramslist) > 0 && p2 != "" {
  1272. for _, value := range paramslist {
  1273. if value == "ID" {
  1274. id := parammaps.Get("ID").ValueStr()
  1275. pastureid := parammaps.Get("pastureid").ValueStr()
  1276. 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
  1277. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1278. if err != nil {
  1279. logging.Error("PostRJSBData err: ", err)
  1280. msg := geterrmsg(err.Error())
  1281. appG.Response(http.StatusOK, e.ERROR, msg)
  1282. return
  1283. }
  1284. for _, item := range datalist {
  1285. id = item["id"]
  1286. }
  1287. s_params = append(s_params, id)
  1288. } else {
  1289. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1290. }
  1291. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1292. }
  1293. }
  1294. _, err = tx.SQL(sql2, s_params...).Execute()
  1295. if err != nil {
  1296. logging.Error("PostRJSBData2 err: ", err)
  1297. msg := geterrmsg(err.Error())
  1298. appG.Response(http.StatusOK, e.ERROR, msg)
  1299. return
  1300. }
  1301. s_params = make([]interface{}, 0)
  1302. paramslist = strings.Split(p3, ",")
  1303. if len(paramslist) > 0 && p3 != "" {
  1304. for _, value := range paramslist {
  1305. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1306. }
  1307. }
  1308. _, err = tx.SQL(sql3, s_params...).Execute()
  1309. if err != nil {
  1310. logging.Error("PostRJSBData3 err: ", err)
  1311. msg := geterrmsg(err.Error())
  1312. appG.Response(http.StatusOK, e.ERROR, msg)
  1313. return
  1314. }
  1315. }
  1316. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1317. }
  1318. // @Summary 根据APISQL表中SQL执行得到数据集
  1319. // @Tags ExecDataByConfig
  1320. // @Accept json
  1321. // @Produce json
  1322. // @Param sqlname query string true "sqlname"
  1323. // @Param offset query int true "offset"
  1324. // @Param pagecount query int true "pagecount"
  1325. // @Param returntype query string true "returntype"
  1326. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1327. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1328. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1329. // @Router /data/PostDataByName [POST]
  1330. func ExecDataByConfig(c *gin.Context) {
  1331. appG := app.Gin{C: c}
  1332. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1333. tempval_ := make(map[string]interface{})
  1334. tempCommon := make(map[string]interface{})
  1335. tempval := make([]map[string]interface{}, 0)
  1336. err := json.Unmarshal(dataByte, &tempval_)
  1337. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1338. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1339. if err != nil {
  1340. } else {
  1341. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1342. tempCommon = v
  1343. }
  1344. if v, ok := tempval_["data"].([]interface{}); ok {
  1345. for _, Tvalue := range v {
  1346. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1347. tempval = append(tempval, v1)
  1348. }
  1349. }
  1350. }
  1351. tx := restful.Engine.NewSession()
  1352. err := tx.Begin()
  1353. if err != nil {
  1354. logging.Error("tx.Begin 事务启动失败__error:", err)
  1355. }
  1356. defer func() {
  1357. switch {
  1358. case err != nil:
  1359. if tx != nil {
  1360. tx.Rollback()
  1361. }
  1362. default:
  1363. if tx != nil {
  1364. err = tx.Commit()
  1365. }
  1366. }
  1367. if tx != nil {
  1368. tx.Close()
  1369. }
  1370. }()
  1371. if err == nil {
  1372. if tempv, exists := c.Get("jwt_username"); exists {
  1373. tempCommon["jwt_username"] = tempv.(string)
  1374. }
  1375. for _, paramvalue := range tempval {
  1376. fmt.Println(paramvalue["name"])
  1377. if paramvalue["name"].(string) == "updateBigFP" {
  1378. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1379. if err != nil {
  1380. msg := geterrmsg(err.Error())
  1381. appG.Response(http.StatusOK, e.ERROR, msg)
  1382. return
  1383. }
  1384. }
  1385. }
  1386. for _, paramvalue := range tempval {
  1387. if _, ok := paramvalue["resultname"]; !ok {
  1388. paramvalue["resultname"] = paramvalue["name"]
  1389. }
  1390. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1391. if err != nil {
  1392. logging.Error("ExecDataParam error:", err)
  1393. break
  1394. }
  1395. }
  1396. if err == nil {
  1397. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1398. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1399. } else {
  1400. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1401. }
  1402. } else {
  1403. msg := geterrmsg(err.Error())
  1404. appG.Response(http.StatusOK, e.ERROR, msg)
  1405. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1406. }
  1407. }
  1408. }
  1409. if err != nil {
  1410. msg := geterrmsg(err.Error())
  1411. appG.Response(http.StatusOK, e.ERROR, msg)
  1412. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1413. }
  1414. }
  1415. func interfacetostring(val interface{}) string {
  1416. switch val.(type) {
  1417. case string:
  1418. ss := val.(string)
  1419. return ss
  1420. break
  1421. case int:
  1422. ss := val.(int)
  1423. return strconv.Itoa(ss)
  1424. break
  1425. case int64:
  1426. ss := val.(int64)
  1427. return strconv.FormatInt(ss, 10)
  1428. break
  1429. case float64:
  1430. ss := val.(float64)
  1431. return strconv.FormatFloat(ss, 'E', -1, 32)
  1432. break
  1433. }
  1434. return ""
  1435. }
  1436. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1437. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1438. tempstrb := strings.IndexAny(valuestring, "@")
  1439. tempstre := strings.IndexAny(valuestring, ".")
  1440. if tempstrb > -1 && tempstre > -1 {
  1441. for _, ParamMapList := range ParamMap {
  1442. if v, ok := ParamMapList["resultname"]; ok {
  1443. if v == valuestring[tempstrb+1:tempstre] {
  1444. if v1, ok := ParamMapList["resultmaps"]; ok {
  1445. if newA, ok := v1.([]map[string]interface{}); ok {
  1446. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1447. } else if newA, ok := v1.(map[string]interface{}); ok {
  1448. return interfacetostring(newA[valuestring[tempstre+1:]])
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. } else {
  1455. return valuestring
  1456. }
  1457. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1458. return strconv.FormatInt(int64(valuestring), 10)
  1459. }
  1460. return ""
  1461. }
  1462. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1463. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1464. tempstrb := strings.IndexAny(valuestring, "@")
  1465. tempstre := strings.IndexAny(valuestring, ".")
  1466. if tempstrb > -1 && tempstre > -1 {
  1467. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1468. if s, ok := v.(string); ok {
  1469. return s
  1470. } else if s, ok := v.(float64); ok {
  1471. return strconv.FormatFloat(s, 'f', -1, 64)
  1472. // return strconv.FormatInt(int64(s), 10)
  1473. }
  1474. }
  1475. }
  1476. }
  1477. return ""
  1478. }
  1479. 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) {
  1480. sqlname := fasion["name"].(string)
  1481. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1482. if v, ok := fasion["type"]; ok {
  1483. sqltype = v.(string)
  1484. }
  1485. sql := ""
  1486. p := ""
  1487. s_params := make([]interface{}, 0)
  1488. if sqltype != "" {
  1489. sql, p = restful.GetSqlByName(sqlname, tx)
  1490. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1491. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1492. paramslist := strings.Split(p, ",")
  1493. if len(paramslist) > 0 && p != "" {
  1494. for _, value := range paramslist {
  1495. ss := ""
  1496. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1497. ids, err := setting.SnowIds.NextId()
  1498. if err != nil {
  1499. ids = time.Now().UnixNano()
  1500. logging.Info("create SnowIds err", err)
  1501. }
  1502. s_params = append(s_params, ids)
  1503. } else {
  1504. if ss == "" && CommonParamMap != nil {
  1505. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1506. ss = valuestring
  1507. tempstrb := strings.IndexAny(valuestring, "@")
  1508. tempstre := strings.IndexAny(valuestring, ".")
  1509. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1510. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1511. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1512. }
  1513. } else {
  1514. ss = ""
  1515. }
  1516. }
  1517. }
  1518. if ss == "" && ParentParamMap != nil {
  1519. ss = getParamValue_(v, value, ParentParamMap)
  1520. }
  1521. if ss == "" && sameParamMap != nil {
  1522. ss = getParamValue(v, value, sameParamMap)
  1523. }
  1524. if ss == "" && ParamMap != nil {
  1525. ss = getParamValue(v, value, ParamMap)
  1526. }
  1527. s_params = append(s_params, ss)
  1528. }
  1529. }
  1530. }
  1531. }
  1532. }
  1533. if sql == "" {
  1534. sqltype = ""
  1535. }
  1536. if sqltype == "s1" {
  1537. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1538. if v, ok := tempValParam.(map[string]interface{}); ok {
  1539. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1540. }
  1541. if err != nil {
  1542. return nil, err
  1543. }
  1544. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1545. if err != nil {
  1546. return nil, err
  1547. }
  1548. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1549. } else if sqltype == "sm" {
  1550. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1551. if v, ok := tempValParam.(map[string]interface{}); ok {
  1552. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1553. } else {
  1554. }
  1555. if err != nil {
  1556. return nil, err
  1557. }
  1558. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1559. if err != nil {
  1560. return nil, err
  1561. }
  1562. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1563. } else if sqltype == "v" {
  1564. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1565. if v, ok := tempValParam.(map[string]interface{}); ok {
  1566. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1567. } else {
  1568. }
  1569. if err != nil {
  1570. return nil, err
  1571. }
  1572. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1573. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1574. }
  1575. } else if sqltype == "e" {
  1576. tempVal_arrary := make([]map[string]interface{}, 0)
  1577. tempVal_map := make(map[string]interface{})
  1578. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1579. if err == nil {
  1580. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1581. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1582. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1583. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1584. return tempVal_arrary, err
  1585. }
  1586. return nil, err
  1587. } else {
  1588. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1589. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1590. if err != nil {
  1591. return nil, err
  1592. }
  1593. return nil, err
  1594. }
  1595. }
  1596. return nil, nil
  1597. }
  1598. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1599. var err error
  1600. subarray, ok := fasion["children"]
  1601. if ok {
  1602. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1603. tempVal_arrary := make([]map[string]interface{}, 0)
  1604. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1605. tempVal_ := make(map[string]interface{})
  1606. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1607. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1608. } else {
  1609. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1610. }
  1611. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1612. if err != nil {
  1613. return err
  1614. }
  1615. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1616. }
  1617. v.(map[string]interface{})["children"] = tempVal_arrary
  1618. }
  1619. }
  1620. return nil
  1621. }
  1622. // @Summary 删除图片
  1623. // @Tags RemovePicByName
  1624. // @Accept json
  1625. // @Produce json
  1626. // @Param sqlname query string true "sqlname"
  1627. // @Param offset query int true "offset"
  1628. // @Param pagecount query int true "pagecount"
  1629. // @Param returntype query string true "returntype"
  1630. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1631. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1632. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1633. // @Router /data/PostDataByName [POST]
  1634. func RemovePicByName(c *gin.Context) {
  1635. logging.Info("RemovePicByName ", c.Keys)
  1636. appG := app.Gin{C: c}
  1637. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1638. fsion := gofasion.NewFasion(string(dataByte))
  1639. sqlnamestr := fsion.Get("name").ValueStr()
  1640. picname := fsion.Get("picname").ValueStr()
  1641. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1642. params := fsion.Get("params").Array()
  1643. s_params := make([]interface{}, 0)
  1644. for _, v_params := range params {
  1645. s_params = append(s_params, v_params.ValueStr())
  1646. }
  1647. if sql != "" {
  1648. queryData, err := execDataBySql(sql, s_params)
  1649. if picname != "" {
  1650. // Destination
  1651. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1652. err := os.Remove(distPath) //删除文件test.txt
  1653. if err != nil {
  1654. //如果删除失败则输出 file remove Error!
  1655. fmt.Println("file remove Error!")
  1656. //输出错误详细信息
  1657. fmt.Printf("%s", err)
  1658. } else {
  1659. //如果删除成功则输出 file remove OK!
  1660. fmt.Print("file remove OK!")
  1661. }
  1662. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, 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. }
  1674. if err != nil {
  1675. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1676. } else {
  1677. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1678. }
  1679. } else {
  1680. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1681. }
  1682. }
  1683. // @Summary 删除文件
  1684. // @Tags RemoveFileByName
  1685. // @Accept json
  1686. // @Produce json
  1687. // @Param sqlname query string true "sqlname"
  1688. // @Param offset query int true "offset"
  1689. // @Param pagecount query int true "pagecount"
  1690. // @Param returntype query string true "returntype"
  1691. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1692. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1693. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1694. // @Router /data/PostDataByName [POST]
  1695. func RemoveFileByName(c *gin.Context) {
  1696. appG := app.Gin{C: c}
  1697. id := c.Param("id")
  1698. logging.Info("DownloadFile ", c.Keys, id)
  1699. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1700. if eqdoc == nil {
  1701. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1702. return
  1703. }
  1704. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1705. err = os.Remove(distPath) //删除文件test.txt
  1706. if err != nil {
  1707. //如果删除失败则输出 file remove Error!
  1708. fmt.Println("file remove Error!")
  1709. //输出错误详细信息
  1710. fmt.Printf("%s", err)
  1711. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1712. return
  1713. }
  1714. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1715. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1716. }
  1717. // @Summary 根据APISQL表中SQL执行得到数据集
  1718. // @Tags PostDataByName
  1719. // @Accept json
  1720. // @Produce json
  1721. // @Param sqlname query string true "sqlname"
  1722. // @Param offset query int true "offset"
  1723. // @Param pagecount query int true "pagecount"
  1724. // @Param returntype query string true "returntype"
  1725. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1726. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1727. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1728. // @Router /data/PostDataByName [POST]
  1729. func UpdateDataRelation(c *gin.Context) {
  1730. appG := app.Gin{C: c}
  1731. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1732. fsion := gofasion.NewFasion(string(dataByte))
  1733. tablename := fsion.Get("name").ValueStr()
  1734. dataname := fsion.Get("dataname").ValueStr()
  1735. datavalue := fsion.Get("datavalue").ValueStr()
  1736. valuename := fsion.Get("valuename").ValueStr()
  1737. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1738. values := fsion.Get("values").Array()
  1739. tx := restful.Engine.NewSession()
  1740. err := tx.Begin()
  1741. defer func() {
  1742. switch {
  1743. case err != nil:
  1744. if tx != nil {
  1745. tx.Rollback()
  1746. }
  1747. default:
  1748. if tx != nil {
  1749. err = tx.Commit()
  1750. }
  1751. }
  1752. if tx != nil {
  1753. tx.Close()
  1754. }
  1755. }()
  1756. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1757. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1758. d_params := make([]interface{}, 4)
  1759. d_params[0] = datavalue
  1760. s_params := ""
  1761. for _, v_values := range values {
  1762. d_params[1] = v_values.ValueStr()
  1763. if s_params == "" {
  1764. s_params = v_values.ValueStr()
  1765. } else {
  1766. s_params = s_params + "," + v_values.ValueStr()
  1767. }
  1768. d_params[2] = d_params[1]
  1769. d_params[3] = d_params[0]
  1770. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1771. if err != nil {
  1772. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1773. break
  1774. }
  1775. }
  1776. if s_params != "" {
  1777. deleteSqlstr := "delete from " + tablename + " " +
  1778. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1779. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1780. if err != nil {
  1781. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1782. } else if err == nil {
  1783. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1784. }
  1785. } else {
  1786. deleteSqlstr := "delete from " + tablename + " " +
  1787. " where " + dataname + " = " + datavalue
  1788. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1789. if err != nil {
  1790. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1791. } else if err == nil {
  1792. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1793. }
  1794. }
  1795. }
  1796. // @Summary 根据APISQL表中SQL执行得到数据集
  1797. // @Tags PostDatasByName
  1798. // @Accept json
  1799. // @Produce json
  1800. // @Param sqlname query string true "sqlname"
  1801. // @Param offset query int true "offset"
  1802. // @Param pagecount query int true "pagecount"
  1803. // @Param returntype query string true "returntype"
  1804. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1805. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1806. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1807. // @Router /data/PostDatasByName [POST]
  1808. func PostDataByNames(c *gin.Context) {
  1809. appG := app.Gin{C: c}
  1810. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1811. fsion := gofasion.NewFasion(string(dataByte))
  1812. sqlParams := fsion.Get("array").Array()
  1813. queryData := make(map[string]interface{})
  1814. for _, v := range sqlParams {
  1815. fsion2 := gofasion.NewFasion(v.Json())
  1816. ss := fsion2.Get("name")
  1817. aa := fsion2.Get("params")
  1818. fmt.Println(ss, aa)
  1819. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1820. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1821. if sql == "" {
  1822. errorm := make(map[string]interface{})
  1823. errorm["code"] = e.ERROR
  1824. errorm["message"] = "sql没有找到"
  1825. errorm["param"] = ""
  1826. queryData[fsion2.Get("name").ValueStr()] = errorm
  1827. continue
  1828. } else if sql != "" {
  1829. s_params := make([]interface{}, 0)
  1830. if fsion2.HasKey("parammaps") {
  1831. parammaps := fsion2.Get("parammaps")
  1832. paramslist := strings.Split(p, ",")
  1833. if len(paramslist) > 0 && p != "" {
  1834. for _, value := range paramslist {
  1835. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1836. if tempv, exists := c.Get("jwt_username"); exists {
  1837. s_params = append(s_params, tempv.(string))
  1838. } else {
  1839. s_params = append(s_params, "")
  1840. }
  1841. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1842. ids, err := setting.SnowIds.NextId()
  1843. if err != nil {
  1844. ids = time.Now().UnixNano()
  1845. logging.Info("create SnowIds err", err)
  1846. }
  1847. s_params = append(s_params, ids)
  1848. } else {
  1849. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1850. }
  1851. }
  1852. }
  1853. } else if fsion2.HasKey("params") {
  1854. params := fsion2.Get("params").Array()
  1855. //ids,err := setting.SnowIds.NextId()
  1856. //if err !=nil{
  1857. // ids = time.Now().UnixNano()
  1858. // logging.Info("create SnowIds err",err)
  1859. //}
  1860. //s_params = append(s_params, ids)
  1861. for _, v_params := range params {
  1862. s_params = append(s_params, v_params.ValueStr())
  1863. }
  1864. }
  1865. _, err := execDataBySql(sql, s_params)
  1866. if err != nil {
  1867. logging.Error("PostDataByName err: ", err)
  1868. errorm := make(map[string]interface{})
  1869. errorm["code"] = e.ERROR
  1870. errorm["message"] = err.Error()
  1871. errorm["param"] = s_params
  1872. queryData[fsion2.Get("name").ValueStr()] = errorm
  1873. continue
  1874. } else {
  1875. errorm := make(map[string]interface{})
  1876. errorm["code"] = e.SUCCESS
  1877. errorm["message"] = "success"
  1878. queryData[fsion2.Get("name").ValueStr()] = errorm
  1879. continue
  1880. }
  1881. } else {
  1882. errorm := make(map[string]interface{})
  1883. errorm["code"] = e.ERROR
  1884. errorm["message"] = "NO SQL"
  1885. errorm["param"] = ""
  1886. queryData[fsion2.Get("name").ValueStr()] = errorm
  1887. }
  1888. }
  1889. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1890. }
  1891. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1892. if offset > 0 {
  1893. offset = offset - 1
  1894. }
  1895. //if pagecount == 0 {
  1896. // pagecount = setting.AppSetting.PageSize
  1897. //}else if pagecount>setting.AppSetting.PageSize{
  1898. // pagecount = setting.AppSetting.PageSize
  1899. //}
  1900. if returntype == "list" {
  1901. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1902. return queryData, err
  1903. } else if returntype == "listlist" {
  1904. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1905. return queryData, err
  1906. } else {
  1907. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1908. return queryData, err
  1909. }
  1910. }
  1911. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1912. if offset > 0 {
  1913. offset = offset - 1
  1914. }
  1915. //if pagecount == 0 {
  1916. // pagecount = setting.AppSetting.PageSize
  1917. //}else if pagecount>setting.AppSetting.PageSize{
  1918. // pagecount = setting.AppSetting.PageSize
  1919. //}
  1920. if returntype == "list" {
  1921. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1922. return queryData, err
  1923. } else if returntype == "listlist" {
  1924. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1925. return queryData, err
  1926. } else {
  1927. fmt.Println(params)
  1928. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1929. return queryData, err
  1930. }
  1931. }
  1932. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1933. paramslist := strings.Split(Params, ",")
  1934. s_params := make([]interface{}, 0)
  1935. if isList {
  1936. for _, v_params := range thisParams["params"].([]interface{}) {
  1937. s_params = append(s_params, v_params)
  1938. }
  1939. } else {
  1940. paramslist := strings.Split(Params, ",")
  1941. if len(paramslist) > 0 && Params != "" {
  1942. for _, value := range paramslist {
  1943. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1944. }
  1945. }
  1946. }
  1947. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1948. for _, queryData_ := range queryData {
  1949. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1950. if isList {
  1951. if queryData_[idname] != nil {
  1952. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1953. }
  1954. } else {
  1955. if queryData_[idname] != nil {
  1956. thisParams[idname] = queryData_[idname].(interface{})
  1957. }
  1958. if len(paramslist) > 0 && Params != "" {
  1959. s_params = make([]interface{}, 0)
  1960. for _, value := range paramslist {
  1961. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1962. }
  1963. }
  1964. }
  1965. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1966. } else {
  1967. }
  1968. }
  1969. return queryData, err
  1970. }
  1971. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1972. queryData, err := restful.ExecQuery(sqlstr, params)
  1973. return queryData, err
  1974. }
  1975. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1976. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1977. return queryData, err
  1978. }
  1979. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1980. queryData, err := restful.ExecQuery(sqlstr, params)
  1981. return queryData, err
  1982. }
  1983. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1984. // @Tags ImportExcel
  1985. // @Accept json
  1986. // @Produce json
  1987. // @Param file query string true "文件名"
  1988. // @Param name header string true "执行sql的名字"
  1989. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1990. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1991. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1992. // @Router /data/ImportExcel [POST]
  1993. func ImportExcel(c *gin.Context) {
  1994. appG := app.Gin{C: c}
  1995. inputdata := ""
  1996. c.Request.ParseForm()
  1997. params := c.Request.Form
  1998. file, _, err := c.Request.FormFile("file")
  1999. if err != nil {
  2000. appG.Response(http.StatusOK, e.ERROR, err)
  2001. return
  2002. }
  2003. sqlnamestrs := params.Get("name")
  2004. sheetname := params.Get("sheetname")
  2005. pastureid := params.Get("pastureid")
  2006. //importParams := params.Get("importParams")
  2007. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2008. // 必输项参数 (字符串格式 "field1,field2,field3")
  2009. requiredParams := params.Get("requiredParams")
  2010. // 日期参数
  2011. dateParams := params.Get("dateParams")
  2012. // 数字参数
  2013. numParams := params.Get("numParams")
  2014. //将字符串分割开
  2015. dateParamslist := strings.Split(dateParams, ",")
  2016. requiredParamslist := strings.Split(requiredParams, ",")
  2017. numParamslist := strings.Split(numParams, ",")
  2018. queryData := make([]interface{}, 0)
  2019. sqlslist := strings.Split(sqlnamestrs, ",")
  2020. xlsx1, err := excelize.OpenReader(file)
  2021. if err != nil {
  2022. fmt.Println(err)
  2023. return
  2024. }
  2025. ok := 0
  2026. error := 0
  2027. isdone := true
  2028. rows := xlsx1.GetRows(sheetname)
  2029. // 限制10000条,多余的截取掉
  2030. if len(rows) > 10000 {
  2031. rows = rows[:10000]
  2032. }
  2033. for i, row := range rows {
  2034. if i > 0 {
  2035. entry := make(map[string]interface{})
  2036. outentry := make(map[string]interface{})
  2037. for j, colCell := range rows[0] {
  2038. for k, colCell1 := range row {
  2039. if j == k {
  2040. outentry[colCell] = colCell1
  2041. entry[colCell] = colCell1
  2042. }
  2043. }
  2044. }
  2045. inputdata = ""
  2046. a := ""
  2047. fmt.Println(outentry, entry)
  2048. //校验日期格式
  2049. for _, v := range dateParamslist {
  2050. if v == "" {
  2051. continue
  2052. }
  2053. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2054. dtime, err := TransfTime(d.(string))
  2055. if err != nil {
  2056. a = strings.Trim(v, " ")
  2057. break
  2058. }
  2059. outentry[strings.Trim(v, " ")] = dtime
  2060. }
  2061. }
  2062. if a != "" {
  2063. outentry["error_msg"] = a + " 格式错误"
  2064. error++
  2065. queryData = append(queryData, outentry)
  2066. continue
  2067. }
  2068. a = ""
  2069. //校验必填格式
  2070. for _, v := range requiredParamslist {
  2071. if v == "" {
  2072. continue
  2073. }
  2074. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2075. a = strings.Trim(v, " ")
  2076. break
  2077. }
  2078. }
  2079. if a != "" {
  2080. outentry["error_msg"] = a + " 未填或格式错误"
  2081. error++
  2082. queryData = append(queryData, outentry)
  2083. continue
  2084. }
  2085. a = ""
  2086. //校验数字格式
  2087. for _, v := range numParamslist {
  2088. if v == "" {
  2089. continue
  2090. }
  2091. d, ok := outentry[strings.Trim(v, " ")]
  2092. if !ok || d == "" {
  2093. outentry[strings.Trim(v, " ")] = 0
  2094. } else {
  2095. var fl float64
  2096. switch d.(type) {
  2097. case string:
  2098. fl, err = strconv.ParseFloat(d.(string), 64)
  2099. }
  2100. if err != nil || fl < 0 {
  2101. a = strings.Trim(v, " ")
  2102. break
  2103. }
  2104. }
  2105. }
  2106. if a != "" {
  2107. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2108. error++
  2109. queryData = append(queryData, outentry)
  2110. continue
  2111. }
  2112. tx := restful.Engine.NewSession()
  2113. err := tx.Begin()
  2114. for _, sqlnamestr := range sqlslist {
  2115. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2116. paramslist := strings.Split(paramslists, ",")
  2117. if len(paramslist) > 0 {
  2118. s_params := make([]interface{}, 0)
  2119. for _, value := range paramslist {
  2120. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2121. if tempv, exists := c.Get("jwt_username"); exists {
  2122. s_params = append(s_params, tempv.(string))
  2123. } else {
  2124. s_params = append(s_params, "")
  2125. }
  2126. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2127. s_params = append(s_params, pastureid)
  2128. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2129. ids, err := setting.SnowIds.NextId()
  2130. if err != nil {
  2131. ids = time.Now().UnixNano()
  2132. logging.Info("create SnowIds err", err)
  2133. }
  2134. s_params = append(s_params, ids)
  2135. } else {
  2136. if outentry[strings.Trim(value, " ")] == nil {
  2137. s_params = append(s_params, "")
  2138. } else {
  2139. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2140. }
  2141. }
  2142. }
  2143. outentry["input"] = inputdata
  2144. fmt.Println(sql, s_params)
  2145. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2146. if err != nil {
  2147. if tx != nil {
  2148. tx.Rollback()
  2149. }
  2150. if tx != nil {
  2151. tx.Close()
  2152. }
  2153. msg := geterrmsg(err.Error())
  2154. outentry["error_msg"] = msg
  2155. error++
  2156. queryData = append(queryData, outentry)
  2157. isdone = true
  2158. break
  2159. } else {
  2160. if len(returnmsgmap1) > 0 {
  2161. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2162. if tx != nil {
  2163. tx.Rollback()
  2164. }
  2165. if tx != nil {
  2166. tx.Close()
  2167. }
  2168. msg := geterrmsg(va.(string))
  2169. outentry["error_msg"] = msg
  2170. error++
  2171. queryData = append(queryData, outentry)
  2172. isdone = true
  2173. break
  2174. }
  2175. }
  2176. isdone = false
  2177. }
  2178. }
  2179. }
  2180. switch {
  2181. case err != nil:
  2182. if tx != nil {
  2183. tx.Rollback()
  2184. }
  2185. default:
  2186. if tx != nil {
  2187. err = tx.Commit()
  2188. }
  2189. }
  2190. if tx != nil {
  2191. tx.Close()
  2192. }
  2193. }
  2194. if !isdone {
  2195. ok++
  2196. isdone = true
  2197. }
  2198. }
  2199. data := make(map[string]interface{})
  2200. data["result"] = queryData
  2201. data["success"] = ok
  2202. data["err_count"] = error
  2203. appG.Response(http.StatusOK, e.SUCCESS, data)
  2204. }
  2205. func TransfTime(timestr string) (string, error) {
  2206. if timestr == "" {
  2207. return time.Now().Format("2006-01-02"), nil
  2208. }
  2209. days, err := strconv.Atoi(timestr)
  2210. if err != nil {
  2211. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2212. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2213. }
  2214. _, err := time.Parse("2006-01-02", timestr)
  2215. if err != nil {
  2216. t, err := time.Parse("2006/01/02", timestr)
  2217. if err != nil {
  2218. t, err := time.Parse("2006.01.02", timestr)
  2219. if err != nil {
  2220. return "", err
  2221. } else {
  2222. return t.Format("2006-01-02"), nil
  2223. }
  2224. } else {
  2225. return t.Format("2006-01-02"), nil
  2226. }
  2227. } else {
  2228. return timestr, nil
  2229. }
  2230. }
  2231. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2232. times = times.AddDate(0, 0, days)
  2233. return times.Format("2006-01-02"), nil
  2234. }
  2235. func Createchart(c *gin.Context) {
  2236. appG := app.Gin{C: c}
  2237. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2238. fsion := gofasion.NewFasion(string(dataByte))
  2239. chart_name := fsion.Get("chart_name").ValueStr()
  2240. desc := fsion.Get("desc").ValueStr()
  2241. pastureid := fsion.Get("pastureid").ValueStr()
  2242. source_id := fsion.Get("source_id").ValueStr()
  2243. emp := fsion.Get("emp").ValueStr()
  2244. content := fsion.Get("content").Json()
  2245. var mapResult map[string]interface{}
  2246. err1 := json.Unmarshal([]byte(content), &mapResult)
  2247. if err1 != nil {
  2248. fmt.Println("JsonToMapDemo err: ", err1)
  2249. }
  2250. tx := restful.Engine.NewSession()
  2251. err := tx.Begin()
  2252. defer func() {
  2253. switch {
  2254. case err != nil:
  2255. logging.Error("tx.Begin 事务启动失败__error:", err)
  2256. if tx != nil {
  2257. tx.Rollback()
  2258. }
  2259. default:
  2260. if tx != nil {
  2261. err = tx.Commit()
  2262. }
  2263. }
  2264. if tx != nil {
  2265. tx.Close()
  2266. }
  2267. }()
  2268. ids, err := setting.SnowIds.NextId()
  2269. if err != nil {
  2270. ids = time.Now().UnixNano()
  2271. logging.Info("create SnowIds err", err)
  2272. }
  2273. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2274. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2275. if err != nil {
  2276. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2277. } else {
  2278. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2279. }
  2280. }
  2281. func Updatedashboard(c *gin.Context) {
  2282. appG := app.Gin{C: c}
  2283. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2284. fsion := gofasion.NewFasion(string(dataByte))
  2285. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2286. pastureid := fsion.Get("pastureid").ValueStr()
  2287. content := fsion.Get("content").Json()
  2288. var mapResult map[string]interface{}
  2289. err1 := json.Unmarshal([]byte(content), &mapResult)
  2290. if err1 != nil {
  2291. fmt.Println("JsonToMapDemo err: ", err1)
  2292. }
  2293. layout := mapResult["layout"]
  2294. tx := restful.Engine.NewSession()
  2295. err := tx.Begin()
  2296. defer func() {
  2297. switch {
  2298. case err != nil:
  2299. logging.Error("tx.Begin 事务启动失败__error:", err)
  2300. if tx != nil {
  2301. tx.Rollback()
  2302. }
  2303. default:
  2304. if tx != nil {
  2305. err = tx.Commit()
  2306. }
  2307. }
  2308. if tx != nil {
  2309. tx.Close()
  2310. }
  2311. }()
  2312. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2313. if err != nil {
  2314. println("2", err.Error())
  2315. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2316. } else {
  2317. if exec != nil {
  2318. if exec[0]["content"] == nil {
  2319. mapR := make(map[string]interface{})
  2320. mapR["layout"] = layout
  2321. mjson, _ := json.Marshal(mapR)
  2322. mString := string(mjson)
  2323. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2324. if err3 != nil {
  2325. println("3", err3.Error())
  2326. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2327. } else {
  2328. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2329. }
  2330. } else {
  2331. var mapR map[string]interface{}
  2332. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2333. if err1 != nil {
  2334. fmt.Println("JsonToMapDemo err: ", err2)
  2335. }
  2336. mapR["layout"] = layout
  2337. mjson, _ := json.Marshal(mapR)
  2338. mString := string(mjson)
  2339. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2340. if err3 != nil {
  2341. println("3", err3.Error())
  2342. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2343. } else {
  2344. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2345. }
  2346. }
  2347. } else {
  2348. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2349. }
  2350. }
  2351. }
  2352. func ExecSQL(c *gin.Context) {
  2353. appG := app.Gin{C: c}
  2354. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2355. fsion := gofasion.NewFasion(string(dataByte))
  2356. content := fsion.Get("content").Json()
  2357. pastureid := fsion.Get("pastureid").ValueStr()
  2358. var mapResult map[string]interface{}
  2359. err1 := json.Unmarshal([]byte(content), &mapResult)
  2360. if err1 != nil {
  2361. fmt.Println("JsonToMapDemo err: ", err1)
  2362. }
  2363. sqlstr := "select "
  2364. groupstr := " GROUP BY "
  2365. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2366. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2367. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2368. }
  2369. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2370. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2371. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2372. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2373. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2374. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2375. sqlstr = sqlstr + tem + ","
  2376. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2377. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2378. sqlstr = sqlstr + tem + ","
  2379. } else {
  2380. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2381. sqlstr = sqlstr + tem + ","
  2382. }
  2383. }
  2384. if _, ok := mapResult["selectedCalcul2"]; ok {
  2385. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2386. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2387. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2388. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2389. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2390. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2391. sqlstr = sqlstr + tem + ","
  2392. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2393. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2394. sqlstr = sqlstr + tem + ","
  2395. } else {
  2396. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2397. sqlstr = sqlstr + tem + ","
  2398. }
  2399. }
  2400. }
  2401. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2402. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2403. sqlstr = sqlstr + " where pastureid=" + pastureid
  2404. if len(mapResult["filters"].([]interface{})) > 0 {
  2405. sqlstr = sqlstr + " and "
  2406. }
  2407. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2408. for _, value := range mapResult["filters"].([]interface{}) {
  2409. switch value.(map[string]interface{})["filterOperator"].(string) {
  2410. case ">", "=", "<", ">=", "<=", "!=", "like":
  2411. 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 "
  2412. case "IN":
  2413. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2414. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2415. sqlstr = sqlstr + value1.(string) + ","
  2416. }
  2417. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2418. sqlstr = sqlstr + ")" + " AND "
  2419. case "BETWEEN":
  2420. 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 "
  2421. }
  2422. }
  2423. if len(mapResult["filters"].([]interface{})) > 0 {
  2424. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2425. }
  2426. //
  2427. groupstr = groupstr[0 : len(groupstr)-1]
  2428. sqlstr = sqlstr + groupstr + " "
  2429. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2430. sqlstr = sqlstr + " order by "
  2431. }
  2432. //
  2433. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2434. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2435. sqlstr = sqlstr + value.(string) + " "
  2436. } else {
  2437. sqlstr = sqlstr + value.(string) + ","
  2438. }
  2439. }
  2440. //
  2441. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2442. tx := restful.Engine.NewSession()
  2443. err := tx.Begin()
  2444. defer func() {
  2445. switch {
  2446. case err != nil:
  2447. logging.Error("tx.Begin 事务启动失败__error:", err)
  2448. if tx != nil {
  2449. tx.Rollback()
  2450. }
  2451. default:
  2452. if tx != nil {
  2453. err = tx.Commit()
  2454. }
  2455. }
  2456. if tx != nil {
  2457. tx.Close()
  2458. }
  2459. }()
  2460. exec, err := tx.SQL(sqlstr).Query().List()
  2461. if err != nil {
  2462. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2463. } else {
  2464. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2465. }
  2466. }
  2467. func Dashboards(c *gin.Context) {
  2468. appG := app.Gin{C: c}
  2469. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2470. fsion := gofasion.NewFasion(string(dataByte))
  2471. sqlnamestr := fsion.Get("name").ValueStr()
  2472. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2473. offset := fsion.Get("offset").ValueDefaultInt(0)
  2474. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2475. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2476. month := fsion.Get("month").ValueDefaultStr("map")
  2477. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2478. tx := restful.Engine.NewSession()
  2479. err := tx.Begin()
  2480. defer func() {
  2481. switch {
  2482. case err != nil:
  2483. if tx != nil {
  2484. tx.Rollback()
  2485. }
  2486. default:
  2487. if tx != nil {
  2488. err = tx.Commit()
  2489. }
  2490. }
  2491. if tx != nil {
  2492. tx.Close()
  2493. }
  2494. }()
  2495. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2496. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2497. if sql != "" {
  2498. s_params := make([]interface{}, 0)
  2499. if fsion.HasKey("parammaps") {
  2500. parammaps := fsion.Get("parammaps")
  2501. paramslist := strings.Split(p, ",")
  2502. if len(paramslist) > 0 && p != "" {
  2503. for _, value := range paramslist {
  2504. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2505. if tempv, exists := c.Get("jwt_username"); exists {
  2506. s_params = append(s_params, tempv.(string))
  2507. } else {
  2508. s_params = append(s_params, "")
  2509. }
  2510. } else {
  2511. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2512. }
  2513. }
  2514. }
  2515. }
  2516. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2517. if err != nil {
  2518. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2519. } else {
  2520. //paramslist1 := strings.Split(p1, ",")
  2521. dids := make([]interface{}, 0)
  2522. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2523. var mapResult map[string]interface{}
  2524. dids = append(dids, value["dashboard_id"])
  2525. if value["content"] != nil {
  2526. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2527. if err1 != nil {
  2528. println("JsonToMapDemo1 err: ", err1)
  2529. }
  2530. temap := make(map[string]interface{})
  2531. tem := mapResult["layout"].([]interface{})
  2532. if v, ok := value["chartids"]; ok {
  2533. chartids := strings.Split(v.(string), ",")
  2534. for _, va := range chartids {
  2535. a := false
  2536. for _, v2 := range tem {
  2537. if v2.(map[string]interface{})["id"].(string) == va {
  2538. a = true
  2539. //println("va1======",va)
  2540. }
  2541. }
  2542. if !a {
  2543. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2544. va + "\",\"id\":\"" + va +
  2545. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2546. var mapTem map[string]interface{}
  2547. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2548. if err1 != nil {
  2549. println("JsonToMapDemo err: ", err1)
  2550. }
  2551. tem = append(tem, mapTem)
  2552. }
  2553. }
  2554. temap["layout"] = tem
  2555. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2556. }
  2557. } else {
  2558. temap := make(map[string]interface{})
  2559. tem := make([]interface{}, 0)
  2560. if v, ok := value["chartids"]; ok {
  2561. chartids := strings.Split(v.(string), ",")
  2562. for _, va := range chartids {
  2563. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2564. va + "\",\"id\":\"" + va +
  2565. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2566. var mapTem map[string]interface{}
  2567. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2568. if err1 != nil {
  2569. println("JsonToMapDemo err: ", err1)
  2570. }
  2571. tem = append(tem, mapTem)
  2572. }
  2573. temap["layout"] = tem
  2574. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2575. }
  2576. }
  2577. }
  2578. queryData.(map[string]interface{})["order"] = dids
  2579. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2580. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2581. }
  2582. } else {
  2583. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2584. }
  2585. }
  2586. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2587. fsion := gofasion.NewFasion(parammaps)
  2588. sqlnamestr := fsion.Get("name").ValueStr()
  2589. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2590. offset := fsion.Get("offset").ValueDefaultInt(0)
  2591. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2592. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2593. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2594. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2595. body := []byte("")
  2596. if sql != "" {
  2597. s_params := make([]interface{}, 0)
  2598. if fsion.HasKey("parammaps") {
  2599. parammaps := fsion.Get("parammaps")
  2600. paramslist := strings.Split(p, ",")
  2601. if len(paramslist) > 0 && p != "" {
  2602. for _, value := range paramslist {
  2603. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2604. }
  2605. }
  2606. }
  2607. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2608. if err != nil {
  2609. } else {
  2610. paramslist1 := strings.Split(p1, ",")
  2611. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2612. s_params1 := make([]interface{}, 0)
  2613. if len(paramslist1) > 0 && p1 != "" {
  2614. for _, v := range paramslist1 {
  2615. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2616. }
  2617. }
  2618. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2619. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2620. body, _ = json.Marshal(queryData)
  2621. }
  2622. }
  2623. }
  2624. bs := bytes.NewBuffer(body)
  2625. client := &http.Client{}
  2626. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2627. req, err := http.NewRequest(RequestMethod,
  2628. url,
  2629. bs,
  2630. )
  2631. if err != nil {
  2632. }
  2633. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2634. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2635. if err != nil {
  2636. // handle error
  2637. }
  2638. resp, err := client.Do(req)
  2639. if err != nil {
  2640. return ""
  2641. }
  2642. defer resp.Body.Close()
  2643. result_body, err := ioutil.ReadAll(resp.Body)
  2644. if err != nil {
  2645. return ""
  2646. }
  2647. fmt.Println(string(result_body))
  2648. return ""
  2649. }
  2650. func GetSummary(c *gin.Context) {
  2651. appG := app.Gin{C: c}
  2652. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2653. fsion := gofasion.NewFasion(string(dataByte))
  2654. offset := fsion.Get("offset").ValueDefaultInt(0)
  2655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2656. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2657. parammaps := fsion.Get("parammaps")
  2658. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2659. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2660. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2661. tx := restful.Engine.NewSession()
  2662. defer tx.Close()
  2663. sqlnamestr := ""
  2664. if genre == "0" {
  2665. if status == "0" {
  2666. sqlnamestr = "getAccuracyJSY"
  2667. } else if status == "1" {
  2668. sqlnamestr = "getAccuracyHFT"
  2669. } else if status == "2" {
  2670. sqlnamestr = "getAccuracyHNS"
  2671. } else if status == "3" {
  2672. sqlnamestr = "getAccuracyHSC"
  2673. } else if status == "4" {
  2674. sqlnamestr = "getAccuracyHCC"
  2675. } else if status == "5" {
  2676. sqlnamestr = "getAccuracyMC"
  2677. } else if status == "6" {
  2678. sqlnamestr = "getAccuracyFeedHL"
  2679. } else if status == "7" {
  2680. sqlnamestr = "getAccuracyRT"
  2681. }
  2682. } else {
  2683. if status == "0" {
  2684. sqlnamestr = "getAccuracySCCJSY"
  2685. } else if status == "1" {
  2686. sqlnamestr = "getAccuracySFT"
  2687. } else if status == "2" {
  2688. sqlnamestr = "getAccuracySNS"
  2689. } else if status == "3" {
  2690. sqlnamestr = "getAccuracySSC"
  2691. } else if status == "4" {
  2692. sqlnamestr = "getAccuracySCC"
  2693. } else if status == "5" {
  2694. sqlnamestr = "getAccuracySLCL"
  2695. } else if status == "7" {
  2696. sqlnamestr = "getAccuracySCCRT"
  2697. }
  2698. }
  2699. if isDate == "1" {
  2700. sqlnamestr += "Date"
  2701. }
  2702. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2703. // fmt.Println(sqlnamestr, sql)
  2704. if sql != "" {
  2705. s_params := make([]interface{}, 0)
  2706. // if fsion.HasKey("parammaps") {
  2707. fmt.Println(s_params, "222", p)
  2708. paramslist := strings.Split(p, ",")
  2709. if len(paramslist) > 0 && p != "" {
  2710. for _, value := range paramslist {
  2711. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2712. if tempv, exists := c.Get("jwt_username"); exists {
  2713. s_params = append(s_params, tempv.(string))
  2714. } else {
  2715. s_params = append(s_params, "")
  2716. }
  2717. } else {
  2718. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2719. }
  2720. }
  2721. }
  2722. if returntype == "xlsx" {
  2723. var xlsxfile *xlsx.File
  2724. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2725. //c.File("c:/dd.xlsx")
  2726. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2727. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2728. c.Header("Content-Transfer-Encoding", "binary")
  2729. _ = xlsxfile.Write(c.Writer)
  2730. } else {
  2731. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2732. if err != nil {
  2733. logging.Error("GetDataByName err: ", err)
  2734. msg := geterrmsg(err.Error())
  2735. appG.Response(http.StatusOK, e.ERROR, msg)
  2736. } else {
  2737. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2738. }
  2739. }
  2740. } else {
  2741. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2742. }
  2743. }
  2744. // type lpplanStruct struct {
  2745. // Id int64 `xorm:"id"`
  2746. // Tmrname string `xorm:"tmrname"`
  2747. // Tmrid int64 `xorm:"tmrid"`
  2748. // Sort int64 `xorm:"sort"`
  2749. // Sel int64 `xorm:"sel"`
  2750. // Times int64 `xorm:"times"`
  2751. // Ftname string `xorm:"ftname"`
  2752. // Ftid int64 `xorm:"ftid"`
  2753. // Maxweight float64 `xorm:"maxweight"`
  2754. // Sumweight float64 `xorm:"sumweight"`
  2755. // Sumcowcount int64 `xorm:"sumcowcount"`
  2756. // Pastureid string `xorm:"pastureid"`
  2757. // Display string `xorm:"display"`
  2758. // Issplit int64 `xorm:"issplit"`
  2759. // BeginTime string `xorm:"begintime"`
  2760. // }
  2761. func UpdateFTdetail(c *gin.Context) {
  2762. appG := app.Gin{C: c}
  2763. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2764. tempval_ := make(map[string]interface{})
  2765. tempCommon := make(map[string]interface{})
  2766. tempval := make([]map[string]interface{}, 0)
  2767. fTChange := make(map[string]interface{}, 0)
  2768. fpdOldDataList := make([]map[string]interface{}, 0)
  2769. fpdDataList := make([]map[string]interface{}, 0)
  2770. fsion := gofasion.NewFasion(string(dataByte))
  2771. // parammaps := fsion.Get("parammaps")
  2772. createdate := time.Now().Format("2006-01-02 15:04:05")
  2773. err := json.Unmarshal(dataByte, &tempval_)
  2774. if err != nil {
  2775. appG.Response(http.StatusOK, e.ERROR, false)
  2776. return
  2777. }
  2778. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2779. tx := restful.Engine.NewSession()
  2780. if v, ok := tempval_["data"].([]interface{}); ok {
  2781. for _, Tvalue := range v {
  2782. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2783. if v1["name"] == "updateFPbyFTChange" {
  2784. fTChange = v1
  2785. continue
  2786. }
  2787. tempval = append(tempval, v1)
  2788. }
  2789. }
  2790. }
  2791. parammaps := fTChange["parammaps"].(map[string]interface{})
  2792. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2793. // if err != nil {
  2794. // logs.Error(err)
  2795. // appG.Response(http.StatusOK, e.ERROR, false)
  2796. // return
  2797. // }
  2798. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2799. // if err != nil {
  2800. // logs.Error(err)
  2801. // appG.Response(http.StatusOK, e.ERROR, false)
  2802. // return
  2803. // }
  2804. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2805. // if err != nil {
  2806. // logs.Error(err)
  2807. // appG.Response(http.StatusOK, e.ERROR, false)
  2808. // return
  2809. // }
  2810. err = tx.Begin()
  2811. if err != nil {
  2812. logging.Error("tx.Begin 事务启动失败__error:", err)
  2813. }
  2814. defer func() {
  2815. if err != nil {
  2816. if tx != nil {
  2817. tx.Rollback()
  2818. }
  2819. }
  2820. if tx != nil {
  2821. tx.Close()
  2822. }
  2823. }()
  2824. if err != nil {
  2825. } else {
  2826. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2827. tempCommon = v
  2828. }
  2829. 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 ,
  2830. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2831. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2832. UNION
  2833. 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 ,
  2834. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2835. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2836. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2837. if err == nil {
  2838. if tempv, exists := c.Get("jwt_username"); exists {
  2839. tempCommon["jwt_username"] = tempv.(string)
  2840. }
  2841. for _, paramvalue := range tempval {
  2842. if _, ok := paramvalue["resultname"]; !ok {
  2843. paramvalue["resultname"] = paramvalue["name"]
  2844. }
  2845. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2846. if err != nil {
  2847. logging.Error("ExecDataParam error:", err)
  2848. break
  2849. }
  2850. }
  2851. if err != nil {
  2852. msg := geterrmsg(err.Error())
  2853. appG.Response(http.StatusOK, e.ERROR, msg)
  2854. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2855. }
  2856. }
  2857. }
  2858. tx.Commit()
  2859. // go func() {
  2860. if fTChange != nil {
  2861. parammaps := fTChange["parammaps"].(map[string]interface{})
  2862. if parammaps["type"].(float64) == 1 {
  2863. _, err = tx.SQL(`UPDATE feedp fp
  2864. set
  2865. ccountratio = ccount *(ratio /100 ),
  2866. fp.ftweight= IFNULL(IF(
  2867. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2868. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2869. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2870. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2871. ),0),fp.feedweight = IFNULL(IF(
  2872. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2873. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2874. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2875. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2876. ),0) +ifnull(fp.supplyweight,0)
  2877. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2878. _, err = tx.SQL(`UPDATE fpdetail fpd
  2879. INNER JOIN feedp fp
  2880. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2881. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2882. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2883. } else {
  2884. _, err = tx.SQL(`UPDATE feedp fp
  2885. SET ccountratio = ccount *(ratio /100 ),
  2886. fp.supplyweight= IFNULL(IF(
  2887. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2888. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2889. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2890. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2891. ),0),fp.feedweight = IFNULL(IF(
  2892. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2893. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2894. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2895. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2896. ),0) +ifnull(fp.supplyweight,0)
  2897. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2898. _, err = tx.SQL(`UPDATE fpdetail fpd
  2899. INNER JOIN feedp fp
  2900. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2901. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2902. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2903. }
  2904. 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 ,
  2905. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2906. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2907. UNION
  2908. 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 ,
  2909. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2910. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2911. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2912. lpplanList := make([]*lpplanStruct, 0)
  2913. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2914. if err != nil {
  2915. logs.Error(err, 1)
  2916. return
  2917. }
  2918. lppidlist := []string{}
  2919. for _, lpp := range lpplanList {
  2920. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2921. }
  2922. if len(lppidlist) <= 0 {
  2923. appG.Response(http.StatusOK, e.SUCCESS, true)
  2924. return
  2925. }
  2926. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2927. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2928. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2929. if err != nil {
  2930. // tx.Rollback()
  2931. logs.Error(err, 2, parammaps["pastureid"])
  2932. return
  2933. }
  2934. var wg sync.WaitGroup
  2935. for _, old := range fpdOldDataList {
  2936. for _, fpd := range fpdDataList {
  2937. wg.Add(1)
  2938. go func(old, fpd map[string]interface{}) {
  2939. updateLppandList := make([]*lpplandtl1, 0)
  2940. defer wg.Done()
  2941. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2942. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2943. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2944. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2945. // if weight > oldweight {
  2946. // return
  2947. // }
  2948. var w float64
  2949. var status int
  2950. if weight < oldweight {
  2951. if weight >= 0 {
  2952. return
  2953. }
  2954. w = weight
  2955. status = 0
  2956. } else {
  2957. if oldweight > 0 {
  2958. return
  2959. }
  2960. w = weight
  2961. status = 1
  2962. }
  2963. // fweight = w
  2964. for _, lpp := range lpplanList {
  2965. var fweight float64
  2966. var lweight float64
  2967. lpplandtl1List := make([]*lpplandtl1, 0)
  2968. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2969. for _, lppland := range lpplandtl1AllList {
  2970. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2971. lpplandtl1List = append(lpplandtl1List, lppland)
  2972. }
  2973. }
  2974. if len(lpplandtl1List) == 0 {
  2975. continue
  2976. }
  2977. for _, lppland := range lpplandtl1List {
  2978. lweight += lppland.Lweight
  2979. }
  2980. if status == 0 {
  2981. if lweight <= 0 {
  2982. continue
  2983. }
  2984. } else {
  2985. if lpp.Maxweight <= lweight {
  2986. continue
  2987. }
  2988. }
  2989. for _, lppland := range lpplandtl1List {
  2990. if fpdid == lppland.Fpdid {
  2991. if status == 1 {
  2992. // if w <= lppland.Lweight {
  2993. if lpp.Maxweight <= lweight {
  2994. continue
  2995. }
  2996. if w+lweight <= lpp.Maxweight {
  2997. lppland.Lweight += w
  2998. lweight += w
  2999. fweight += w
  3000. w = 0
  3001. } else {
  3002. w = w - (lpp.Maxweight - lweight)
  3003. n := (lpp.Maxweight - lweight)
  3004. lppland.Lweight = lppland.Lweight + n
  3005. lweight += n
  3006. fweight += n
  3007. }
  3008. } else {
  3009. if lppland.Lweight == 0 {
  3010. continue
  3011. }
  3012. if w+lppland.Lweight >= 0 {
  3013. lppland.Lweight = lppland.Lweight + w
  3014. lweight = lweight + w
  3015. fweight = fweight + w
  3016. w = 0
  3017. } else {
  3018. w = w + lppland.Lweight
  3019. lweight = lweight - lppland.Lweight
  3020. fweight = fweight - lppland.Lweight
  3021. lppland.Lweight = 0
  3022. }
  3023. }
  3024. updateLppandList = append(updateLppandList, lppland)
  3025. break
  3026. }
  3027. }
  3028. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3029. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3030. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3031. if err != nil {
  3032. // tx.Rollback()
  3033. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3034. return
  3035. }
  3036. for _, lppland := range updateLppandList {
  3037. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3038. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3039. if err != nil {
  3040. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3041. // tx.Rollback()
  3042. logs.Error(err, 3)
  3043. return
  3044. }
  3045. // defer wg.Done()
  3046. }
  3047. updateLppandList = []*lpplandtl1{}
  3048. if w == 0 {
  3049. break
  3050. }
  3051. }
  3052. }
  3053. }(old, fpd)
  3054. }
  3055. }
  3056. wg.Wait()
  3057. }
  3058. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3059. if err != nil {
  3060. logs.Error(err)
  3061. appG.Response(http.StatusOK, e.ERROR, false)
  3062. return
  3063. }
  3064. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3065. if err != nil {
  3066. logs.Error(err)
  3067. appG.Response(http.StatusOK, e.ERROR, false)
  3068. return
  3069. }
  3070. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3071. if err != nil {
  3072. logs.Error(err)
  3073. appG.Response(http.StatusOK, e.ERROR, false)
  3074. return
  3075. }
  3076. now := createdate
  3077. // for _, oldFpd := range oldFpdDataList {
  3078. for _, newFpd := range newFpdDataList {
  3079. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3080. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3081. // go func() {
  3082. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3083. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3084. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3085. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3086. if err != nil {
  3087. logs.Error(err)
  3088. appG.Response(http.StatusOK, e.ERROR, false)
  3089. return
  3090. }
  3091. // }()
  3092. }
  3093. // break
  3094. // }
  3095. // }
  3096. // }
  3097. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3098. for _, newLpplandtl1 := range newLpplandtl1List {
  3099. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3100. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3101. // go func() {
  3102. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3103. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3104. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3105. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3106. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3107. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3108. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3109. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3110. if err != nil {
  3111. logs.Error(err)
  3112. appG.Response(http.StatusOK, e.ERROR, false)
  3113. return
  3114. }
  3115. // }()
  3116. // }
  3117. // break
  3118. // }
  3119. // }
  3120. }
  3121. // for _, oldFeedp := range oldFeedpList {
  3122. for _, newFeedp := range newFeedpList {
  3123. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3124. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3125. // go func() {
  3126. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3127. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3128. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3129. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3130. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3131. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3132. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3133. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3134. if err != nil {
  3135. logs.Error(err)
  3136. appG.Response(http.StatusOK, e.ERROR, false)
  3137. return
  3138. }
  3139. // }()
  3140. // }
  3141. // }
  3142. }
  3143. appG.Response(http.StatusOK, e.SUCCESS, true)
  3144. }
  3145. type lpplandtlInfo struct {
  3146. Id int64 `xorm:"id"`
  3147. Pastureid int64 `xorm:"pastureid"`
  3148. Lppid int64 `xorm:"lppid"`
  3149. Barid int64 `xorm:"barid"`
  3150. Barname string `xorm:"barname"`
  3151. Fpdid int64 `xorm:"fpdid"`
  3152. Fttype int64 `xorm:"fttype"`
  3153. Lweight float64 `xorm:"lweight"`
  3154. Sort int64 `xorm:"sort"`
  3155. Tmrid int64 `xorm:"tmrid"`
  3156. Tmrname string `xorm:"tmrname"`
  3157. Cowcount int64 `xorm:"cowcount"`
  3158. Ccountradio float64 `xorm:"ccountradio"`
  3159. Background string `xorm:"background"`
  3160. Lweighthis float64 `xorm:"lweighthis"`
  3161. Maxweight float64 `xorm:"maxweight"`
  3162. }
  3163. func UpdateFpdetailBar(c *gin.Context) {
  3164. appG := app.Gin{C: c}
  3165. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3166. fsion := gofasion.NewFasion(string(dataByte))
  3167. pastureid := fsion.Get("pastureid").ValueStr()
  3168. id := fsion.Get("id").ValueStr()
  3169. tx := restful.Engine.NewSession()
  3170. tx.Begin()
  3171. 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 `,
  3172. pastureid, id).Query().List()
  3173. if err != nil {
  3174. logs.Error(err)
  3175. }
  3176. for _, fpd := range fpdList {
  3177. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3178. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3179. pastureid, fpd["id"]).Query().List()
  3180. if err != nil {
  3181. tx.Rollback()
  3182. logs.Error(err)
  3183. appG.Response(http.StatusOK, e.ERROR, false)
  3184. return
  3185. }
  3186. var lweight float64
  3187. for _, lppland := range lpplandList {
  3188. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3189. lweight += lweight1
  3190. }
  3191. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3192. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3193. if fpdweight >= ptuse && lweight == ptuse {
  3194. continue
  3195. } else {
  3196. if lweight <= fpdweight {
  3197. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3198. if err != nil {
  3199. tx.Rollback()
  3200. logs.Error(err)
  3201. appG.Response(http.StatusOK, e.ERROR, false)
  3202. return
  3203. }
  3204. } else {
  3205. weight := fpdweight - lweight
  3206. for _, lppland := range lpplandList {
  3207. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3208. if weight >= lpplandlweight {
  3209. weight = weight - lpplandlweight
  3210. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3211. if err != nil {
  3212. tx.Rollback()
  3213. logs.Error(err)
  3214. appG.Response(http.StatusOK, e.ERROR, false)
  3215. return
  3216. }
  3217. } else {
  3218. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3219. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3220. // if err != nil {
  3221. // tx.Rollback()
  3222. // logs.Error(err)
  3223. // appG.Response(http.StatusOK, e.ERROR, false)
  3224. // return
  3225. // }
  3226. weight = 0
  3227. break
  3228. }
  3229. }
  3230. }
  3231. }
  3232. }
  3233. fsionData := fsion.Get("data").Array()
  3234. for _, list := range fsionData {
  3235. ftmap := make(map[string]interface{})
  3236. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3237. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3238. ftmap["times"] = list.Get("times").ValueInt64()
  3239. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3240. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3241. // fmt.Println(ftmap)
  3242. fpdDataList, err := tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(-1 ) ptsid ,
  3243. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3244. WHERE fpdetail.pastureid = ? and barid =(select barid from feedp where id = ? ) and times = ?
  3245. UNION
  3246. 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 ,
  3247. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3248. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? ) t
  3249. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3250. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3251. if err != nil {
  3252. tx.Rollback()
  3253. logs.Error(err)
  3254. }
  3255. for _, fpd := range fpdDataList {
  3256. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3257. fttype := -1
  3258. if ftmap["ptid"].(string) != "-1" {
  3259. fttype = 1
  3260. }
  3261. var fweight float64
  3262. var lweight float64
  3263. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3264. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3265. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3266. join tmr t on t.id = lpp.tmrid
  3267. where lppland.fpdid =?
  3268. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3269. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3270. if err != nil {
  3271. tx.Rollback()
  3272. logs.Error(err)
  3273. }
  3274. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3275. var w float64
  3276. var status int
  3277. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3278. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3279. if weight >= 0 {
  3280. continue
  3281. }
  3282. w = weight
  3283. status = 0
  3284. } else {
  3285. // continue
  3286. if weight <= 0 {
  3287. continue
  3288. }
  3289. w = weight
  3290. status = 1
  3291. }
  3292. for _, lppland := range lpplandtl1List {
  3293. lweight += lppland.Lweight
  3294. }
  3295. for _, lppland := range lpplandtl1List {
  3296. if status == 1 {
  3297. // if w <= lppland.Lweight {
  3298. if lppland.Maxweight <= lweight {
  3299. continue
  3300. }
  3301. if w+lweight <= lppland.Maxweight {
  3302. lppland.Lweight += w
  3303. lweight += w
  3304. fweight += w
  3305. w = 0
  3306. } else {
  3307. w = w - (lppland.Maxweight - lweight)
  3308. n := (lppland.Maxweight - lweight)
  3309. lppland.Lweight = lppland.Lweight + n
  3310. lweight += n
  3311. fweight += n
  3312. }
  3313. } else {
  3314. if lppland.Lweight == 0 {
  3315. continue
  3316. }
  3317. if w+lppland.Lweight >= 0 {
  3318. lppland.Lweight = lppland.Lweight + w
  3319. lweight = lweight + w
  3320. fweight = fweight + w
  3321. w = 0
  3322. } else {
  3323. w = w + lppland.Lweight
  3324. lweight = lweight - lppland.Lweight
  3325. fweight = fweight - lppland.Lweight
  3326. lppland.Lweight = 0
  3327. }
  3328. }
  3329. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3330. if err != nil {
  3331. tx.Rollback()
  3332. logs.Error(err)
  3333. return
  3334. }
  3335. break
  3336. }
  3337. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3338. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3339. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3340. if err != nil {
  3341. tx.Rollback()
  3342. logs.Error(err)
  3343. }
  3344. if w == 0 {
  3345. break
  3346. }
  3347. }
  3348. }
  3349. }
  3350. tx.Commit()
  3351. now := time.Now()
  3352. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3353. if err != nil {
  3354. logs.Error(err)
  3355. appG.Response(http.StatusOK, e.ERROR, false)
  3356. return
  3357. }
  3358. for _, newLpplandtl1 := range newLpplandtl1List {
  3359. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3360. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3361. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3362. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3363. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3364. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3365. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3366. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3367. if err != nil {
  3368. logs.Error(err)
  3369. appG.Response(http.StatusOK, e.ERROR, false)
  3370. return
  3371. }
  3372. }
  3373. appG.Response(http.StatusOK, e.SUCCESS, true)
  3374. }
  3375. func GetProcessAnalysis(c *gin.Context) {
  3376. appG := app.Gin{C: c}
  3377. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3378. fsion := gofasion.NewFasion(string(dataByte))
  3379. sqlnamestr := fsion.Get("name").ValueStr()
  3380. offset := fsion.Get("offset").ValueDefaultInt(0)
  3381. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3382. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3383. parammaps := fsion.Get("parammaps")
  3384. tx := restful.Engine.NewSession()
  3385. err := tx.Begin()
  3386. defer func() {
  3387. switch {
  3388. case err != nil:
  3389. logging.Error("tx.Begin 事务启动失败__error:", err)
  3390. if tx != nil {
  3391. tx.Rollback()
  3392. }
  3393. default:
  3394. if tx != nil {
  3395. err = tx.Commit()
  3396. }
  3397. }
  3398. if tx != nil {
  3399. tx.Close()
  3400. }
  3401. }()
  3402. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3403. s_params := make([]interface{}, 0)
  3404. paramslist := strings.Split(p, ",")
  3405. if len(paramslist) > 0 && p != "" {
  3406. for _, value := range paramslist {
  3407. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3408. if tempv, exists := c.Get("jwt_username"); exists {
  3409. s_params = append(s_params, tempv.(string))
  3410. } else {
  3411. s_params = append(s_params, "")
  3412. }
  3413. } else {
  3414. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3415. }
  3416. }
  3417. }
  3418. tmrtnameStr := ""
  3419. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3420. if len(tmrtnameStr) == 0 {
  3421. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3422. } else {
  3423. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3424. }
  3425. }
  3426. if len(tmrtnameStr) > 0 {
  3427. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3428. }
  3429. sql += " ORDER BY d.intime"
  3430. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3431. if err != nil {
  3432. logging.Error("GetDataByName err: ", err)
  3433. msg := geterrmsg(err.Error())
  3434. appG.Response(http.StatusOK, e.ERROR, msg)
  3435. } else {
  3436. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3437. }
  3438. }
  3439. func UpdateFeedtempletStatus(c *gin.Context) {
  3440. appG := app.Gin{C: c}
  3441. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3442. fsion := gofasion.NewFasion(string(dataByte))
  3443. parammaps := fsion.Get("parammaps")
  3444. tx := restful.Engine.NewSession()
  3445. tx.Begin()
  3446. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3447. if err != nil {
  3448. tx.Rollback()
  3449. logs.Error(err)
  3450. appG.Response(http.StatusOK, e.ERROR, err)
  3451. return
  3452. }
  3453. tx.Commit()
  3454. appG.Response(http.StatusOK, e.SUCCESS, true)
  3455. }
  3456. func AddFtdry(c *gin.Context) {
  3457. appG := app.Gin{C: c}
  3458. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3459. fsion := gofasion.NewFasion(string(dataByte))
  3460. sqlnamestr := fsion.Get("name").ValueStr()
  3461. s_params := make([]interface{}, 0)
  3462. tx := restful.Engine.NewSession()
  3463. err := tx.Begin()
  3464. defer func() {
  3465. switch {
  3466. case err != nil:
  3467. if tx != nil {
  3468. tx.Rollback()
  3469. }
  3470. default:
  3471. if tx != nil {
  3472. err = tx.Commit()
  3473. }
  3474. }
  3475. if tx != nil {
  3476. tx.Close()
  3477. }
  3478. }()
  3479. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3480. if sql != "" {
  3481. parammaps := fsion.Get("parammaps")
  3482. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3483. paramslist := strings.Split(p, ",")
  3484. if len(paramslist) > 0 && p != "" {
  3485. for _, value := range paramslist {
  3486. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3487. if tempv, exists := c.Get("jwt_username"); exists {
  3488. s_params = append(s_params, tempv.(string))
  3489. } else {
  3490. s_params = append(s_params, "")
  3491. }
  3492. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3493. ids, err := setting.SnowIds.NextId()
  3494. if err != nil {
  3495. ids = time.Now().UnixNano()
  3496. logging.Info("create SnowIds err", err)
  3497. }
  3498. s_params = append(s_params, ids)
  3499. } else {
  3500. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3501. }
  3502. }
  3503. }
  3504. var actweight float64
  3505. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3506. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3507. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3508. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3509. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3510. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3511. 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()
  3512. if err != nil {
  3513. logging.Error("AddFtdry err: ", err)
  3514. msg := geterrmsg(err.Error())
  3515. appG.Response(http.StatusOK, e.ERROR, msg)
  3516. }
  3517. if len(actweightList) > 0 {
  3518. for _, item := range actweightList {
  3519. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3520. if err != nil {
  3521. logging.Error("AddFtdry err: ", err)
  3522. msg := geterrmsg(err.Error())
  3523. appG.Response(http.StatusOK, e.ERROR, msg)
  3524. }
  3525. actweight = fl
  3526. }
  3527. } else {
  3528. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3529. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3530. parammaps.Get("barid").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. for _, item := range dryList {
  3537. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3538. if err != nil {
  3539. logging.Error("AddFtdry err: ", err)
  3540. msg := geterrmsg(err.Error())
  3541. appG.Response(http.StatusOK, e.ERROR, msg)
  3542. }
  3543. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3544. }
  3545. }
  3546. if sqlnamestr == "insertFtdry" {
  3547. s_params = append(s_params, actweight)
  3548. } else if sqlnamestr == "updateFtdry" {
  3549. sql = fmt.Sprintf(sql, actweight)
  3550. }
  3551. queryData, err := execDataBySqlT(sql, s_params, tx)
  3552. if err != nil {
  3553. logging.Error("AddFtdry err: ", err)
  3554. msg := geterrmsg(err.Error())
  3555. appG.Response(http.StatusOK, e.ERROR, msg)
  3556. } else {
  3557. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3558. }
  3559. } else {
  3560. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3561. }
  3562. }
  3563. func CheckDates(c *gin.Context) {
  3564. tx := restful.Engine.NewSession()
  3565. defer tx.Close()
  3566. appG := app.Gin{C: c}
  3567. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3568. tempval_ := make(map[string]interface{})
  3569. tempCommon := make(map[string]interface{})
  3570. tempval := make([]map[string]interface{}, 0)
  3571. err := json.Unmarshal(dataByte, &tempval_)
  3572. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3573. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3574. if err != nil {
  3575. } else {
  3576. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3577. tempCommon = v
  3578. }
  3579. if v, ok := tempval_["data"].([]interface{}); ok {
  3580. for _, Tvalue := range v {
  3581. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3582. tempval = append(tempval, v1)
  3583. }
  3584. }
  3585. }
  3586. if err == nil {
  3587. if tempv, exists := c.Get("jwt_username"); exists {
  3588. tempCommon["jwt_username"] = tempv.(string)
  3589. }
  3590. for _, paramvalue := range tempval {
  3591. if _, ok := paramvalue["resultname"]; !ok {
  3592. paramvalue["resultname"] = paramvalue["name"]
  3593. }
  3594. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3595. if err != nil {
  3596. logging.Error("ExecDataParam error:", err)
  3597. }
  3598. }
  3599. if err == nil {
  3600. vmsg := ""
  3601. for _, item := range tempval {
  3602. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3603. for _, childrenList := range list.([]interface{}) {
  3604. for k, children := range childrenList.(map[string]interface{}) {
  3605. if k != "children" {
  3606. continue
  3607. }
  3608. for _, v := range children.([]map[string]interface{}) {
  3609. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3610. if k1 == "list" {
  3611. for _, v2 := range v1.([]map[string]interface{}) {
  3612. if v2["vmsg"].(string) != "1" {
  3613. if len(vmsg) == 0 {
  3614. vmsg = v2["vmsg"].(string)
  3615. } else {
  3616. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3617. }
  3618. }
  3619. }
  3620. }
  3621. }
  3622. }
  3623. }
  3624. }
  3625. }
  3626. }
  3627. if len(vmsg) > 0 {
  3628. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3629. } else {
  3630. appG.Response(http.StatusOK, e.SUCCESS, true)
  3631. }
  3632. } else {
  3633. msg := geterrmsg(err.Error())
  3634. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3635. }
  3636. }
  3637. }
  3638. if err != nil {
  3639. msg := geterrmsg(err.Error())
  3640. appG.Response(http.StatusOK, e.ERROR, msg)
  3641. }
  3642. }
  3643. 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) {
  3644. sqlname := fasion["name"].(string)
  3645. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3646. if v, ok := fasion["type"]; ok {
  3647. sqltype = v.(string)
  3648. }
  3649. sql := ""
  3650. p := ""
  3651. s_params := make([]interface{}, 0)
  3652. if sqltype != "" {
  3653. sql, p = restful.GetSqlByName(sqlname, tx)
  3654. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3655. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3656. paramslist := strings.Split(p, ",")
  3657. if len(paramslist) > 0 && p != "" {
  3658. for _, value := range paramslist {
  3659. ss := ""
  3660. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3661. ids, err := setting.SnowIds.NextId()
  3662. if err != nil {
  3663. ids = time.Now().UnixNano()
  3664. logging.Info("create SnowIds err", err)
  3665. }
  3666. s_params = append(s_params, ids)
  3667. } else {
  3668. if ss == "" && CommonParamMap != nil {
  3669. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3670. ss = valuestring
  3671. tempstrb := strings.IndexAny(valuestring, "@")
  3672. tempstre := strings.IndexAny(valuestring, ".")
  3673. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3674. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3675. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3676. }
  3677. } else {
  3678. ss = ""
  3679. }
  3680. }
  3681. }
  3682. if ss == "" && ParentParamMap != nil {
  3683. ss = getParamValue_(v, value, ParentParamMap)
  3684. }
  3685. if ss == "" && sameParamMap != nil {
  3686. ss = getParamValue(v, value, sameParamMap)
  3687. }
  3688. if ss == "" && ParamMap != nil {
  3689. ss = getParamValue(v, value, ParamMap)
  3690. }
  3691. s_params = append(s_params, ss)
  3692. }
  3693. }
  3694. }
  3695. }
  3696. }
  3697. if sql == "" {
  3698. sqltype = ""
  3699. }
  3700. if sql != "" {
  3701. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3702. if err != nil {
  3703. return nil, err
  3704. }
  3705. // fmt.Println(tempValParam)
  3706. return tempValParam.(map[string]interface{}), nil
  3707. } else {
  3708. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3709. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3710. if err != nil {
  3711. return nil, err
  3712. }
  3713. return nil, err
  3714. }
  3715. }
  3716. return nil, nil
  3717. }
  3718. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3719. var err error
  3720. subarray, ok := fasion["children"]
  3721. if ok {
  3722. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3723. tempVal_arrary := make([]map[string]interface{}, 0)
  3724. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3725. tempVal_ := make(map[string]interface{})
  3726. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3727. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3728. } else {
  3729. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3730. }
  3731. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3732. if err != nil {
  3733. return err
  3734. }
  3735. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3736. }
  3737. v.(map[string]interface{})["children"] = tempVal_arrary
  3738. }
  3739. }
  3740. return nil
  3741. }
  3742. func FpdImportExcel(c *gin.Context) {
  3743. appG := app.Gin{C: c}
  3744. inputdata := ""
  3745. c.Request.ParseForm()
  3746. params := c.Request.Form
  3747. file, _, err := c.Request.FormFile("file")
  3748. if err != nil {
  3749. appG.Response(http.StatusOK, e.ERROR, err)
  3750. return
  3751. }
  3752. sqlnamestrs := params.Get("name")
  3753. sheetname := params.Get("sheetname")
  3754. pastureid := params.Get("pastureid")
  3755. // importParams := params.Get("importParams")
  3756. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3757. // 必输项参数 (字符串格式 "field1,field2,field3")
  3758. requiredParams := params.Get("requiredParams")
  3759. // 日期参数
  3760. dateParams := params.Get("dateParams")
  3761. // 数字参数
  3762. numParams := params.Get("numParams")
  3763. //将字符串分割开
  3764. dateParamslist := strings.Split(dateParams, ",")
  3765. requiredParamslist := strings.Split(requiredParams, ",")
  3766. numParamslist := strings.Split(numParams, ",")
  3767. queryData := make([]interface{}, 0)
  3768. sqlslist := strings.Split(sqlnamestrs, ",")
  3769. xlsx1, err := excelize.OpenReader(file)
  3770. if err != nil {
  3771. fmt.Println(err)
  3772. return
  3773. }
  3774. ok := 0
  3775. error := 0
  3776. isdone := true
  3777. tx := restful.Engine.NewSession()
  3778. defer tx.Close()
  3779. 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
  3780. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3781. if err != nil {
  3782. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3783. return
  3784. }
  3785. rows := xlsx1.GetRows(sheetname)
  3786. // 限制10000条,多余的截取掉
  3787. if len(rows) > 10000 {
  3788. rows = rows[:10000]
  3789. }
  3790. for i, row := range rows {
  3791. if i > 0 {
  3792. entry := make(map[string]interface{})
  3793. outentry := make(map[string]interface{})
  3794. for j, colCell := range rows[0] {
  3795. for k, colCell1 := range row {
  3796. if j == k {
  3797. outentry[colCell] = colCell1
  3798. entry[colCell] = colCell1
  3799. }
  3800. }
  3801. }
  3802. inputdata = ""
  3803. a := ""
  3804. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3805. //校验日期格式
  3806. for _, v := range dateParamslist {
  3807. if v == "" {
  3808. continue
  3809. }
  3810. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3811. dtime, err := TransfTime(d.(string))
  3812. if err != nil {
  3813. a = strings.Trim(v, " ")
  3814. break
  3815. }
  3816. outentry[strings.Trim(v, " ")] = dtime
  3817. }
  3818. }
  3819. if a != "" {
  3820. outentry["error_msg"] = a + " 格式错误"
  3821. error++
  3822. queryData = append(queryData, outentry)
  3823. continue
  3824. }
  3825. a = ""
  3826. //校验必填格式
  3827. for _, v := range requiredParamslist {
  3828. if v == "" {
  3829. continue
  3830. }
  3831. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3832. a = strings.Trim(v, " ")
  3833. break
  3834. }
  3835. }
  3836. if a != "" {
  3837. outentry["error_msg"] = a + " 未填或格式错误"
  3838. error++
  3839. queryData = append(queryData, outentry)
  3840. continue
  3841. }
  3842. a = ""
  3843. //校验数字格式
  3844. for _, v := range numParamslist {
  3845. if v == "" {
  3846. continue
  3847. }
  3848. d, ok := outentry[strings.Trim(v, " ")]
  3849. if !ok || d == "" {
  3850. outentry[strings.Trim(v, " ")] = 0
  3851. } else {
  3852. var fl float64
  3853. switch d.(type) {
  3854. case string:
  3855. fl, err = strconv.ParseFloat(d.(string), 64)
  3856. }
  3857. if err != nil || fl < 0 {
  3858. a = strings.Trim(v, " ")
  3859. break
  3860. }
  3861. }
  3862. }
  3863. if a != "" {
  3864. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3865. error++
  3866. queryData = append(queryData, outentry)
  3867. continue
  3868. }
  3869. errExist := false
  3870. for _, sqlnamestr := range sqlslist {
  3871. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3872. paramslist := strings.Split(paramslists, ",")
  3873. if len(paramslist) > 0 {
  3874. s_params := make([]interface{}, 0)
  3875. for _, value := range paramslist {
  3876. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3877. if tempv, exists := c.Get("jwt_username"); exists {
  3878. s_params = append(s_params, tempv.(string))
  3879. } else {
  3880. s_params = append(s_params, "")
  3881. }
  3882. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3883. s_params = append(s_params, pastureid)
  3884. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3885. ids, err := setting.SnowIds.NextId()
  3886. if err != nil {
  3887. ids = time.Now().UnixNano()
  3888. logging.Info("create SnowIds err", err)
  3889. }
  3890. s_params = append(s_params, ids)
  3891. } else {
  3892. if outentry[strings.Trim(value, " ")] == nil {
  3893. s_params = append(s_params, "")
  3894. } else {
  3895. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3896. }
  3897. }
  3898. }
  3899. outentry["input"] = inputdata
  3900. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3901. if err != nil {
  3902. errExist = true
  3903. // if tx != nil {
  3904. // tx.Rollback()
  3905. // }
  3906. // if tx != nil {
  3907. // tx.Close()
  3908. // }
  3909. msg := geterrmsg(err.Error())
  3910. outentry["error_msg"] = msg
  3911. error++
  3912. queryData = append(queryData, outentry)
  3913. isdone = true
  3914. break
  3915. } else {
  3916. if len(returnmsgmap1) > 0 {
  3917. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3918. // if tx != nil {
  3919. // tx.Rollback()
  3920. // }
  3921. // if tx != nil {
  3922. // tx.Close()
  3923. // }
  3924. msg := geterrmsg(va.(string))
  3925. outentry["error_msg"] = msg
  3926. error++
  3927. queryData = append(queryData, outentry)
  3928. isdone = true
  3929. break
  3930. }
  3931. }
  3932. isdone = false
  3933. }
  3934. }
  3935. }
  3936. if !errExist {
  3937. dataexcel := make(map[string]interface{}, 0)
  3938. if _, ok := outentry["栏舍名称"]; ok {
  3939. dataexcel["barname"] = outentry["栏舍名称"]
  3940. }
  3941. if _, ok := outentry["实际牛头数"]; ok {
  3942. dataexcel["ccount"] = outentry["实际牛头数"]
  3943. }
  3944. if _, ok := outentry["系数(%)"]; ok {
  3945. dataexcel["ratio"] = outentry["系数(%)"]
  3946. }
  3947. if _, ok := outentry["配方模板"]; ok {
  3948. dataexcel["ftname"] = outentry["配方模板"]
  3949. }
  3950. if _, ok := outentry["补料配方"]; ok {
  3951. dataexcel["ptsfname"] = outentry["补料配方"]
  3952. }
  3953. if _, ok := outentry["第一班比例(%)"]; ok {
  3954. dataexcel["1"] = outentry["第一班比例(%)"]
  3955. }
  3956. if _, ok := outentry["第二班比例(%)"]; ok {
  3957. dataexcel["2"] = outentry["第二班比例(%)"]
  3958. }
  3959. if _, ok := outentry["第三班比例(%)"]; ok {
  3960. dataexcel["3"] = outentry["第三班比例(%)"]
  3961. }
  3962. if _, ok := outentry["第四班比例(%)"]; ok {
  3963. dataexcel["4"] = outentry["第四班比例(%)"]
  3964. }
  3965. if _, ok := outentry["第五班比例(%)"]; ok {
  3966. dataexcel["5"] = outentry["第四班比例(%)"]
  3967. }
  3968. if _, ok := outentry["第六班比例(%)"]; ok {
  3969. dataexcel["6"] = outentry["第六班比例(%)"]
  3970. }
  3971. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3972. if err != nil {
  3973. logs.Error(err)
  3974. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3975. return
  3976. }
  3977. if !existbar {
  3978. continue
  3979. }
  3980. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  3981. if err != nil {
  3982. logs.Error(err)
  3983. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3984. return
  3985. }
  3986. if !ftexist {
  3987. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  3988. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3989. if err != nil {
  3990. logs.Error(err)
  3991. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3992. return
  3993. }
  3994. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3995. if err != nil {
  3996. logs.Error(err)
  3997. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3998. return
  3999. }
  4000. }
  4001. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4002. if err != nil {
  4003. logs.Error(err)
  4004. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4005. return
  4006. }
  4007. if !exist {
  4008. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4009. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4010. if err != nil {
  4011. logs.Error(err)
  4012. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4013. return
  4014. }
  4015. }
  4016. var feedpargs []interface{}
  4017. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4018. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4019. if _, ok := dataexcel["ftname"]; ok {
  4020. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4021. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4022. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4023. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4024. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4025. } else {
  4026. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4027. }
  4028. if _, ok := dataexcel["ptsfname"]; ok {
  4029. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4030. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4031. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4032. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4033. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4034. } else {
  4035. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4036. }
  4037. upFeedpSql += " where barname = ? and pastureid = ? "
  4038. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4039. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4040. if err != nil {
  4041. logs.Error(err)
  4042. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4043. return
  4044. }
  4045. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4046. if err != nil {
  4047. logs.Error(err)
  4048. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4049. return
  4050. }
  4051. if !exist1 {
  4052. _, 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) `,
  4053. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4054. if err != nil {
  4055. logs.Error(err)
  4056. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4057. return
  4058. }
  4059. }
  4060. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4061. if err != nil {
  4062. logs.Error(err)
  4063. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4064. return
  4065. }
  4066. if !exist2 {
  4067. _, 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) `,
  4068. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4069. if err != nil {
  4070. logs.Error(err)
  4071. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4072. return
  4073. }
  4074. }
  4075. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4076. if err != nil {
  4077. logs.Error(err)
  4078. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4079. return
  4080. }
  4081. if !exist3 {
  4082. _, 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) `,
  4083. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4084. if err != nil {
  4085. logs.Error(err)
  4086. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4087. return
  4088. }
  4089. }
  4090. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4091. if err != nil {
  4092. logs.Error(err)
  4093. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4094. return
  4095. }
  4096. if !exist4 {
  4097. _, 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) `,
  4098. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4099. if err != nil {
  4100. logs.Error(err)
  4101. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4102. return
  4103. }
  4104. }
  4105. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4106. if err != nil {
  4107. logs.Error(err)
  4108. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4109. return
  4110. }
  4111. if !exist5 {
  4112. _, 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) `,
  4113. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4114. if err != nil {
  4115. logs.Error(err)
  4116. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4117. return
  4118. }
  4119. }
  4120. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4121. if err != nil {
  4122. logs.Error(err)
  4123. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4124. return
  4125. }
  4126. if !exist6 {
  4127. _, 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) `,
  4128. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4129. if err != nil {
  4130. logs.Error(err)
  4131. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4132. return
  4133. }
  4134. }
  4135. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4136. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4137. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4138. and pastureid = ? and times = ?`
  4139. var fpdargs1 []interface{}
  4140. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4141. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4142. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4143. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4144. if err != nil {
  4145. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4146. return
  4147. }
  4148. var fpdargs2 []interface{}
  4149. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4150. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4151. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4152. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4153. if err != nil {
  4154. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4155. return
  4156. }
  4157. var fpdargs3 []interface{}
  4158. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4159. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4160. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4161. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4162. if err != nil {
  4163. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4164. return
  4165. }
  4166. var fpdargs4 []interface{}
  4167. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4168. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4169. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4170. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4171. if err != nil {
  4172. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4173. return
  4174. }
  4175. var fpdargs5 []interface{}
  4176. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4177. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4178. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4179. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4180. if err != nil {
  4181. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4182. return
  4183. }
  4184. var fpdargs6 []interface{}
  4185. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4186. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4187. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4188. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4189. if err != nil {
  4190. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4191. return
  4192. }
  4193. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4194. 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()
  4195. if err != nil {
  4196. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4197. return
  4198. }
  4199. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4200. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4201. upFpdetailList := make([]*upFpdetail, 0)
  4202. for _, newfpd := range newList {
  4203. for _, oldfpd := range oldFpdList {
  4204. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4205. var oldweight, newweight float64
  4206. if oldfpd["weight"] != nil {
  4207. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4208. }
  4209. if newfpd["weight"] != nil {
  4210. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4211. }
  4212. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4213. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4214. Old: oldweight,
  4215. New: newweight,
  4216. Times: newfpd["times"].(int64),
  4217. Ptid: newfpd["ptid"].(int64),
  4218. Fweight: fweight,
  4219. Id: oldfpd["id"].(int64),
  4220. })
  4221. break
  4222. }
  4223. }
  4224. }
  4225. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4226. }
  4227. }
  4228. if !isdone {
  4229. ok++
  4230. isdone = true
  4231. }
  4232. }
  4233. data := make(map[string]interface{})
  4234. data["result"] = queryData
  4235. data["success"] = ok
  4236. data["err_count"] = error
  4237. appG.Response(http.StatusOK, e.SUCCESS, data)
  4238. }
  4239. type upFpdetail struct {
  4240. Old float64
  4241. New float64
  4242. Times int64
  4243. Ptid int64
  4244. Fweight float64
  4245. Id int64
  4246. // Ptsid string
  4247. }
  4248. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4249. tx := restful.Engine.NewSession()
  4250. defer tx.Close()
  4251. tx.Begin()
  4252. 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 `,
  4253. pastureid, barname).Query().List()
  4254. if err != nil {
  4255. logs.Error(err)
  4256. }
  4257. for _, fpd := range fpdList {
  4258. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4259. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4260. pastureid, fpd["id"], fpd["times"]).Query().List()
  4261. if err != nil {
  4262. tx.Rollback()
  4263. logs.Error(err)
  4264. return err
  4265. }
  4266. var lweight float64
  4267. for _, lppland := range lpplandList {
  4268. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4269. lweight += lweight1
  4270. }
  4271. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4272. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4273. if fpdweight >= ptuse && lweight == ptuse {
  4274. continue
  4275. } else {
  4276. if lweight <= fpdweight {
  4277. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4278. if err != nil {
  4279. tx.Rollback()
  4280. logs.Error(err)
  4281. return err
  4282. }
  4283. } else {
  4284. weight := lweight - fpdweight
  4285. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4286. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4287. if err != nil {
  4288. tx.Rollback()
  4289. logs.Error(err)
  4290. return err
  4291. }
  4292. for _, lppland := range lpplandList {
  4293. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4294. if weight >= lpplandlweight {
  4295. weight = weight - lpplandlweight
  4296. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4297. if err != nil {
  4298. tx.Rollback()
  4299. logs.Error(err)
  4300. return err
  4301. }
  4302. } else {
  4303. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4304. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4305. if err != nil {
  4306. tx.Rollback()
  4307. logs.Error(err)
  4308. return err
  4309. }
  4310. weight = 0
  4311. break
  4312. }
  4313. }
  4314. }
  4315. }
  4316. }
  4317. for _, list := range dataList {
  4318. ftmap := make(map[string]interface{})
  4319. ftmap["old"] = list.Old
  4320. ftmap["new"] = list.New
  4321. ftmap["times"] = list.Times
  4322. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4323. ftmap["ptsid"] = ""
  4324. // fmt.Println(ftmap)
  4325. fpdDataList, err := tx.SQL(`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 ,
  4326. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4327. WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4328. UNION
  4329. 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 ,
  4330. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4331. WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  4332. order by t.barname,t.times`, pastureid, barname, ftmap["times"], pastureid, barname, ftmap["times"]).Query().List()
  4333. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4334. if err != nil {
  4335. tx.Rollback()
  4336. logs.Error(err)
  4337. }
  4338. for _, fpd := range fpdDataList {
  4339. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4340. fttype := -1
  4341. if ftmap["ptid"].(string) != "-1" {
  4342. fttype = 1
  4343. }
  4344. var fweight float64
  4345. var lweight float64
  4346. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4347. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  4348. join lpplandtl1 lppland on lpp.id = lppland.lppid
  4349. join tmr t on t.id = lpp.tmrid
  4350. where lppland.fpdid =?
  4351. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4352. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4353. if err != nil {
  4354. tx.Rollback()
  4355. logs.Error(err)
  4356. }
  4357. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4358. // ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4359. var w float64
  4360. var status int
  4361. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  4362. if weight >= 0 {
  4363. continue
  4364. }
  4365. w = weight
  4366. status = 0
  4367. } else {
  4368. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4369. continue
  4370. }
  4371. w = weight
  4372. status = 1
  4373. }
  4374. for _, lppland := range lpplandtl1List {
  4375. lweight += lppland.Lweight
  4376. }
  4377. for _, lppland := range lpplandtl1List {
  4378. if status == 1 {
  4379. // if w <= lppland.Lweight {
  4380. if lppland.Maxweight <= lweight {
  4381. continue
  4382. }
  4383. if w+lweight <= lppland.Maxweight {
  4384. lppland.Lweight += w
  4385. lweight += w
  4386. fweight += w
  4387. w = 0
  4388. } else {
  4389. w = w - (lppland.Maxweight - lweight)
  4390. n := (lppland.Maxweight - lweight)
  4391. lppland.Lweight = lppland.Lweight + n
  4392. lweight += n
  4393. fweight += n
  4394. }
  4395. } else {
  4396. if lppland.Lweight == 0 {
  4397. continue
  4398. }
  4399. if w+lppland.Lweight >= 0 {
  4400. lppland.Lweight = lppland.Lweight + w
  4401. lweight = lweight + w
  4402. fweight = fweight + w
  4403. w = 0
  4404. } else {
  4405. w = w + lppland.Lweight
  4406. lweight = lweight - lppland.Lweight
  4407. fweight = fweight - lppland.Lweight
  4408. lppland.Lweight = 0
  4409. }
  4410. }
  4411. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4412. if err != nil {
  4413. tx.Rollback()
  4414. logs.Error(err)
  4415. return err
  4416. }
  4417. break
  4418. }
  4419. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4420. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4421. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4422. if err != nil {
  4423. tx.Rollback()
  4424. logs.Error(err)
  4425. }
  4426. if w == 0 {
  4427. break
  4428. }
  4429. }
  4430. }
  4431. }
  4432. // for _, data := range dataList {
  4433. // fttype := -1
  4434. // if data.Ptid != -1 {
  4435. // fttype = 1
  4436. // }
  4437. // var fweight float64
  4438. // var lweight float64
  4439. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4440. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4441. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4442. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4443. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4444. // if err != nil {
  4445. // tx.Rollback()
  4446. // logs.Error(err)
  4447. // return err
  4448. // }
  4449. // weight := data.Fweight
  4450. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4451. // var w float64
  4452. // var status int
  4453. // if data.New < data.Old {
  4454. // if weight >= 0 {
  4455. // continue
  4456. // }
  4457. // w = weight
  4458. // status = 0
  4459. // } else {
  4460. // // if weight-(data.New-data.Old) > 0 {
  4461. // // continue
  4462. // // }
  4463. // w = data.New - data.Old
  4464. // status = 1
  4465. // }
  4466. // for _, lppland := range lpplandtl1List {
  4467. // var lppdata lpplandtlInfo
  4468. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4469. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4470. // if err != nil {
  4471. // tx.Rollback()
  4472. // logs.Error(err)
  4473. // return err
  4474. // }
  4475. // lweight = lppdata.Lweight
  4476. // if status == 1 {
  4477. // // if w <= lppland.Lweight {
  4478. // if lppland.Maxweight <= lweight {
  4479. // continue
  4480. // }
  4481. // if w+lweight <= lppland.Maxweight {
  4482. // lppland.Lweight += w
  4483. // lweight += w
  4484. // fweight += w
  4485. // w = 0
  4486. // } else {
  4487. // w = w - (lppland.Maxweight - lweight)
  4488. // n := (lppland.Maxweight - lweight)
  4489. // lppland.Lweight = lppland.Lweight + n
  4490. // lweight += n
  4491. // fweight += n
  4492. // }
  4493. // } else {
  4494. // if lppland.Lweight == 0 {
  4495. // continue
  4496. // }
  4497. // if w+lppland.Lweight >= 0 {
  4498. // lppland.Lweight = lppland.Lweight + w
  4499. // lweight = lweight + w
  4500. // fweight = fweight + w
  4501. // w = 0
  4502. // } else {
  4503. // w = w + lppland.Lweight
  4504. // lweight = lweight - lppland.Lweight
  4505. // fweight = fweight - lppland.Lweight
  4506. // lppland.Lweight = 0
  4507. // }
  4508. // }
  4509. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4510. // if err != nil {
  4511. // tx.Rollback()
  4512. // logs.Error(err)
  4513. // return err
  4514. // }
  4515. // break
  4516. // }
  4517. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4518. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4519. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4520. // if err != nil {
  4521. // tx.Rollback()
  4522. // logs.Error(err)
  4523. // return err
  4524. // }
  4525. // // if w == 0 {
  4526. // // break
  4527. // // }
  4528. // // }
  4529. // }
  4530. err = tx.Commit()
  4531. if err != nil {
  4532. logs.Error(err)
  4533. tx.Rollback()
  4534. return err
  4535. }
  4536. now := time.Now()
  4537. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4538. if err != nil {
  4539. logs.Error(err)
  4540. return nil
  4541. }
  4542. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4543. if err != nil {
  4544. logs.Error(err)
  4545. return nil
  4546. }
  4547. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4548. if err != nil {
  4549. logs.Error(err)
  4550. return nil
  4551. }
  4552. for _, newLpplandtl1 := range newLpplandtl1List {
  4553. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4554. background,cowcount,ccountradio,lweighthis,createdate)
  4555. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4556. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4557. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4558. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4559. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4560. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4561. if err != nil {
  4562. logs.Error(err)
  4563. // appG.Response(http.StatusOK, e.ERROR, false)
  4564. return nil
  4565. }
  4566. }
  4567. for _, newFpd := range newFpdDataList {
  4568. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4569. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4570. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4571. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4572. if err != nil {
  4573. logs.Error(err)
  4574. // appG.Response(http.StatusOK, e.ERROR, false)
  4575. return nil
  4576. }
  4577. }
  4578. for _, newFeedp := range newFeedpList {
  4579. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4580. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4581. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4582. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4583. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4584. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4585. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4586. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4587. if err != nil {
  4588. logs.Error(err)
  4589. // appG.Response(http.StatusOK, e.ERROR, false)
  4590. return nil
  4591. }
  4592. }
  4593. return nil
  4594. }
  4595. func DeleteFTdetail(c *gin.Context) {
  4596. appG := app.Gin{C: c}
  4597. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4598. fsion := gofasion.NewFasion(string(dataByte))
  4599. parammaps := fsion.Get("parammaps")
  4600. pastureid := parammaps.Get("pastureid").ValueStr()
  4601. ftid := parammaps.Get("ftid").ValueStr()
  4602. tx := restful.Engine.NewSession()
  4603. defer tx.Close()
  4604. tx.Begin()
  4605. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4606. if err != nil {
  4607. tx.Rollback()
  4608. logs.Error(err)
  4609. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4610. return
  4611. }
  4612. if parammaps.Get("type").ValueStr() == "1" {
  4613. _, err := tx.SQL(`UPDATE feedp fp
  4614. set
  4615. fp.ftweight= IFNULL(IF(
  4616. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4617. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4618. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4619. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4620. ),0),fp.feedweight = IFNULL(IF(
  4621. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4622. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4623. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4624. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4625. ),0) +ifnull(fp.supplyweight,0)
  4626. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4627. if err != nil {
  4628. tx.Rollback()
  4629. logs.Error(err)
  4630. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4631. return
  4632. }
  4633. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4634. _, err = tx.SQL(`
  4635. UPDATE fpdetail fpd
  4636. INNER JOIN feedp fp
  4637. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4638. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4639. ptuse= 0
  4640. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4641. if err != nil {
  4642. tx.Rollback()
  4643. logs.Error(err)
  4644. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4645. return
  4646. }
  4647. } else {
  4648. _, err := tx.SQL(`UPDATE feedp fp
  4649. SET
  4650. fp.supplyweight= IFNULL(IF(
  4651. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4652. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4653. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4654. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4655. ),0),fp.feedweight = IFNULL(IF(
  4656. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4657. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4658. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4659. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4660. ),0) + ifnull(fp.supplyweight,0)
  4661. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4662. if err != nil {
  4663. tx.Rollback()
  4664. logs.Error(err)
  4665. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4666. return
  4667. }
  4668. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4669. _, err = tx.SQL(`
  4670. UPDATE fpdetail fpd
  4671. INNER JOIN feedp fp
  4672. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4673. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4674. ptsrate = 0
  4675. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4676. if err != nil {
  4677. tx.Rollback()
  4678. logs.Error(err)
  4679. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4680. return
  4681. }
  4682. }
  4683. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4684. if err != nil {
  4685. tx.Rollback()
  4686. logs.Error(err)
  4687. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4688. return
  4689. }
  4690. err = tx.Commit()
  4691. if err != nil {
  4692. tx.Rollback()
  4693. logs.Error(err)
  4694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4695. return
  4696. }
  4697. appG.Response(http.StatusOK, e.SUCCESS, true)
  4698. }
  4699. func DeleteSpillageAll(c *gin.Context) {
  4700. appG := app.Gin{C: c}
  4701. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4702. fsion := gofasion.NewFasion(string(dataByte))
  4703. parammaps := fsion.Get("parammaps")
  4704. pastureid := parammaps.Get("pastureid").ValueStr()
  4705. times := parammaps.Get("times").ValueStr()
  4706. barid := parammaps.Get("barid").ValueStr()
  4707. tx := restful.Engine.NewSession()
  4708. defer tx.Close()
  4709. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4710. if err != nil {
  4711. logs.Error(err)
  4712. appG.Response(http.StatusOK, e.ERROR, false)
  4713. return
  4714. }
  4715. now := time.Now()
  4716. for _, item := range lpplandtl1List {
  4717. go func(item map[string]interface{}) {
  4718. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4719. background,cowcount,ccountradio,lweighthis,createdate)
  4720. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4721. item["pastureid"], item["lppid"], item["barid"],
  4722. item["barname"], item["fpdid"], item["fttype"],
  4723. item["lweight"], item["sort"], item["tmrid"],
  4724. item["tmrname"], item["background"], item["cowcount"],
  4725. item["ccountradio"], item["lweighthis"], now).Execute()
  4726. if err != nil {
  4727. logs.Error(err)
  4728. appG.Response(http.StatusOK, e.ERROR, false)
  4729. return
  4730. }
  4731. }(item)
  4732. }
  4733. tx.Begin()
  4734. _, 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()
  4735. if err != nil {
  4736. tx.Rollback()
  4737. logs.Error(err)
  4738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4739. return
  4740. }
  4741. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4742. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4743. if err != nil {
  4744. tx.Rollback()
  4745. logs.Error(err)
  4746. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4747. return
  4748. }
  4749. err = tx.Commit()
  4750. if err != nil {
  4751. tx.Rollback()
  4752. logs.Error(err)
  4753. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4754. return
  4755. }
  4756. appG.Response(http.StatusOK, e.SUCCESS, true)
  4757. }
  4758. func GetTMRListEnableTypeAll(c *gin.Context) {
  4759. appG := app.Gin{C: c}
  4760. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4761. fsion := gofasion.NewFasion(string(dataByte))
  4762. parammaps := fsion.Get("parammaps")
  4763. pastureid := parammaps.Get("pastureid").ValueStr()
  4764. tx := restful.Engine.NewSession()
  4765. defer tx.Close()
  4766. dataList, err := tx.SQL(`SELECT
  4767. eqcode,
  4768. tname,
  4769. datacaptureno,
  4770. trim(tclassid) tclassid,
  4771. concat(tname,' / ',eqcode) tmrmix,
  4772. d.label tclassname,
  4773. maxstirfeed,
  4774. remark,
  4775. tmr.enable,
  4776. TRIM(tmr.id) id,
  4777. TRIM(tmr.pastureid)pastureid
  4778. FROM
  4779. tmr
  4780. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4781. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4782. ORDER BY id DESC`, pastureid).Query().List()
  4783. if err != nil {
  4784. logs.Error(err)
  4785. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4786. return
  4787. }
  4788. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4789. if err != nil {
  4790. logs.Error(err)
  4791. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4792. return
  4793. }
  4794. var carNum int64
  4795. for _, sysopt := range sysoptData {
  4796. if sysopt["inforvalue"] == nil {
  4797. carNum = 1
  4798. } else {
  4799. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4800. }
  4801. }
  4802. id := 200
  4803. n := 0
  4804. for i := carNum; i > 0; i-- {
  4805. id++
  4806. n++
  4807. data := make(map[string]interface{}, 0)
  4808. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4809. data["tname"] = fmt.Sprintf("任意车%d", n)
  4810. data["datacaptureno"] = -2
  4811. data["tclassid"] = -2
  4812. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4813. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4814. data["maxstirfeed"] = 100000
  4815. data["remark"] = fmt.Sprintf("任意车%d", n)
  4816. data["enable"] = 1
  4817. data["id"] = fmt.Sprintf("%d", id)
  4818. data["pastureid"] = pastureid
  4819. dataList = append(dataList, data)
  4820. }
  4821. // UNION ALL
  4822. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4823. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4824. }
  4825. func GetFeedpHistory(c *gin.Context) {
  4826. appG := app.Gin{C: c}
  4827. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4828. fsion := gofasion.NewFasion(string(dataByte))
  4829. // parammaps := fsion.Get("parammaps")
  4830. bar := fsion.Get("barname").ValueStr()
  4831. startDate := fsion.Get("startDate").ValueStr()
  4832. endDate := fsion.Get("endDate").ValueStr()
  4833. tx := restful.Engine.NewSession()
  4834. defer tx.Close()
  4835. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4836. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  4837. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4838. if err != nil {
  4839. logs.Error(err)
  4840. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4841. return
  4842. }
  4843. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  4844. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  4845. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4846. if err != nil {
  4847. logs.Error(err)
  4848. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4849. return
  4850. }
  4851. for _, feedp := range feedpList {
  4852. // LastftList, err := tx.SQL(` select tname ,id
  4853. // from feedtemplethistory where id = ?
  4854. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4855. // if err != nil {
  4856. // logs.Error(err)
  4857. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4858. // return
  4859. // }
  4860. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4861. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4862. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4863. if err != nil {
  4864. logs.Error(err)
  4865. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4866. return
  4867. }
  4868. var ftname interface{}
  4869. ftnamestatus := 0
  4870. ftname = feedp["ftname"]
  4871. var lastftid int64
  4872. if len(nextfeedpList) > 0 {
  4873. for _, ft := range nextfeedpList {
  4874. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4875. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4876. lastftid = ft["ftid"].(int64)
  4877. ftnamestatus = 1
  4878. break
  4879. }
  4880. }
  4881. }
  4882. for i, fpd := range fpdList {
  4883. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4884. fpd["weightstatus"] = 0
  4885. fpd["tratiostatus"] = 0
  4886. fpd["ftnamestatus"] = ftnamestatus
  4887. for k, fpd2 := range fpdList {
  4888. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4889. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4890. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4891. fpd["weightstatus"] = 1
  4892. }
  4893. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4894. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4895. fpd["tratiostatus"] = 1
  4896. }
  4897. break
  4898. }
  4899. }
  4900. fpd["barid"] = feedp["barid"]
  4901. fpd["barname"] = feedp["barname"]
  4902. fpd["ccount"] = feedp["ccount"]
  4903. fpd["ratio"] = feedp["ratio"]
  4904. fpd["ccountratio"] = feedp["ccountratio"]
  4905. fpd["ftid"] = feedp["ftid"]
  4906. fpd["ftname"] = ftname
  4907. fpd["ccountstatus"] = 0
  4908. fpd["ccountratiostatus"] = 0
  4909. fpd["ratiostatus"] = 0
  4910. fpd["ftnamestatus"] = 0
  4911. fpd["lastftid"] = lastftid
  4912. for _, next := range nextfeedpList {
  4913. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4914. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4915. fpd["ccountstatus"] = 1
  4916. }
  4917. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4918. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4919. fpd["ccountratiostatus"] = 1
  4920. }
  4921. if next["ratio"].(string) != fpd["ratio"].(string) {
  4922. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4923. fpd["ratiostatus"] = 1
  4924. }
  4925. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4926. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4927. // fpd["ftnamestatus"] = 1
  4928. // }
  4929. }
  4930. }
  4931. }
  4932. }
  4933. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4934. }
  4935. // func GetLpplandtl1History(c *gin.Context) {
  4936. // appG := app.Gin{C: c}
  4937. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4938. // fsion := gofasion.NewFasion(string(dataByte))
  4939. // // parammaps := fsion.Get("parammaps")
  4940. // barid := fsion.Get("barid").ValueStr()
  4941. // startDate := fsion.Get("startDate").ValueStr()
  4942. // endDate := fsion.Get("endDate").ValueStr()
  4943. // tx := restful.Engine.NewSession()
  4944. // defer tx.Close()
  4945. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4946. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4947. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4948. // // if err != nil {
  4949. // // logs.Error(err)
  4950. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4951. // // return
  4952. // // }
  4953. // // for _, feedp := range feedpList {
  4954. // // fmt.Println(feedp)
  4955. // // for i, fpd := range fpdList {
  4956. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4957. // // for k, fpd2 := range fpdList {
  4958. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4959. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4960. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4961. // // }
  4962. // // break
  4963. // // }
  4964. // // }
  4965. // // fpd["barid"] = feedp["barid"]
  4966. // // fpd["barname"] = feedp["barname"]
  4967. // // fpd["ccount"] = feedp["ccount"]
  4968. // // fpd["ratio"] = feedp["ratio"]
  4969. // // fpd["ccountratio"] = feedp["ccountratio"]
  4970. // // fpd["ftid"] = feedp["ftid"]
  4971. // // fpd["ftname"] = feedp["ftname"]
  4972. // // }
  4973. // // }
  4974. // // }
  4975. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4976. // }
  4977. func GetRemind(c *gin.Context) {
  4978. appG := app.Gin{C: c}
  4979. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4980. fsion := gofasion.NewFasion(string(dataByte))
  4981. parammaps := fsion.Get("parammaps")
  4982. pastureid := parammaps.Get("pastureid").ValueStr()
  4983. tx := restful.Engine.NewSession()
  4984. defer tx.Close()
  4985. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4986. if err != nil {
  4987. logs.Error(err)
  4988. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4989. return
  4990. }
  4991. // pastureid = "3"
  4992. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  4993. if err != nil {
  4994. logs.Error(err)
  4995. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4996. return
  4997. }
  4998. defer resp.Body.Close()
  4999. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5000. buf.ReadFrom(resp.Body)
  5001. fmt.Println(string(buf.Bytes()))
  5002. respMap := make(map[string]interface{}, 0)
  5003. err = json.Unmarshal(buf.Bytes(), &respMap)
  5004. if err != nil {
  5005. logs.Error(err)
  5006. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5007. return
  5008. }
  5009. for _, data := range dataList {
  5010. r := make(map[string]interface{}, 0)
  5011. r["sys_name"] = ""
  5012. r["service_id"] = ""
  5013. r["pasture_id"] = ""
  5014. r["type_name"] = ""
  5015. r["remind_type_id"] = ""
  5016. r["remind_type"] = ""
  5017. r["push_date"] = ""
  5018. r["push_time"] = ""
  5019. r["interval_time"] = ""
  5020. r["push_limit"] = ""
  5021. r["template_id"] = ""
  5022. r["roles_id"] = ""
  5023. r["users_id"] = ""
  5024. r["date_type"] = ""
  5025. r["cycle_type"] = ""
  5026. data["data"] = r
  5027. for _, resp := range respMap["data"].([]interface{}) {
  5028. resp1 := resp.(map[string]interface{})
  5029. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5030. if resp1["push_time"] == nil {
  5031. resp1["push_time"] = ""
  5032. }
  5033. data["data"] = resp1
  5034. break
  5035. }
  5036. }
  5037. }
  5038. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5039. }
  5040. type NoticeMsgtype struct {
  5041. SysName string `json:"sys_name"`
  5042. PastureId int64 `json:"pasture_id"`
  5043. ServiceId int64 `json:"service_id"`
  5044. TypeName string `json:"type_name"`
  5045. RemindType int64 `json:"remind_type"`
  5046. PushDate int64 `json:"push_date"`
  5047. PushTime string `json:"push_time"`
  5048. IntervalTime int64 `json:"interval_time"`
  5049. PushLimit int64 `json:"push_limit"`
  5050. TemplateId string `json:"template_id"`
  5051. UsersId string `json:"users_id"`
  5052. DateType int64 `json:"date_type"`
  5053. CycleType int64 `json:"cycle_type"`
  5054. DelayTime int64 `json:"delay_time"`
  5055. Status int64 `json:"status"`
  5056. }
  5057. func UpdateRemind(c *gin.Context) {
  5058. appG := app.Gin{C: c}
  5059. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5060. parammaps := gofasion.NewFasion(string(dataByte))
  5061. // parammaps := fsion.Get("parammaps")
  5062. // user := parammaps.Get("user").ValueStr()
  5063. id := parammaps.Get("id").ValueInt64()
  5064. noticeMsgtype := new(NoticeMsgtype)
  5065. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5066. noticeMsgtype.ServiceId = id
  5067. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5068. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5069. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5070. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5071. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5072. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5073. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5074. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5075. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5076. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5077. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5078. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5079. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5080. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5081. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5082. //TODO
  5083. noticeMsgtype.SysName = "tmrWatch"
  5084. userList := parammaps.Get("user").Array()
  5085. var userstr []string
  5086. for _, user := range userList {
  5087. userstr = append(userstr, user.ValueStr())
  5088. }
  5089. tx := restful.Engine.NewSession()
  5090. defer tx.Close()
  5091. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5092. if err != nil {
  5093. logs.Error(err)
  5094. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5095. return
  5096. }
  5097. // var jsonStr = []byte(noticeMsgtype
  5098. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5099. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5100. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5101. req.Header.Set("Content-Type", "application/json")
  5102. client := &http.Client{}
  5103. resp, err := client.Do(req)
  5104. if err != nil {
  5105. logs.Error(err)
  5106. }
  5107. defer resp.Body.Close()
  5108. body, _ := ioutil.ReadAll(resp.Body)
  5109. fmt.Println("response Body:", string(body))
  5110. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5111. if err != nil {
  5112. logs.Error(err)
  5113. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5114. return
  5115. }
  5116. defer getresp.Body.Close()
  5117. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5118. buf.ReadFrom(getresp.Body)
  5119. // fmt.Println(string(buf.Bytes()))
  5120. respMap := make(map[string]interface{}, 0)
  5121. err = json.Unmarshal(buf.Bytes(), &respMap)
  5122. if err != nil {
  5123. logs.Error(err)
  5124. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5125. return
  5126. }
  5127. for _, resp := range respMap["data"].([]interface{}) {
  5128. resp1 := resp.(map[string]interface{})
  5129. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5130. if err != nil {
  5131. logs.Error(err)
  5132. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5133. return
  5134. }
  5135. }
  5136. appG.Response(http.StatusOK, e.SUCCESS, true)
  5137. }
  5138. func GetSpillageallHistory(c *gin.Context) {
  5139. appG := app.Gin{C: c}
  5140. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5141. parammaps := gofasion.NewFasion(string(dataByte))
  5142. barname := parammaps.Get("barname").ValueStr()
  5143. pastureid := parammaps.Get("pastureid").ValueStr()
  5144. startdate := parammaps.Get("startDate").ValueStr()
  5145. enddate := parammaps.Get("endDate").ValueStr()
  5146. tx := restful.Engine.NewSession()
  5147. defer tx.Close()
  5148. 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
  5149. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5150. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5151. if err != nil {
  5152. logs.Error(err)
  5153. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5154. return
  5155. }
  5156. respMap := make([]map[string]interface{}, 0)
  5157. data := make(map[interface{}]interface{})
  5158. for _, history := range historyList {
  5159. data[history["createdate"]] = history["createdate"]
  5160. }
  5161. createList := []string{}
  5162. for _, v := range data {
  5163. createList = append(createList, v.(string))
  5164. }
  5165. // sort.Sort()
  5166. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5167. sort.Slice(createList, func(i, j int) bool {
  5168. return createList[i] > createList[j]
  5169. })
  5170. for _, v := range createList {
  5171. a := make(map[string]interface{})
  5172. a["createdate"] = data[v]
  5173. // createList = append(createList, v.(string))
  5174. respMap = append(respMap, a)
  5175. }
  5176. number := 0
  5177. dataMap := make([]interface{}, 0)
  5178. for k, resp := range respMap {
  5179. createdate := resp["createdate"].(string)
  5180. var nextcreatedate string
  5181. if len(respMap) > k+1 {
  5182. nextcreatedate = respMap[k+1]["createdate"].(string)
  5183. }
  5184. // dataList := make(map[string][]interface{})
  5185. // list := make(map[string]interface{})
  5186. times := make(map[interface{}]int)
  5187. for _, history := range historyList {
  5188. // List := make(map[interface{}][]interface{})
  5189. i := 0
  5190. if history["createdate"].(string) == createdate {
  5191. times[history["times"]]++
  5192. data := make(map[string]interface{})
  5193. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5194. // exist := false
  5195. if nextcreatedate != "" {
  5196. for _, history1 := range historyList {
  5197. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5198. history1["times"].(int64) == history["times"].(int64) {
  5199. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  5200. break
  5201. // exist = true
  5202. }
  5203. }
  5204. }
  5205. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5206. i++
  5207. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5208. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5209. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5210. // resp["times"] = history["times"]
  5211. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5212. data1 := make(map[string]interface{})
  5213. data1["times"] = history["times"]
  5214. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5215. data1["createdate"] = resp["createdate"]
  5216. // fmt.Println(dataList)
  5217. dataMap = append(dataMap, data1)
  5218. }
  5219. if i > number {
  5220. number = i
  5221. }
  5222. // respMap = append(respMap, dataList)
  5223. }
  5224. // for k, data := range dataList {
  5225. // resp[k] = data
  5226. // }
  5227. // resp["data"] = dataList
  5228. }
  5229. // resp := make(map[string]interface{})
  5230. // sort.Strings(createList)
  5231. //
  5232. // for _, create := range createList {
  5233. // for _, r := range respMap {
  5234. // if create == r["createdate"].(string) {
  5235. // resp[create] = r
  5236. // break
  5237. // }
  5238. // }
  5239. // }
  5240. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5241. var trainsList []interface{}
  5242. for i := 0; i < number; i++ {
  5243. trains := make(map[string]interface{})
  5244. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5245. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5246. trainsList = append(trainsList, trains)
  5247. }
  5248. respdata := make(map[string]interface{})
  5249. respdata["data"] = dataMap
  5250. respdata["trains"] = trainsList
  5251. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5252. }
  5253. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5254. appG := app.Gin{C: c}
  5255. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5256. parammaps := gofasion.NewFasion(string(dataByte))
  5257. ftid := parammaps.Get("ftid").ValueInt64()
  5258. lastftid := parammaps.Get("lastftid").ValueInt64()
  5259. pastureid := parammaps.Get("pastureid").ValueInt64()
  5260. // createdate := parammaps.Get("createdate").ValueStr()
  5261. tx := restful.Engine.NewSession()
  5262. defer tx.Close()
  5263. data := make(map[string]interface{})
  5264. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5265. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5266. if err != nil {
  5267. logs.Error(err)
  5268. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5269. return
  5270. }
  5271. feedtemplet := make(map[string]interface{})
  5272. for _, f := range feedtempletList {
  5273. feedtemplet = f
  5274. }
  5275. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5276. if err != nil {
  5277. logs.Error(err)
  5278. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5279. return
  5280. }
  5281. feedtemplet["fit"] = fitList
  5282. data["current"] = feedtemplet
  5283. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5284. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5285. if err != nil {
  5286. logs.Error(err)
  5287. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5288. return
  5289. }
  5290. lastfeedtemplet := make(map[string]interface{})
  5291. for _, f := range lastfeedtempletList {
  5292. lastfeedtemplet = f
  5293. }
  5294. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5295. if err != nil {
  5296. logs.Error(err)
  5297. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5298. return
  5299. }
  5300. lastfeedtemplet["fit"] = lastfitList
  5301. data["last"] = lastfeedtemplet
  5302. appG.Response(http.StatusOK, e.SUCCESS, data)
  5303. }
  5304. func GetFeedtempletHistory(c *gin.Context) {
  5305. appG := app.Gin{C: c}
  5306. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5307. parammaps := gofasion.NewFasion(string(dataByte))
  5308. ftid := parammaps.Get("ftid").ValueStr()
  5309. pastureid := parammaps.Get("pastureid").ValueInt64()
  5310. start := parammaps.Get("startdate").ValueStr()
  5311. end := parammaps.Get("enddate").ValueStr()
  5312. tx := restful.Engine.NewSession()
  5313. defer tx.Close()
  5314. 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 ?
  5315. and id = ? and pastureid = ? order by createdate desc `,
  5316. start, end, ftid, pastureid).Query().List()
  5317. if err != nil {
  5318. logs.Error(err)
  5319. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5320. return
  5321. }
  5322. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5323. ftid, pastureid).Query().List()
  5324. if err != nil {
  5325. logs.Error(err)
  5326. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5327. return
  5328. }
  5329. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5330. for i, ft := range ftList {
  5331. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5332. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5333. (select empname from user where id = fit.userId) empname,
  5334. 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
  5335. where fit.fitid = ?
  5336. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5337. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5338. if err != nil {
  5339. logs.Error(err)
  5340. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5341. return
  5342. }
  5343. ft["createdate"] = ft["createdate1"]
  5344. // data["tname"] = ft["tname"]
  5345. // data["tcode"] = ft["tcode"]
  5346. // data["tcolor"] = ft["tcolor"]
  5347. // data["fttype"] = ft["fttype"]
  5348. // data["ccname"] = ft["ccname"]
  5349. // data["source"] = ft["source"]
  5350. // data["version"] = ft["version"]
  5351. // data["remark"] = ft["remark"]
  5352. for n, ft2 := range ftList {
  5353. if i < n {
  5354. if ft["tname"].(string) != ft2["tname"].(string) {
  5355. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5356. }
  5357. if _, ok := ft["tcode"]; ok {
  5358. if _, ok := ft2["tcode"]; ok {
  5359. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5360. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5361. }
  5362. }
  5363. }
  5364. if _, ok := ft["tcolor"]; ok {
  5365. if _, ok := ft2["tcolor"]; ok {
  5366. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5367. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5368. }
  5369. }
  5370. }
  5371. if _, ok := ft["fttype"]; ok {
  5372. if _, ok := ft2["fttype"]; ok {
  5373. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5374. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5375. }
  5376. }
  5377. }
  5378. if _, ok := ft["ccname"]; ok {
  5379. if _, ok := ft2["ccname"]; ok {
  5380. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5381. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5382. }
  5383. }
  5384. }
  5385. if _, ok := ft["source"]; ok {
  5386. if _, ok := ft2["source"]; ok {
  5387. if ft["source"].(string) != ft2["source"].(string) {
  5388. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5389. }
  5390. }
  5391. }
  5392. if _, ok := ft["version"]; ok {
  5393. if _, ok := ft2["version"]; ok {
  5394. if ft["version"].(int64) != ft2["version"].(int64) {
  5395. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5396. }
  5397. }
  5398. }
  5399. if _, ok := ft["remark"]; ok {
  5400. if _, ok := ft2["remark"]; ok {
  5401. if ft["remark"].(string) != ft2["remark"].(string) {
  5402. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5403. }
  5404. }
  5405. }
  5406. break
  5407. }
  5408. }
  5409. dataList := make([]map[string]interface{}, 0)
  5410. if len(fithisList) > 0 {
  5411. for _, fit := range fithisList {
  5412. data := make(map[string]interface{})
  5413. data["feedgroup"] = fit["feedgroup"]
  5414. data["fname"] = fit["fname"]
  5415. data["empname"] = fit["empname"]
  5416. if fit["Eweight"] != nil {
  5417. if fit["Eweight"].(string) != fit["weight"].(string) {
  5418. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5419. } else {
  5420. data["fweight"] = fit["Eweight"]
  5421. }
  5422. data["fweightstatus"] = 1
  5423. } else {
  5424. data["fweight"] = fit["weight"]
  5425. data["fweightstatus"] = 0
  5426. }
  5427. data["autosecond"] = fit["autosecond"]
  5428. // data["tname"] = ft["tname"]
  5429. // data["tcode"] = ft["tcode"]
  5430. // data["tcolor"] = ft["tcolor"]
  5431. // data["fttype"] = ft["fttype"]
  5432. // data["ccname"] = ft["ccname"]
  5433. // data["source"] = ft["source"]
  5434. // data["version"] = ft["version"]
  5435. // data["remark"] = ft["remark"]
  5436. // data["createdate"] = ft["createdate1"]
  5437. // ft["fit"] = data
  5438. dataList = append(dataList, data)
  5439. }
  5440. } else {
  5441. for _, fit := range ftdetailList {
  5442. data := make(map[string]interface{})
  5443. data["feedgroup"] = fit["feedgroup"]
  5444. data["fname"] = fit["fname"]
  5445. // if fit["Eweight"] != nil {
  5446. // data["weight"] = fit["Eweight"]
  5447. // } else {
  5448. data["fweight"] = fit["fweight"]
  5449. // }
  5450. data["autosecond"] = fit["autosecond"]
  5451. // ft["fit"] = data
  5452. dataList = append(dataList, data)
  5453. }
  5454. }
  5455. ft["fit"] = dataList
  5456. }
  5457. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5458. }
  5459. func UpdateMaterialTMR(c *gin.Context) {
  5460. appG := app.Gin{C: c}
  5461. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5462. parammaps := gofasion.NewFasion(string(dataByte))
  5463. tmrid := parammaps.Get("tmrid").ValueStr()
  5464. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5465. lppid := parammaps.Get("lppid").ValueStr()
  5466. times := parammaps.Get("times").ValueStr()
  5467. pastureid := parammaps.Get("pastureid").ValueStr()
  5468. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5469. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5470. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5471. tx := restful.Engine.NewSession()
  5472. defer tx.Close()
  5473. tx.Begin()
  5474. if tmrid != "1000" {
  5475. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5476. if err != nil {
  5477. logs.Error(err)
  5478. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5479. return
  5480. }
  5481. var maxstirfeed float64
  5482. for _, tmr := range tmrList {
  5483. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5484. }
  5485. if status == 0 {
  5486. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5487. if err != nil {
  5488. tx.Rollback()
  5489. logs.Error(err)
  5490. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5491. return
  5492. }
  5493. var lweight float64
  5494. for _, item := range lpplandtl1List {
  5495. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5496. lweight += fl
  5497. }
  5498. if lweight > maxstirfeed {
  5499. lweight = lweight - maxstirfeed
  5500. } else {
  5501. lweight = 0
  5502. }
  5503. if lweight > 0 {
  5504. lweight1 := lweight / float64(len(lpplandtl1List))
  5505. number := 0
  5506. for _, item := range lpplandtl1List {
  5507. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5508. if lweight1 >= fl {
  5509. number++
  5510. }
  5511. }
  5512. lweight := lweight / float64((len(lpplandtl1List) - number))
  5513. for _, item := range lpplandtl1List {
  5514. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5515. if lweight1 >= fl {
  5516. continue
  5517. }
  5518. if tmrtype == "1" {
  5519. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5520. if err != nil {
  5521. tx.Rollback()
  5522. logs.Error(err)
  5523. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5524. return
  5525. }
  5526. } else if tmrtype == "2" {
  5527. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5528. if err != nil {
  5529. tx.Rollback()
  5530. logs.Error(err)
  5531. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5532. return
  5533. }
  5534. }
  5535. if item["fttype"].(int64) == 0 {
  5536. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5537. if err != nil {
  5538. tx.Rollback()
  5539. logs.Error(err)
  5540. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5541. return
  5542. }
  5543. } else {
  5544. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5545. if err != nil {
  5546. tx.Rollback()
  5547. logs.Error(err)
  5548. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5549. return
  5550. }
  5551. }
  5552. }
  5553. } else {
  5554. for _, item := range lpplandtl1List {
  5555. // 自走式
  5556. if tmrtype == "1" {
  5557. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5558. if err != nil {
  5559. logs.Error(err)
  5560. tx.Rollback()
  5561. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5562. return
  5563. }
  5564. } else if tmrtype == "2" {
  5565. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5566. if err != nil {
  5567. logs.Error(err)
  5568. tx.Rollback()
  5569. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5570. return
  5571. }
  5572. }
  5573. }
  5574. }
  5575. } else if status == 1 {
  5576. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5577. if err != nil {
  5578. logs.Error(err)
  5579. tx.Rollback()
  5580. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5581. return
  5582. }
  5583. var lweight float64
  5584. for _, item := range lpplandtl1List {
  5585. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5586. lweight += fl
  5587. }
  5588. if lweight > maxstirfeed {
  5589. lweight = lweight - maxstirfeed
  5590. } else {
  5591. lweight = 0
  5592. }
  5593. for _, item := range lpplandtl1List {
  5594. if lweight > 0 {
  5595. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5596. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5597. if fl >= lweight {
  5598. item["lweight"] = fl - lweight
  5599. lweight = 0
  5600. if tmrtype == "1" {
  5601. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5602. if err != nil {
  5603. logs.Error(err)
  5604. tx.Rollback()
  5605. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5606. return
  5607. }
  5608. } else if tmrtype == "2" {
  5609. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5610. if err != nil {
  5611. logs.Error(err)
  5612. tx.Rollback()
  5613. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5614. return
  5615. }
  5616. }
  5617. if item["fttype"].(int64) == 0 {
  5618. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5619. if err != nil {
  5620. logs.Error(err)
  5621. tx.Rollback()
  5622. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5623. return
  5624. }
  5625. } else {
  5626. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5627. if err != nil {
  5628. logs.Error(err)
  5629. tx.Rollback()
  5630. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5631. return
  5632. }
  5633. }
  5634. } else {
  5635. lweight = lweight - fl
  5636. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5637. if err != nil {
  5638. logs.Error(err)
  5639. tx.Rollback()
  5640. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5641. return
  5642. }
  5643. if item["fttype"].(int64) == 0 {
  5644. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5645. if err != nil {
  5646. logs.Error(err)
  5647. tx.Rollback()
  5648. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5649. return
  5650. }
  5651. } else {
  5652. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5653. if err != nil {
  5654. logs.Error(err)
  5655. tx.Rollback()
  5656. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5657. return
  5658. }
  5659. }
  5660. }
  5661. } else {
  5662. // 自走式
  5663. if tmrtype == "1" {
  5664. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5665. if err != nil {
  5666. logs.Error(err)
  5667. tx.Rollback()
  5668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5669. return
  5670. }
  5671. } else if tmrtype == "2" {
  5672. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5673. if err != nil {
  5674. logs.Error(err)
  5675. tx.Rollback()
  5676. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5677. return
  5678. }
  5679. }
  5680. }
  5681. }
  5682. } else {
  5683. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5684. if err != nil {
  5685. logs.Error(err)
  5686. tx.Rollback()
  5687. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5688. return
  5689. }
  5690. for _, item := range lpplandtl1List {
  5691. if item["fttype"].(int64) == 0 {
  5692. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5693. if err != nil {
  5694. logs.Error(err)
  5695. tx.Rollback()
  5696. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5697. return
  5698. }
  5699. } else {
  5700. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5701. if err != nil {
  5702. logs.Error(err)
  5703. tx.Rollback()
  5704. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5705. return
  5706. }
  5707. }
  5708. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5709. if err != nil {
  5710. logs.Error(err)
  5711. tx.Rollback()
  5712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5713. return
  5714. }
  5715. }
  5716. }
  5717. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5718. if err != nil {
  5719. logs.Error(err)
  5720. tx.Rollback()
  5721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5722. return
  5723. }
  5724. } else {
  5725. if status == 2 {
  5726. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5727. if err != nil {
  5728. logs.Error(err)
  5729. tx.Rollback()
  5730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5731. return
  5732. }
  5733. for _, item := range lpplandtl1List {
  5734. if item["fttype"].(int64) == 0 {
  5735. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5736. if err != nil {
  5737. logs.Error(err)
  5738. tx.Rollback()
  5739. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5740. return
  5741. }
  5742. } else {
  5743. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5744. if err != nil {
  5745. logs.Error(err)
  5746. tx.Rollback()
  5747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5748. return
  5749. }
  5750. }
  5751. }
  5752. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).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 lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).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. }
  5769. err := tx.Commit()
  5770. if err != nil {
  5771. logs.Error(err)
  5772. tx.Rollback()
  5773. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5774. return
  5775. }
  5776. appG.Response(http.StatusOK, e.SUCCESS, true)
  5777. }
  5778. func UpdateMaterialTMRDate(c *gin.Context) {
  5779. appG := app.Gin{C: c}
  5780. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5781. parammaps := gofasion.NewFasion(string(dataByte))
  5782. tmrid := parammaps.Get("tmrid").ValueStr()
  5783. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5784. lppid := parammaps.Get("lppid").ValueStr()
  5785. times := parammaps.Get("times").ValueStr()
  5786. pastureid := parammaps.Get("pastureid").ValueStr()
  5787. date := parammaps.Get("date").ValueStr()
  5788. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5789. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5790. tx := restful.Engine.NewSession()
  5791. defer tx.Close()
  5792. tx.Begin()
  5793. if tmrid != "1000" {
  5794. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5795. if err != nil {
  5796. logs.Error(err)
  5797. tx.Rollback()
  5798. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5799. return
  5800. }
  5801. var maxstirfeed float64
  5802. for _, tmr := range tmrList {
  5803. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5804. }
  5805. if status == 0 {
  5806. 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()
  5807. if err != nil {
  5808. logs.Error(err)
  5809. tx.Rollback()
  5810. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5811. return
  5812. }
  5813. var lweight float64
  5814. for _, item := range lpplandtl1List {
  5815. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5816. lweight += fl
  5817. }
  5818. if lweight > maxstirfeed {
  5819. lweight = lweight - maxstirfeed
  5820. } else {
  5821. lweight = 0
  5822. }
  5823. if lweight > 0 {
  5824. lweight1 := lweight / float64(len(lpplandtl1List))
  5825. number := 0
  5826. for _, item := range lpplandtl1List {
  5827. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5828. if lweight1 >= fl {
  5829. number++
  5830. }
  5831. }
  5832. lweight := lweight / float64((len(lpplandtl1List) - number))
  5833. for _, item := range lpplandtl1List {
  5834. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5835. if lweight1 >= fl {
  5836. continue
  5837. }
  5838. if tmrtype == "1" {
  5839. _, 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()
  5840. if err != nil {
  5841. logs.Error(err)
  5842. tx.Rollback()
  5843. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5844. return
  5845. }
  5846. } else if tmrtype == "2" {
  5847. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5848. if err != nil {
  5849. logs.Error(err)
  5850. tx.Rollback()
  5851. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5852. return
  5853. }
  5854. }
  5855. if item["fttype"].(int64) == 0 {
  5856. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5857. if err != nil {
  5858. logs.Error(err)
  5859. tx.Rollback()
  5860. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5861. return
  5862. }
  5863. } else {
  5864. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5865. if err != nil {
  5866. logs.Error(err)
  5867. tx.Rollback()
  5868. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5869. return
  5870. }
  5871. }
  5872. }
  5873. } else {
  5874. for _, item := range lpplandtl1List {
  5875. // 自走式
  5876. if tmrtype == "1" {
  5877. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5878. if err != nil {
  5879. logs.Error(err)
  5880. tx.Rollback()
  5881. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5882. return
  5883. }
  5884. } else if tmrtype == "2" {
  5885. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5886. if err != nil {
  5887. logs.Error(err)
  5888. tx.Rollback()
  5889. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5890. return
  5891. }
  5892. }
  5893. }
  5894. }
  5895. } else if status == 1 {
  5896. 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()
  5897. if err != nil {
  5898. logs.Error(err)
  5899. tx.Rollback()
  5900. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5901. return
  5902. }
  5903. var lweight float64
  5904. for _, item := range lpplandtl1List {
  5905. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5906. lweight += fl
  5907. }
  5908. if lweight > maxstirfeed {
  5909. lweight = lweight - maxstirfeed
  5910. } else {
  5911. lweight = 0
  5912. }
  5913. for _, item := range lpplandtl1List {
  5914. if lweight > 0 {
  5915. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5916. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5917. if fl >= lweight {
  5918. item["lweight"] = fl - lweight
  5919. lweight = 0
  5920. if tmrtype == "1" {
  5921. _, 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()
  5922. if err != nil {
  5923. logs.Error(err)
  5924. tx.Rollback()
  5925. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5926. return
  5927. }
  5928. } else if tmrtype == "2" {
  5929. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5930. if err != nil {
  5931. logs.Error(err)
  5932. tx.Rollback()
  5933. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5934. return
  5935. }
  5936. }
  5937. if item["fttype"].(int64) == 0 {
  5938. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5939. if err != nil {
  5940. logs.Error(err)
  5941. tx.Rollback()
  5942. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5943. return
  5944. }
  5945. } else {
  5946. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5947. if err != nil {
  5948. logs.Error(err)
  5949. tx.Rollback()
  5950. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5951. return
  5952. }
  5953. }
  5954. } else {
  5955. lweight = lweight - fl
  5956. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5957. if err != nil {
  5958. logs.Error(err)
  5959. tx.Rollback()
  5960. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5961. return
  5962. }
  5963. if item["fttype"].(int64) == 0 {
  5964. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5965. if err != nil {
  5966. logs.Error(err)
  5967. tx.Rollback()
  5968. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5969. return
  5970. }
  5971. } else {
  5972. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5973. if err != nil {
  5974. logs.Error(err)
  5975. tx.Rollback()
  5976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5977. return
  5978. }
  5979. }
  5980. }
  5981. } else {
  5982. // 自走式
  5983. if tmrtype == "1" {
  5984. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5985. if err != nil {
  5986. logs.Error(err)
  5987. tx.Rollback()
  5988. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5989. return
  5990. }
  5991. } else if tmrtype == "2" {
  5992. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5993. if err != nil {
  5994. logs.Error(err)
  5995. tx.Rollback()
  5996. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5997. return
  5998. }
  5999. }
  6000. }
  6001. }
  6002. } else {
  6003. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6004. if err != nil {
  6005. logs.Error(err)
  6006. tx.Rollback()
  6007. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6008. return
  6009. }
  6010. for _, item := range lpplandtl1List {
  6011. if item["fttype"].(int64) == 0 {
  6012. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6013. if err != nil {
  6014. logs.Error(err)
  6015. tx.Rollback()
  6016. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6017. return
  6018. }
  6019. } else {
  6020. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6021. if err != nil {
  6022. logs.Error(err)
  6023. tx.Rollback()
  6024. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6025. return
  6026. }
  6027. }
  6028. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6029. if err != nil {
  6030. logs.Error(err)
  6031. tx.Rollback()
  6032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6033. return
  6034. }
  6035. }
  6036. }
  6037. _, 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()
  6038. if err != nil {
  6039. logs.Error(err)
  6040. tx.Rollback()
  6041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6042. return
  6043. }
  6044. } else {
  6045. if status == 2 {
  6046. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6047. if err != nil {
  6048. logs.Error(err)
  6049. tx.Rollback()
  6050. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6051. return
  6052. }
  6053. for _, item := range lpplandtl1List {
  6054. if item["fttype"].(int64) == 0 {
  6055. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6056. if err != nil {
  6057. logs.Error(err)
  6058. tx.Rollback()
  6059. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6060. return
  6061. }
  6062. } else {
  6063. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6064. if err != nil {
  6065. logs.Error(err)
  6066. tx.Rollback()
  6067. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6068. return
  6069. }
  6070. }
  6071. }
  6072. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, 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 lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, 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. }
  6089. err := tx.Commit()
  6090. if err != nil {
  6091. logs.Error(err)
  6092. tx.Rollback()
  6093. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6094. return
  6095. }
  6096. appG.Response(http.StatusOK, e.SUCCESS, true)
  6097. }
  6098. func Decimal(value float64) float64 {
  6099. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6100. return value
  6101. }
  6102. func UpdateDailyData(c *gin.Context) {
  6103. appG := app.Gin{C: c}
  6104. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6105. parammaps := gofasion.NewFasion(string(dataByte))
  6106. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6107. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6108. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6109. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6110. date := parammaps.Get("date").ValueStr()
  6111. tx := restful.Engine.NewSession()
  6112. defer tx.Close()
  6113. tx.Begin()
  6114. if location == 0 {
  6115. fid := parammaps.Get("fid").ValueStr()
  6116. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6117. if err != nil {
  6118. logs.Error("UpdateDailyData-error-1:", err)
  6119. tx.Rollback()
  6120. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6121. return
  6122. }
  6123. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6124. if err != nil {
  6125. logs.Error("UpdateDailyData-error-1:", err)
  6126. tx.Rollback()
  6127. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6128. return
  6129. }
  6130. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6131. if err != nil {
  6132. fmt.Println("Error:", err)
  6133. return
  6134. }
  6135. actualWeight := weight - num
  6136. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6137. if err != nil {
  6138. logs.Error("UpdateDailyData-error-2:", err)
  6139. tx.Rollback()
  6140. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6141. return
  6142. }
  6143. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6144. if err != nil {
  6145. logs.Error("UpdateDailyData-error-3:", err)
  6146. tx.Rollback()
  6147. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6148. return
  6149. }
  6150. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6151. if err != nil {
  6152. logs.Error("UpdateDailyData-error-4:", err)
  6153. tx.Rollback()
  6154. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6155. return
  6156. }
  6157. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6158. if err != nil {
  6159. logs.Error("UpdateDailyData-error-5:", err)
  6160. tx.Rollback()
  6161. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6162. return
  6163. }
  6164. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6165. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6166. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6167. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6168. if err != nil {
  6169. fmt.Println("Error:", err)
  6170. return
  6171. }
  6172. // actual := actualWeight / float64(len(downloadedplanList))
  6173. for _, item := range downloadedplanList {
  6174. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6175. if err != nil {
  6176. fmt.Println("Error:", err)
  6177. return
  6178. }
  6179. actual := itemLweight / lweight * actualWeight
  6180. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6181. if err != nil {
  6182. logs.Error("UpdateDailyData-error-6:", err)
  6183. tx.Rollback()
  6184. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6185. return
  6186. }
  6187. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6188. if err != nil {
  6189. logs.Error("UpdateDailyData-error-7:", err)
  6190. tx.Rollback()
  6191. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6192. return
  6193. }
  6194. _, 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()
  6195. if err != nil {
  6196. logs.Error("UpdateDailyData-error-8:", err)
  6197. tx.Rollback()
  6198. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6199. return
  6200. }
  6201. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6202. if err != nil {
  6203. logs.Error("UpdateDailyData-error-9:", err)
  6204. tx.Rollback()
  6205. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6206. return
  6207. }
  6208. }
  6209. } else {
  6210. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6211. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6212. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6213. // if err != nil {
  6214. // fmt.Println("Error:", err)
  6215. // return
  6216. // }
  6217. for _, item := range downloadedplanList {
  6218. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6219. if err != nil {
  6220. logs.Error("UpdateDailyData-error-6:", err)
  6221. tx.Rollback()
  6222. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6223. return
  6224. }
  6225. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6226. item["lweight"], actualWeight, item["id"]).Execute()
  6227. if err != nil {
  6228. logs.Error("UpdateDailyData-error-7:", err)
  6229. tx.Rollback()
  6230. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6231. return
  6232. }
  6233. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6234. where pid = ?`, item["id"]).Execute()
  6235. if err != nil {
  6236. logs.Error("UpdateDailyData-error-8:", err)
  6237. tx.Rollback()
  6238. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6239. return
  6240. }
  6241. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6242. if err != nil {
  6243. logs.Error("UpdateDailyData-error-9:", err)
  6244. tx.Rollback()
  6245. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6246. return
  6247. }
  6248. }
  6249. }
  6250. } else {
  6251. fbarid := parammaps.Get("fbarid").ValueStr()
  6252. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6253. if err != nil {
  6254. logs.Error("UpdateDailyData-error-10:", err)
  6255. tx.Rollback()
  6256. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6257. return
  6258. }
  6259. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6260. if err != nil {
  6261. logs.Error("UpdateDailyData-error-1:", err)
  6262. tx.Rollback()
  6263. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6264. return
  6265. }
  6266. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6267. if err != nil {
  6268. fmt.Println("Error:", err)
  6269. return
  6270. }
  6271. actualWeight := weight - num
  6272. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6273. if err != nil {
  6274. logs.Error("UpdateDailyData-error-11:", err)
  6275. tx.Rollback()
  6276. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6277. return
  6278. }
  6279. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6280. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6281. if err != nil {
  6282. logs.Error("UpdateDailyData-error-12:", err)
  6283. tx.Rollback()
  6284. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6285. return
  6286. }
  6287. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6288. where pid = ? `, pid).Execute()
  6289. if err != nil {
  6290. logs.Error("UpdateDailyData-error-13:", err)
  6291. tx.Rollback()
  6292. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6293. return
  6294. }
  6295. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6296. if err != nil {
  6297. logs.Error("UpdateDailyData-error-14:", err)
  6298. tx.Rollback()
  6299. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6300. return
  6301. }
  6302. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6303. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6304. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6305. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6306. if err != nil {
  6307. fmt.Println("Error:", err)
  6308. return
  6309. }
  6310. for _, item := range downloadedplanList {
  6311. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6312. if err != nil {
  6313. fmt.Println("Error:", err)
  6314. return
  6315. }
  6316. actual := itemLweight / lweight * actualWeight
  6317. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6318. if err != nil {
  6319. logs.Error("UpdateDailyData-error-6:", err)
  6320. tx.Rollback()
  6321. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6322. return
  6323. }
  6324. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6325. if err != nil {
  6326. logs.Error("UpdateDailyData-error-7:", err)
  6327. tx.Rollback()
  6328. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6329. return
  6330. }
  6331. _, 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()
  6332. if err != nil {
  6333. logs.Error("UpdateDailyData-error-8:", err)
  6334. tx.Rollback()
  6335. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6336. return
  6337. }
  6338. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6339. if err != nil {
  6340. logs.Error("UpdateDailyData-error-9:", err)
  6341. tx.Rollback()
  6342. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6343. return
  6344. }
  6345. }
  6346. } else {
  6347. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6348. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6349. for _, item := range downloadedplanList {
  6350. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6351. // if err != nil {
  6352. // fmt.Println("Error:", err)
  6353. // return
  6354. // }
  6355. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6356. if err != nil {
  6357. logs.Error("UpdateDailyData-error-6:", err)
  6358. tx.Rollback()
  6359. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6360. return
  6361. }
  6362. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6363. item["lweight"], actualWeight, item["id"]).Execute()
  6364. if err != nil {
  6365. logs.Error("UpdateDailyData-error-7:", err)
  6366. tx.Rollback()
  6367. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6368. return
  6369. }
  6370. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6371. where pid = ?`, item["id"]).Execute()
  6372. if err != nil {
  6373. logs.Error("UpdateDailyData-error-8:", err)
  6374. tx.Rollback()
  6375. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6376. return
  6377. }
  6378. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6379. if err != nil {
  6380. logs.Error("UpdateDailyData-error-9:", err)
  6381. tx.Rollback()
  6382. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6383. return
  6384. }
  6385. }
  6386. }
  6387. }
  6388. err := tx.Commit()
  6389. if err != nil {
  6390. logs.Error("UpdateDailyData-error-20:", err)
  6391. tx.Rollback()
  6392. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6393. return
  6394. }
  6395. appG.Response(http.StatusOK, e.SUCCESS, true)
  6396. }
  6397. func GetFormulaStatistics(c *gin.Context) {
  6398. appG := app.Gin{C: c}
  6399. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6400. parammaps := gofasion.NewFasion(string(dataByte))
  6401. startTime := parammaps.Get("startTime").ValueStr()
  6402. endTime := parammaps.Get("endTime").ValueStr()
  6403. pastureId := parammaps.Get("pastureId").ValueStr()
  6404. tx := restful.Engine.NewSession()
  6405. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6406. if err != nil {
  6407. logs.Error("GetFormulaStatistics-error-1:", err)
  6408. tx.Rollback()
  6409. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6410. return
  6411. }
  6412. var feedtemplet, dateList []string
  6413. for _, f := range feedtempletList {
  6414. feedtemplet = append(feedtemplet, f["tname"].(string))
  6415. }
  6416. layout := "2006-01-02"
  6417. // s := "2023-05-01"
  6418. // e := "2023-05-23"
  6419. start, err := time.Parse(layout, startTime)
  6420. if err != nil {
  6421. fmt.Println(err)
  6422. return
  6423. }
  6424. end, err := time.Parse(layout, endTime)
  6425. if err != nil {
  6426. fmt.Println(err)
  6427. return
  6428. }
  6429. end = end.AddDate(0, 0, 1)
  6430. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6431. dateList = append(dateList, d.Format("2006-01-02"))
  6432. }
  6433. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6434. join feedtemplet ft on ft.id = d.tempid where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  6435. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6436. if err != nil {
  6437. logs.Error("GetFormulaStatistics-error-2:", err)
  6438. tx.Rollback()
  6439. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6440. return
  6441. }
  6442. var data2 [][]interface{}
  6443. for _, f := range feedtemplet {
  6444. var data1 []interface{}
  6445. for _, date := range dateList {
  6446. exist := false
  6447. for _, item := range downloadedplanList {
  6448. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6449. data1 = append(data1, item["total"])
  6450. exist = true
  6451. break
  6452. }
  6453. }
  6454. if !exist {
  6455. data1 = append(data1, 0)
  6456. }
  6457. }
  6458. data2 = append(data2, data1)
  6459. }
  6460. //前端让加的
  6461. feedtemplet = append(feedtemplet, "")
  6462. {
  6463. var data1 []interface{}
  6464. for _, f := range dateList {
  6465. // f = f + "\n"
  6466. fmt.Println(f)
  6467. data1 = append(data1, 0)
  6468. }
  6469. data2 = append(data2, data1)
  6470. }
  6471. resp := make(map[string]interface{}, 0)
  6472. resp["xdata"] = dateList
  6473. resp["data1"] = feedtemplet
  6474. resp["data2"] = data2
  6475. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6476. }
  6477. func GetPlanData(c *gin.Context) {
  6478. appG := app.Gin{C: c}
  6479. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6480. fsion := gofasion.NewFasion(string(dataByte))
  6481. sqlnamestr := fsion.Get("name").ValueStr()
  6482. sqlnamestr1 := fsion.Get("name1").ValueStr()
  6483. offset := fsion.Get("offset").ValueDefaultInt(0)
  6484. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  6485. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6486. month := fsion.Get("month").ValueDefaultStr("map")
  6487. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  6488. tx := restful.Engine.NewSession()
  6489. err := tx.Begin()
  6490. defer func() {
  6491. switch {
  6492. case err != nil:
  6493. if tx != nil {
  6494. tx.Rollback()
  6495. }
  6496. default:
  6497. if tx != nil {
  6498. err = tx.Commit()
  6499. }
  6500. }
  6501. if tx != nil {
  6502. tx.Close()
  6503. }
  6504. }()
  6505. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6506. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  6507. if sql != "" {
  6508. s_params := make([]interface{}, 0)
  6509. if fsion.HasKey("parammaps") {
  6510. parammaps := fsion.Get("parammaps")
  6511. paramslist := strings.Split(p, ",")
  6512. if len(paramslist) > 0 && p != "" {
  6513. for _, value := range paramslist {
  6514. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6515. if tempv, exists := c.Get("jwt_username"); exists {
  6516. s_params = append(s_params, tempv.(string))
  6517. } else {
  6518. s_params = append(s_params, "")
  6519. }
  6520. } else {
  6521. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6522. }
  6523. }
  6524. }
  6525. }
  6526. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6527. if err != nil {
  6528. appG.Response(http.StatusOK, e.ERROR, err.Error())
  6529. } else {
  6530. paramslist1 := strings.Split(p1, ",")
  6531. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6532. s_params1 := make([]interface{}, 0)
  6533. if len(paramslist1) > 0 && p1 != "" {
  6534. for _, v := range paramslist1 {
  6535. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  6536. }
  6537. }
  6538. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  6539. for _, item := range arr {
  6540. trgaddressList := []string{}
  6541. if _, ok := item["trgaddress"]; ok {
  6542. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6543. for _, str := range trgaddressList1 {
  6544. if str != "" {
  6545. trgaddressList = append(trgaddressList, str)
  6546. }
  6547. }
  6548. }
  6549. item["trgaddressList"] = trgaddressList
  6550. }
  6551. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  6552. }
  6553. // var wg sync.WaitGroup
  6554. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6555. // wg.Add(1)
  6556. // go func(value map[string]interface{}) {
  6557. // defer wg.Done()
  6558. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  6559. // }(value)
  6560. // }
  6561. // wg.Wait()
  6562. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6563. }
  6564. } else {
  6565. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6566. }
  6567. }
  6568. func PostPlanData(c *gin.Context) {
  6569. appG := app.Gin{C: c}
  6570. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6571. fsion := gofasion.NewFasion(string(dataByte))
  6572. logging.Info("PostRJSBData err: ", string(dataByte))
  6573. s_params := make([]interface{}, 0)
  6574. tx := restful.Engine.NewSession()
  6575. err := tx.Begin()
  6576. defer func() {
  6577. switch {
  6578. case err != nil:
  6579. if tx != nil {
  6580. tx.Rollback()
  6581. }
  6582. default:
  6583. if tx != nil {
  6584. err = tx.Commit()
  6585. }
  6586. }
  6587. if tx != nil {
  6588. tx.Close()
  6589. }
  6590. }()
  6591. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  6592. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  6593. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  6594. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  6595. if !fsion.HasKey("parammaps") {
  6596. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  6597. return
  6598. }
  6599. parammaps := fsion.Get("parammaps")
  6600. paramslist := strings.Split(p, ",")
  6601. if len(paramslist) > 0 && p != "" {
  6602. for _, value := range paramslist {
  6603. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6604. }
  6605. }
  6606. _, err = tx.SQL(sql, s_params...).Execute()
  6607. if err != nil {
  6608. logging.Error("PostRJSBData err: ", err)
  6609. msg := geterrmsg(err.Error())
  6610. appG.Response(http.StatusOK, e.ERROR, msg)
  6611. return
  6612. }
  6613. s_params = make([]interface{}, 0)
  6614. paramslist = strings.Split(p1, ",")
  6615. if len(paramslist) > 0 && p1 != "" {
  6616. for _, value := range paramslist {
  6617. // if value == "ID" {
  6618. // id := parammaps.Get("ID").ValueStr()
  6619. // pastureid := parammaps.Get("pastureid").ValueStr()
  6620. // 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
  6621. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6622. // if err != nil {
  6623. // logging.Error("PostRJSBData err: ", err)
  6624. // msg := geterrmsg(err.Error())
  6625. // appG.Response(http.StatusOK, e.ERROR, msg)
  6626. // return
  6627. // }
  6628. // for _, item := range datalist {
  6629. // id = item["id"]
  6630. // }
  6631. // s_params = append(s_params, id)
  6632. // } else {
  6633. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6634. // }
  6635. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6636. }
  6637. }
  6638. _, err = tx.SQL(sql1, s_params...).Execute()
  6639. if err != nil {
  6640. logging.Error("PostRJSBData1 err: ", err)
  6641. msg := geterrmsg(err.Error())
  6642. appG.Response(http.StatusOK, e.ERROR, msg)
  6643. return
  6644. }
  6645. s_params = make([]interface{}, 0)
  6646. paramslist = strings.Split(p2, ",")
  6647. if len(paramslist) > 0 && p2 != "" {
  6648. for _, value := range paramslist {
  6649. if value == "ID" {
  6650. id := parammaps.Get("ID").ValueStr()
  6651. pastureid := parammaps.Get("pastureid").ValueStr()
  6652. 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
  6653. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6654. if err != nil {
  6655. logging.Error("PostRJSBData err: ", err)
  6656. msg := geterrmsg(err.Error())
  6657. appG.Response(http.StatusOK, e.ERROR, msg)
  6658. return
  6659. }
  6660. for _, item := range datalist {
  6661. id = item["id"]
  6662. }
  6663. s_params = append(s_params, id)
  6664. } else {
  6665. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6666. }
  6667. }
  6668. }
  6669. _, err = tx.SQL(sql2, s_params...).Execute()
  6670. if err != nil {
  6671. logging.Error("PostRJSBData2 err: ", err)
  6672. msg := geterrmsg(err.Error())
  6673. appG.Response(http.StatusOK, e.ERROR, msg)
  6674. return
  6675. }
  6676. s_params = make([]interface{}, 0)
  6677. paramslist = strings.Split(p3, ",")
  6678. if len(paramslist) > 0 && p3 != "" {
  6679. for _, value := range paramslist {
  6680. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6681. }
  6682. }
  6683. _, err = tx.SQL(sql3, s_params...).Execute()
  6684. if err != nil {
  6685. logging.Error("PostRJSBData3 err: ", err)
  6686. msg := geterrmsg(err.Error())
  6687. appG.Response(http.StatusOK, e.ERROR, msg)
  6688. return
  6689. }
  6690. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6691. }
  6692. func CheckFeedTrgaddress(c *gin.Context) {
  6693. appG := app.Gin{C: c}
  6694. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6695. fsion := gofasion.NewFasion(string(dataByte))
  6696. fclassid := fsion.Get("fclassid").ValueStr()
  6697. feedId := fsion.Get("feedId").ValueStr()
  6698. backup1 := fsion.Get("backup1").ValueStr()
  6699. backup1List := strings.Split(backup1, ",")
  6700. tx := restful.Engine.NewSession()
  6701. defer tx.Close()
  6702. // if backup1 != "" {
  6703. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  6704. for _, feed := range feedList {
  6705. if feed["backup1"] == "" {
  6706. continue
  6707. }
  6708. feedbackupList := strings.Split(feed["backup1"], ",")
  6709. for _, feedbackup := range feedbackupList {
  6710. for _, backup := range backup1List {
  6711. if feedbackup == backup {
  6712. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  6713. return
  6714. }
  6715. }
  6716. }
  6717. }
  6718. // }
  6719. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6720. }
  6721. func ThiGetDataByName(c *gin.Context) {
  6722. appG := app.Gin{C: c}
  6723. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6724. fsion := gofasion.NewFasion(string(dataByte))
  6725. sqlnamestr := fsion.Get("name").ValueStr()
  6726. offset := fsion.Get("offset").ValueDefaultInt(0)
  6727. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  6728. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6729. tx := restful.Engine.NewSession()
  6730. err := tx.Begin()
  6731. defer func() {
  6732. switch {
  6733. case err != nil:
  6734. logging.Error("tx.Begin 事务启动失败__error:", err)
  6735. if tx != nil {
  6736. tx.Rollback()
  6737. }
  6738. default:
  6739. if tx != nil {
  6740. err = tx.Commit()
  6741. }
  6742. }
  6743. if tx != nil {
  6744. tx.Close()
  6745. }
  6746. }()
  6747. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6748. if sql != "" {
  6749. s_params := make([]interface{}, 0)
  6750. if fsion.HasKey("parammaps") {
  6751. parammaps := fsion.Get("parammaps")
  6752. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  6753. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  6754. }
  6755. paramslist := strings.Split(p, ",")
  6756. if len(paramslist) > 0 && p != "" {
  6757. for _, value := range paramslist {
  6758. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6759. if tempv, exists := c.Get("jwt_username"); exists {
  6760. s_params = append(s_params, tempv.(string))
  6761. } else {
  6762. s_params = append(s_params, "")
  6763. }
  6764. } else {
  6765. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6766. }
  6767. }
  6768. }
  6769. } else if fsion.HasKey("params") {
  6770. params := fsion.Get("params").Array()
  6771. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  6772. for _, v_params := range params {
  6773. s_params = append(s_params, v_params.ValueStr())
  6774. }
  6775. }
  6776. if returntype == "xlsx" {
  6777. var xlsxfile *xlsx.File
  6778. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  6779. //c.File("c:/dd.xlsx")
  6780. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  6781. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  6782. c.Header("Content-Transfer-Encoding", "binary")
  6783. _ = xlsxfile.Write(c.Writer)
  6784. } else {
  6785. if sqlnamestr == "getHomepageStr" {
  6786. parammaps := fsion.Get("parammaps")
  6787. pastureid := parammaps.Get("pastureid").ValueStr()
  6788. var montimeList []float64
  6789. var montime float64
  6790. var wg sync.WaitGroup
  6791. now := time.Now()
  6792. for i := 0; i < 30; i++ {
  6793. wg.Add(1)
  6794. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  6795. go func(nowstr string) {
  6796. defer wg.Done()
  6797. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  6798. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  6799. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  6800. montimeList = append(montimeList, m)
  6801. }(nowstr)
  6802. }
  6803. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6804. if err != nil {
  6805. logging.Error("GetDataByName err: ", err)
  6806. msg := geterrmsg(err.Error())
  6807. appG.Response(http.StatusOK, e.ERROR, msg)
  6808. }
  6809. wg.Wait()
  6810. for _, m := range montimeList {
  6811. montime += m
  6812. }
  6813. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  6814. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6815. return
  6816. }
  6817. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6818. if err != nil {
  6819. logging.Error("GetDataByName err: ", err)
  6820. msg := geterrmsg(err.Error())
  6821. appG.Response(http.StatusOK, e.ERROR, msg)
  6822. } else {
  6823. if sqlnamestr == "getFeedTrgaddressList" {
  6824. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6825. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6826. trgaddressList := []string{}
  6827. for _, str := range trgaddressList1 {
  6828. if str != "" {
  6829. trgaddressList = append(trgaddressList, str)
  6830. }
  6831. }
  6832. item["trgaddressList"] = trgaddressList
  6833. }
  6834. }
  6835. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6836. }
  6837. }
  6838. } else {
  6839. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6840. }
  6841. }
  6842. // func ToggleCcount(c *gin.Context) {
  6843. // appG := app.Gin{C: c}
  6844. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6845. // fsion := gofasion.NewFasion(string(dataByte))
  6846. // // 0 实际 1 软件
  6847. // status := fsion.Get("status").ValueDefaultInt64(0)
  6848. // pastureId := fsion.Get("pastureId").ValueStr()
  6849. // tx := restful.Engine.NewSession()
  6850. // err := tx.Begin()
  6851. // defer func() {
  6852. // switch {
  6853. // case err != nil:
  6854. // logging.Error("tx.Begin 事务启动失败__error:", err)
  6855. // if tx != nil {
  6856. // tx.Rollback()
  6857. // }
  6858. // default:
  6859. // if tx != nil {
  6860. // err = tx.Commit()
  6861. // }
  6862. // }
  6863. // if tx != nil {
  6864. // tx.Close()
  6865. // }
  6866. // }()
  6867. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  6868. // if err != nil {
  6869. // logs.Error(err)
  6870. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6871. // return
  6872. // }
  6873. // for _, bar := range barList {
  6874. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  6875. // if err != nil {
  6876. // logs.Error(err)
  6877. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6878. // return
  6879. // }
  6880. // if !exist {
  6881. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  6882. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  6883. // if err != nil {
  6884. // logs.Error(err)
  6885. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6886. // return
  6887. // }
  6888. // }
  6889. // }
  6890. // if status == 0 {
  6891. // tx.Exec(`update feedp set ccount = actualcount `)
  6892. // }else{
  6893. // tx.Exec(`update feedp set ccount = softccount `)
  6894. // }
  6895. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  6896. // if err != nil {
  6897. // logs.Error(err)
  6898. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6899. // return
  6900. // }
  6901. // for _, feedpData :=range feedpList{
  6902. // var feedpargs []interface{}
  6903. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  6904. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  6905. // if _, ok := feedpData["ftname"]; ok {
  6906. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  6907. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  6908. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  6909. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  6910. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6911. // } else {
  6912. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  6913. // }
  6914. // if _, ok := feedpData["ptsfname"]; ok {
  6915. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  6916. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  6917. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  6918. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  6919. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6920. // } else {
  6921. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  6922. // }
  6923. // upFeedpSql += " where barname = ? and pastureid = ? "
  6924. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  6925. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  6926. // if err != nil {
  6927. // logs.Error(err)
  6928. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6929. // return
  6930. // }
  6931. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  6932. // if err != nil {
  6933. // logs.Error(err)
  6934. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6935. // return
  6936. // }
  6937. // if !exist1 {
  6938. // _, 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) `,
  6939. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6940. // if err != nil {
  6941. // logs.Error(err)
  6942. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6943. // return
  6944. // }
  6945. // }
  6946. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  6947. // if err != nil {
  6948. // logs.Error(err)
  6949. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6950. // return
  6951. // }
  6952. // if !exist2 {
  6953. // _, 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) `,
  6954. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6955. // if err != nil {
  6956. // logs.Error(err)
  6957. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6958. // return
  6959. // }
  6960. // }
  6961. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  6962. // if err != nil {
  6963. // logs.Error(err)
  6964. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6965. // return
  6966. // }
  6967. // if !exist3 {
  6968. // _, 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) `,
  6969. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6970. // if err != nil {
  6971. // logs.Error(err)
  6972. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6973. // return
  6974. // }
  6975. // }
  6976. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  6977. // if err != nil {
  6978. // logs.Error(err)
  6979. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6980. // return
  6981. // }
  6982. // if !exist4 {
  6983. // _, 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) `,
  6984. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6985. // if err != nil {
  6986. // logs.Error(err)
  6987. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6988. // return
  6989. // }
  6990. // }
  6991. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  6992. // if err != nil {
  6993. // logs.Error(err)
  6994. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6995. // return
  6996. // }
  6997. // if !exist5 {
  6998. // _, 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) `,
  6999. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7000. // if err != nil {
  7001. // logs.Error(err)
  7002. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7003. // return
  7004. // }
  7005. // }
  7006. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7007. // if err != nil {
  7008. // logs.Error(err)
  7009. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7010. // return
  7011. // }
  7012. // if !exist6 {
  7013. // _, 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) `,
  7014. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7015. // if err != nil {
  7016. // logs.Error(err)
  7017. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7018. // return
  7019. // }
  7020. // }
  7021. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7022. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7023. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7024. // and pastureid = ? and times = ?`
  7025. // var fpdargs1 []interface{}
  7026. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7027. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7028. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7029. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7030. // if err != nil {
  7031. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7032. // return
  7033. // }
  7034. // var fpdargs2 []interface{}
  7035. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7036. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7037. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7038. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7039. // if err != nil {
  7040. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7041. // return
  7042. // }
  7043. // var fpdargs3 []interface{}
  7044. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7045. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7046. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7047. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7048. // if err != nil {
  7049. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7050. // return
  7051. // }
  7052. // var fpdargs4 []interface{}
  7053. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7054. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7055. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7056. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7057. // if err != nil {
  7058. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7059. // return
  7060. // }
  7061. // var fpdargs5 []interface{}
  7062. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7063. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7064. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7065. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7066. // if err != nil {
  7067. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7068. // return
  7069. // }
  7070. // var fpdargs6 []interface{}
  7071. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7072. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7073. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7074. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7075. // if err != nil {
  7076. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7077. // return
  7078. // }
  7079. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7080. // 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()
  7081. // if err != nil {
  7082. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7083. // return
  7084. // }
  7085. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7086. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7087. // upFpdetailList := make([]*upFpdetail, 0)
  7088. // for _, newfpd := range newList {
  7089. // for _, oldfpd := range oldFpdList {
  7090. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7091. // var oldweight, newweight float64
  7092. // if oldfpd["weight"] != nil {
  7093. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7094. // }
  7095. // if newfpd["weight"] != nil {
  7096. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7097. // }
  7098. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7099. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7100. // Old: oldweight,
  7101. // New: newweight,
  7102. // Times: newfpd["times"].(int64),
  7103. // Ptid: newfpd["ptid"].(int64),
  7104. // Fweight: fweight,
  7105. // Id: oldfpd["id"].(int64),
  7106. // })
  7107. // break
  7108. // }
  7109. // }
  7110. // }
  7111. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7112. // }
  7113. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7114. // }
  7115. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7116. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7117. if err != nil {
  7118. return err
  7119. }
  7120. for _, item := range feedpList {
  7121. // if item["ftid"].(string) != data["ftid"].(string) {
  7122. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7123. if err != nil {
  7124. return err
  7125. }
  7126. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7127. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7128. if err != nil {
  7129. return err
  7130. }
  7131. // }
  7132. }
  7133. return nil
  7134. }
  7135. func PostPlanDatas(c *gin.Context) {
  7136. appG := app.Gin{C: c}
  7137. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7138. fsions := gofasion.NewFasion(string(dataByte))
  7139. logging.Info("PostRJSBDatas err: ", string(dataByte))
  7140. tx := restful.Engine.NewSession()
  7141. err := tx.Begin()
  7142. defer func() {
  7143. switch {
  7144. case err != nil:
  7145. if tx != nil {
  7146. tx.Rollback()
  7147. }
  7148. default:
  7149. if tx != nil {
  7150. err = tx.Commit()
  7151. }
  7152. }
  7153. if tx != nil {
  7154. tx.Close()
  7155. }
  7156. }()
  7157. pastureId := fsions.Get("pastureid").ValueStr()
  7158. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7159. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  7160. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  7161. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  7162. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7163. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  7164. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  7165. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  7166. for _, parammaps := range fsions.Get("arrList").Array() {
  7167. // if !fsion.HasKey("arrList") {
  7168. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7169. // return
  7170. // }
  7171. // parammaps := fsion.Get("arrList")
  7172. s_params := make([]interface{}, 0)
  7173. paramslist := strings.Split(p, ",")
  7174. if len(paramslist) > 0 && p != "" {
  7175. for _, value := range paramslist {
  7176. if value == "pastureid" {
  7177. s_params = append(s_params, pastureId)
  7178. } else {
  7179. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7180. }
  7181. }
  7182. }
  7183. _, err = tx.SQL(sql, s_params...).Execute()
  7184. if err != nil {
  7185. logging.Error("PostRJSBData err: ", err)
  7186. msg := geterrmsg(err.Error())
  7187. appG.Response(http.StatusOK, e.ERROR, msg)
  7188. return
  7189. }
  7190. s_params = make([]interface{}, 0)
  7191. paramslist = strings.Split(p1, ",")
  7192. if len(paramslist) > 0 && p1 != "" {
  7193. for _, value := range paramslist {
  7194. // if value == "ID" {
  7195. // id := parammaps.Get("ID").ValueStr()
  7196. // pastureid := parammaps.Get("pastureid").ValueStr()
  7197. // 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
  7198. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7199. // if err != nil {
  7200. // logging.Error("PostRJSBData err: ", err)
  7201. // msg := geterrmsg(err.Error())
  7202. // appG.Response(http.StatusOK, e.ERROR, msg)
  7203. // return
  7204. // }
  7205. // for _, item := range datalist {
  7206. // id = item["id"]
  7207. // }
  7208. // s_params = append(s_params, id)
  7209. // } else {
  7210. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7211. // }
  7212. if value == "pastureid" {
  7213. s_params = append(s_params, pastureId)
  7214. } else {
  7215. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7216. }
  7217. }
  7218. }
  7219. _, err = tx.SQL(sql1, s_params...).Execute()
  7220. if err != nil {
  7221. logging.Error("PostRJSBData1 err: ", err)
  7222. msg := geterrmsg(err.Error())
  7223. appG.Response(http.StatusOK, e.ERROR, msg)
  7224. return
  7225. }
  7226. s_params = make([]interface{}, 0)
  7227. paramslist = strings.Split(p2, ",")
  7228. if len(paramslist) > 0 && p2 != "" {
  7229. for _, value := range paramslist {
  7230. if value == "ID" {
  7231. id := parammaps.Get("ID").ValueStr()
  7232. pastureid := parammaps.Get("pastureid").ValueStr()
  7233. 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
  7234. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7235. if err != nil {
  7236. logging.Error("PostRJSBData err: ", err)
  7237. msg := geterrmsg(err.Error())
  7238. appG.Response(http.StatusOK, e.ERROR, msg)
  7239. return
  7240. }
  7241. for _, item := range datalist {
  7242. id = item["id"]
  7243. }
  7244. s_params = append(s_params, id)
  7245. } else if value == "pastureid" {
  7246. s_params = append(s_params, pastureId)
  7247. } else {
  7248. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7249. }
  7250. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7251. }
  7252. }
  7253. _, err = tx.SQL(sql2, s_params...).Execute()
  7254. if err != nil {
  7255. logging.Error("PostRJSBData2 err: ", err)
  7256. msg := geterrmsg(err.Error())
  7257. appG.Response(http.StatusOK, e.ERROR, msg)
  7258. return
  7259. }
  7260. s_params = make([]interface{}, 0)
  7261. paramslist = strings.Split(p3, ",")
  7262. if len(paramslist) > 0 && p3 != "" {
  7263. for _, value := range paramslist {
  7264. if value == "pastureid" {
  7265. s_params = append(s_params, pastureId)
  7266. } else {
  7267. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7268. }
  7269. }
  7270. }
  7271. _, err = tx.SQL(sql3, s_params...).Execute()
  7272. if err != nil {
  7273. logging.Error("PostRJSBData3 err: ", err)
  7274. msg := geterrmsg(err.Error())
  7275. appG.Response(http.StatusOK, e.ERROR, msg)
  7276. return
  7277. }
  7278. }
  7279. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7280. }
  7281. func FpdBatchEdit(c *gin.Context) {
  7282. appG := app.Gin{C: c}
  7283. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7284. fsions := gofasion.NewFasion(string(dataByte))
  7285. barList := fsions.Get("barList").Array()
  7286. pastureid := fsions.Get("pastureId").ValueStr()
  7287. tx := restful.Engine.NewSession()
  7288. defer tx.Close()
  7289. 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
  7290. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7291. if err != nil {
  7292. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7293. return
  7294. }
  7295. for _, barFsions := range barList {
  7296. dataexcel := make(map[string]interface{}, 0)
  7297. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  7298. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  7299. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  7300. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  7301. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  7302. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  7303. continue
  7304. }
  7305. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  7306. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  7307. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  7308. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  7309. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  7310. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  7311. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  7312. if err != nil {
  7313. logs.Error(err)
  7314. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7315. return
  7316. }
  7317. if !ftexist {
  7318. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  7319. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7320. if err != nil {
  7321. logs.Error(err)
  7322. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7323. return
  7324. }
  7325. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7326. if err != nil {
  7327. logs.Error(err)
  7328. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7329. return
  7330. }
  7331. }
  7332. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7333. if err != nil {
  7334. logs.Error(err)
  7335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7336. return
  7337. }
  7338. if !exist {
  7339. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7340. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  7341. if err != nil {
  7342. logs.Error(err)
  7343. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7344. return
  7345. }
  7346. }
  7347. var feedpargs []interface{}
  7348. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7349. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  7350. if _, ok := dataexcel["ftname"]; ok {
  7351. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  7352. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7353. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7354. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7355. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  7356. } else {
  7357. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7358. }
  7359. if _, ok := dataexcel["ptsfname"]; ok {
  7360. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  7361. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7362. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7363. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7364. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  7365. } else {
  7366. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7367. }
  7368. upFeedpSql += " where barname = ? and pastureid = ? "
  7369. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  7370. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7371. if err != nil {
  7372. logs.Error(err)
  7373. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7374. return
  7375. }
  7376. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  7377. if err != nil {
  7378. logs.Error(err)
  7379. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7380. return
  7381. }
  7382. if !exist1 {
  7383. _, 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) `,
  7384. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7385. if err != nil {
  7386. logs.Error(err)
  7387. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7388. return
  7389. }
  7390. }
  7391. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  7392. if err != nil {
  7393. logs.Error(err)
  7394. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7395. return
  7396. }
  7397. if !exist2 {
  7398. _, 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) `,
  7399. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7400. if err != nil {
  7401. logs.Error(err)
  7402. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7403. return
  7404. }
  7405. }
  7406. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  7407. if err != nil {
  7408. logs.Error(err)
  7409. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7410. return
  7411. }
  7412. if !exist3 {
  7413. _, 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) `,
  7414. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7415. if err != nil {
  7416. logs.Error(err)
  7417. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7418. return
  7419. }
  7420. }
  7421. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  7422. if err != nil {
  7423. logs.Error(err)
  7424. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7425. return
  7426. }
  7427. if !exist4 {
  7428. _, 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) `,
  7429. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7430. if err != nil {
  7431. logs.Error(err)
  7432. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7433. return
  7434. }
  7435. }
  7436. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  7437. if err != nil {
  7438. logs.Error(err)
  7439. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7440. return
  7441. }
  7442. if !exist5 {
  7443. _, 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) `,
  7444. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7445. if err != nil {
  7446. logs.Error(err)
  7447. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7448. return
  7449. }
  7450. }
  7451. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, 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 !exist6 {
  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 = ? ),?,6,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. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7467. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7468. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7469. and pastureid = ? and times = ?`
  7470. var fpdargs1 []interface{}
  7471. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7472. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7473. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7474. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7475. if err != nil {
  7476. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7477. return
  7478. }
  7479. var fpdargs2 []interface{}
  7480. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7481. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7482. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7483. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7484. if err != nil {
  7485. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7486. return
  7487. }
  7488. var fpdargs3 []interface{}
  7489. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7490. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7491. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7492. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7493. if err != nil {
  7494. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7495. return
  7496. }
  7497. var fpdargs4 []interface{}
  7498. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7499. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7500. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7501. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7502. if err != nil {
  7503. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7504. return
  7505. }
  7506. var fpdargs5 []interface{}
  7507. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7508. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7509. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7510. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7511. if err != nil {
  7512. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7513. return
  7514. }
  7515. var fpdargs6 []interface{}
  7516. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7517. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7518. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7519. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7520. if err != nil {
  7521. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7522. return
  7523. }
  7524. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7525. 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()
  7526. if err != nil {
  7527. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7528. return
  7529. }
  7530. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7531. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7532. upFpdetailList := make([]*upFpdetail, 0)
  7533. for _, newfpd := range newList {
  7534. for _, oldfpd := range oldFpdList {
  7535. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7536. var oldweight, newweight float64
  7537. if oldfpd["weight"] != nil {
  7538. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7539. }
  7540. if newfpd["weight"] != nil {
  7541. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7542. }
  7543. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7544. upFpdetailList = append(upFpdetailList, &upFpdetail{
  7545. Old: oldweight,
  7546. New: newweight,
  7547. Times: newfpd["times"].(int64),
  7548. Ptid: newfpd["ptid"].(int64),
  7549. Fweight: fweight,
  7550. Id: oldfpd["id"].(int64),
  7551. })
  7552. break
  7553. }
  7554. }
  7555. }
  7556. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  7557. }
  7558. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7559. }
  7560. func UdBarSync(c *gin.Context) {
  7561. appG := app.Gin{C: c}
  7562. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7563. fsions := gofasion.NewFasion(string(dataByte))
  7564. pastureid := fsions.Get("pastureId").ValueStr()
  7565. tx := restful.Engine.NewSession()
  7566. defer tx.Close()
  7567. pastureinfo := new(udPastureInfo)
  7568. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  7569. if err != nil {
  7570. logs.Error(err)
  7571. return
  7572. }
  7573. gm.UdBarSync(pastureid, pastureinfo.Werks)
  7574. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7575. }
  7576. func UdFeedSync(c *gin.Context) {
  7577. appG := app.Gin{C: c}
  7578. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7579. fsions := gofasion.NewFasion(string(dataByte))
  7580. pastureid := fsions.Get("pastureId").ValueStr()
  7581. tx := restful.Engine.NewSession()
  7582. defer tx.Close()
  7583. pastureinfo := new(udPastureInfo)
  7584. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7585. if err != nil {
  7586. logs.Error(err)
  7587. return
  7588. }
  7589. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  7590. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7591. }
  7592. func UdFeedtempletPush(c *gin.Context) {
  7593. appG := app.Gin{C: c}
  7594. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7595. fsions := gofasion.NewFasion(string(dataByte))
  7596. pastureid := fsions.Get("pastureId").ValueStr()
  7597. tx := restful.Engine.NewSession()
  7598. defer tx.Close()
  7599. pastureinfo := new(udPastureInfo)
  7600. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7601. if err != nil {
  7602. logs.Error(err)
  7603. return
  7604. }
  7605. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks)
  7606. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7607. }
  7608. func UdUtirPush(c *gin.Context) {
  7609. appG := app.Gin{C: c}
  7610. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7611. fsions := gofasion.NewFasion(string(dataByte))
  7612. pastureid := fsions.Get("pastureId").ValueStr()
  7613. date := fsions.Get("date").ValueStr()
  7614. tx := restful.Engine.NewSession()
  7615. defer tx.Close()
  7616. pastureinfo := new(udPastureInfo)
  7617. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7618. if err != nil {
  7619. logs.Error(err)
  7620. return
  7621. }
  7622. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  7623. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7624. }
  7625. func UdBarFeedRemainPush(c *gin.Context) {
  7626. appG := app.Gin{C: c}
  7627. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7628. fsions := gofasion.NewFasion(string(dataByte))
  7629. pastureid := fsions.Get("pastureId").ValueStr()
  7630. date := fsions.Get("date").ValueStr()
  7631. tx := restful.Engine.NewSession()
  7632. defer tx.Close()
  7633. pastureinfo := new(udPastureInfo)
  7634. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7635. if err != nil {
  7636. logs.Error(err)
  7637. return
  7638. }
  7639. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  7640. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7641. }
  7642. func UdMaterialIssuePush(c *gin.Context) {
  7643. appG := app.Gin{C: c}
  7644. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7645. fsions := gofasion.NewFasion(string(dataByte))
  7646. pastureid := fsions.Get("pastureId").ValueStr()
  7647. date := fsions.Get("date").ValueStr()
  7648. tx := restful.Engine.NewSession()
  7649. defer tx.Close()
  7650. pastureinfo := new(udPastureInfo)
  7651. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7652. if err != nil {
  7653. logs.Error(err)
  7654. return
  7655. }
  7656. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  7657. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7658. }