db.go 233 KB

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