ops.go 265 KB

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