12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876 |
- package api
- import (
- "bytes"
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "path"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- "tmr-watch/conf/setting"
- "tmr-watch/http/handle/gm"
- "tmr-watch/http/handle/restful"
- "tmr-watch/module"
- "tmr-watch/pkg/app"
- "tmr-watch/pkg/e"
- "tmr-watch/pkg/logging"
- "github.com/360EntSecGroup-Skylar/excelize"
- "github.com/Anderson-Lu/gofasion/gofasion"
- "github.com/astaxie/beego/logs"
- "github.com/gin-gonic/gin"
- "github.com/qichengzx/coordtransform"
- "github.com/tealeg/xlsx"
- "github.com/xormplus/xorm"
- )
- // @Summary 根据SQL执行得到数据集
- // @Tags getData
- // @Accept json
- // @Produce json
- // @Param sql query string true "sql"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/getdata [POST]
- func GetData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func Testpartitions(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
- user := fsion.Get("user").ValueStr() //获取新数据库用户
- passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
- host := fsion.Get("host").ValueStr() //获取新数据库名称
- port := fsion.Get("port").ValueStr() //获取新数据库名称
- sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
- if sqls == nil || err1 != nil {
- appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
- }
- sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
- connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
- mydb, err := sql.Open("mysql", connecting) //连接新连接
- if err != nil {
- println("err1", err.Error())
- }
- _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
- if err != nil {
- println("err2", err.Error())
- }
- mydb.Close()
- connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
- mydb, err = sql.Open("mysql", connecting)
- if err != nil {
- println("err3", err.Error())
- }
- defer mydb.Close()
- if err == nil {
- mydb.SetMaxOpenConns(10)
- mydb.SetMaxIdleConns(10)
- }
- errmsg := ""
- if err == nil {
- //tx ,_ :=mydb.Begin()
- for _, sqlstr := range sqlstrs {
- //println("sqlstr---",sqlstr)
- if sqlstr == "" {
- continue
- }
- _, err = mydb.Exec(sqlstr)
- if err != nil {
- println("err4", err.Error())
- errmsg = err.Error()
- //err1 :=tx.Rollback()
- }
- }
- //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
- //err =tx.Commit()
- }
- if errmsg == "" {
- appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
- }
- }
- func TestData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- token := ""
- if tempv, exists := c.Get("jwt_username"); exists {
- token = tempv.(string)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
- // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
- // tmrNameList := []string{}
- // for _, tmr := range tmrArray {
- // tmrNameList = append(tmrNameList, tmr.ValueStr())
- // }
- // s_params = append(s_params, strings.Join(tmrNameList, ","))
- // } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- if sqlnamestr == "getHomepageStr" {
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- var montimeList []float64
- var montime float64
- var wg sync.WaitGroup
- now := time.Now()
- for i := 0; i < 30; i++ {
- wg.Add(1)
- nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
- go func(nowstr string) {
- defer wg.Done()
- sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
- slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
- m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
- montimeList = append(montimeList, m)
- }(nowstr)
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- wg.Wait()
- for _, m := range montimeList {
- montime += m
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataBySqlIN(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // 错误处理
- // 将报错信息处理成汉字
- func geterrmsg(errstr string) (msgstr string) {
- var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
- rs := []rune(errstr)
- if hzRegexp.MatchString(string(rs[0])) {
- msgstr = errstr
- return
- }
- if strings.Contains(errstr, "Duplicate entry") {
- strs := strings.Split(errstr, ` key '`)
- if len(strs) > 1 {
- if len(strs[len(strs)-1]) > 1 {
- errstr = "Duplicate entry :" + strs[len(strs)-1]
- }
- }
- }
- msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
- if err != nil {
- msgstr = errstr
- return
- }
- if msg == nil || len(msg) == 0 {
- var param []interface{}
- param = append(param, errstr, errstr)
- go func() {
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
- if err != nil {
- logging.Error("insert into err_msg(err,msg) err", err)
- }
- }()
- msgstr = errstr
- } else {
- msgstr = msg[0]["msg"]
- }
- return
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname body json true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Param s formData json true "ss"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNameForm [POST]
- func GetDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- //sqlnamestr := c.PostForm("measureNumber")
- //dataByte, _ := ioutil.ReadAll(c.Request.Body)
- //fsion := gofasion.NewFasion(string(dataByte))
- //sqlnamestr := fsion.Get("name").ValueStr()
- //offset := fsion.Get("offset").ValueInt()
- //pagecount := fsion.Get("pagecount").ValueInt()
- //returntype := fsion.Get("returntype").ValueStr()
- //params := fsion.Get("params").Array()
- c.Request.ParseForm()
- params := c.Request.Form
- offset := 0
- pageSize_ := 0
- returntype := params.Get("page")
- if returntype == "" {
- returntype = "0"
- }
- if tempv, exists := c.Get("jwt_username"); exists {
- params.Set("JwtUserName", tempv.(string))
- } else {
- params.Set("JwtUserName", "")
- }
- sqlnamestr := params.Get("name")
- logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- if returntype == "1" {
- pageNum, error := strconv.Atoi(params.Get("pageNum"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
- }
- pageSize, error := strconv.Atoi(params.Get("pageSize"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
- }
- pageSize_ = pageSize
- offset = pageNum
- }
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- c.Header("Content-Type", "application/octet-stream")
- c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // @Summary 递归获取所有
- // @Tags menu
- // @Accept json
- // @Produce json
- // @Param Ton query string true "Ton"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Router /authdata/GetRoleMenus [GET]
- func GetRecuDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- parentidname := fsion.Get("idname").ValueStr()
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- params := make(map[string]interface{})
- s_params := make([]interface{}, 0)
- if fsion.HasKey("params") {
- for _, v_params := range fsion.Get("params").Array() {
- s_params = append(s_params, v_params.ValueStr())
- }
- params["params"] = s_params
- } else {
- jparams := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- params[value] = tempv.(string)
- } else {
- params[value] = ""
- }
- } else {
- params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
- }
- }
- }
- }
- queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
- logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNames
- // @Accept json
- // @Produce json
- // @RequestBody sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNames [POST]
- func GetDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没找到"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- offset := fsion2.Get("offset").ValueInt()
- pagecount := fsion2.Get("pagecount").ValueInt()
- returntype := fsion2.Get("returntype").ValueStr()
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
- if err != nil {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- queryData[fsion2.Get("name").ValueStr()] = errorm
- logging.Error("GetDataByNames err: ", err)
- continue
- } else {
- queryData[fsion2.Get("name").ValueStr()] = queryData1
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByNameForm [POST]
- func PostDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- c.Request.ParseForm()
- params := c.Request.Form
- sqlnamestr := params.Get("name")
- logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // GetReportform 将数据集转换格式
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- func GetReportform(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- checked := fsion.Get("checked").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
- mode := parammaps.Get("mode").ValueDefaultInt(0)
- logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- // GetUpkeepPlan 保养计划
- func GetUpkeepPlan(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- if v, ok := value["id"]; ok {
- //month = "2020-03"
- seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
- if seviceplans != nil {
- for _, va := range seviceplans { //根据保养计划获取保养单
- //day,_ :=strconv.Atoi(va["day"])
- bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
- //buk := make(map[string]map[string]string)
- for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
- jstr := ""
- if bu["plantime"][8:9] == "0" {
- jstr = "m" + bu["plantime"][9:]
- } else {
- jstr = "m" + bu["plantime"][8:]
- }
- if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- if bu["flowCompeleted"] >= "2" {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
- }
- }
- }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
- // todo 优化性能 children统一查询
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- func GetArrList(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetAccount(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // PostDataByName 根据APISQL表中SQL执行得到数据集
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func PostDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- var err error
- queryData, err := module.PostDataByName(c, fsion)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- var (
- keyWord string
- )
- switch fsion.Get("name").ValueStr() {
- case "insertFeedclass":
- keyWord = "feed"
- err = module.GroupCategorySync(keyWord, fsion)
- case "deleteFeedclass":
- keyWord = "feed_delete"
- err = module.GroupCategoryDelete(keyWord, fsion)
- case "insertCowclass":
- keyWord = "cow"
- err = module.GroupCategorySync(keyWord, fsion)
- case "deleteCowclass":
- keyWord = "cow_delete"
- err = module.GroupCategoryDelete(keyWord, fsion)
- default:
- }
- if err != nil {
- logging.Error(keyWord, err)
- }
- if queryData != nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- //人脸识别/格润富德接口
- func GetRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- var wg sync.WaitGroup
- for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- wg.Add(1)
- go func(value map[string]interface{}) {
- defer wg.Done()
- _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
- }(value)
- }
- wg.Wait()
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBData err: ", string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func PostRJSBDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte)).Array()
- logging.Info("PostRJSBDatas err: ", string(dataByte))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
- for _, fsion := range fsions {
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- ID := parammaps.Get("ID").ValueStr()
- if ID == "" {
- continue
- }
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags ExecDataByConfig
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func ExecDataByConfig(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- fmt.Println(paramvalue["name"])
- if paramvalue["name"].(string) == "updateBigFP" {
- err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- if paramvalue["name"].(string) == "createdownloadedplan" {
- checkPlan(tx, paramvalue, tempCommon, tempval, 0)
- }
- }
- if err == nil {
- if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
- appG.Response(http.StatusOK, e.SUCCESS, tempval)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- func interfacetostring(val interface{}) string {
- switch val.(type) {
- case string:
- ss := val.(string)
- return ss
- break
- case int:
- ss := val.(int)
- return strconv.Itoa(ss)
- break
- case int64:
- ss := val.(int64)
- return strconv.FormatInt(ss, 10)
- break
- case float64:
- ss := val.(float64)
- return strconv.FormatFloat(ss, 'E', -1, 32)
- break
- }
- return ""
- }
- func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- for _, ParamMapList := range ParamMap {
- if v, ok := ParamMapList["resultname"]; ok {
- if v == valuestring[tempstrb+1:tempstre] {
- if v1, ok := ParamMapList["resultmaps"]; ok {
- if newA, ok := v1.([]map[string]interface{}); ok {
- return interfacetostring(newA[0][valuestring[tempstre+1:]])
- } else if newA, ok := v1.(map[string]interface{}); ok {
- return interfacetostring(newA[valuestring[tempstre+1:]])
- }
- }
- }
- }
- }
- } else {
- return valuestring
- }
- } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
- return strconv.FormatInt(int64(valuestring), 10)
- }
- return ""
- }
- func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
- if s, ok := v.(string); ok {
- return s
- } else if s, ok := v.(float64); ok {
- return strconv.FormatFloat(s, 'f', -1, 64)
- // return strconv.FormatInt(int64(s), 10)
- }
- }
- }
- }
- return ""
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- ss = ""
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- if sqltype == "s1" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "sm" {
- tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "v" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- }
- if err != nil {
- return nil, err
- }
- if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
- return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
- }
- } else if sqltype == "e" {
- tempVal_arrary := make([]map[string]interface{}, 0)
- tempVal_map := make(map[string]interface{})
- tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
- if err == nil {
- fasion["resultmaps"] = tempValParam.(map[string]interface{})
- tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
- tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
- tempVal_arrary = append(tempVal_arrary, tempVal_map)
- return tempVal_arrary, err
- }
- return nil, err
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- // @Summary 删除图片
- // @Tags RemovePicByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemovePicByName(c *gin.Context) {
- logging.Info("RemovePicByName ", c.Keys)
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- picname := fsion.Get("picname").ValueStr()
- sql, _ := restful.GetSqlByNameDB(sqlnamestr)
- params := fsion.Get("params").Array()
- s_params := make([]interface{}, 0)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if picname != "" {
- // Destination
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
- err := os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- }
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 删除文件
- // @Tags RemoveFileByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemoveFileByName(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Param("id")
- logging.Info("DownloadFile ", c.Keys, id)
- eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
- if eqdoc == nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
- appG.Response(http.StatusOK, e.SUCCESS, "OK")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func UpdateDataRelation(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- tablename := fsion.Get("name").ValueStr()
- dataname := fsion.Get("dataname").ValueStr()
- datavalue := fsion.Get("datavalue").ValueStr()
- valuename := fsion.Get("valuename").ValueStr()
- logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
- values := fsion.Get("values").Array()
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
- " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
- d_params := make([]interface{}, 4)
- d_params[0] = datavalue
- s_params := ""
- for _, v_values := range values {
- d_params[1] = v_values.ValueStr()
- if s_params == "" {
- s_params = v_values.ValueStr()
- } else {
- s_params = s_params + "," + v_values.ValueStr()
- }
- d_params[2] = d_params[1]
- d_params[3] = d_params[0]
- _, err := execDataBySqlT(insertSqlstr, d_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- break
- }
- }
- if s_params != "" {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDatasByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDatasByName [POST]
- func PostDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Get("array").Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- ss := fsion2.Get("name")
- aa := fsion2.Get("params")
- fmt.Println(ss, aa)
- logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没有找到"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- //ids,err := setting.SnowIds.NextId()
- //if err !=nil{
- // ids = time.Now().UnixNano()
- // logging.Info("create SnowIds err",err)
- //}
- //s_params = append(s_params, ids)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- _, err := execDataBySql(sql, s_params)
- if err != nil {
- logging.Error("PostDataByName err: ", err)
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- errorm["param"] = s_params
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.SUCCESS
- errorm["message"] = "success"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- }
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "NO SQL"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else {
- queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
- return queryData, err
- }
- }
- func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else {
- fmt.Println(params)
- queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- }
- }
- func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
- paramslist := strings.Split(Params, ",")
- s_params := make([]interface{}, 0)
- if isList {
- for _, v_params := range thisParams["params"].([]interface{}) {
- s_params = append(s_params, v_params)
- }
- } else {
- paramslist := strings.Split(Params, ",")
- if len(paramslist) > 0 && Params != "" {
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
- for _, queryData_ := range queryData {
- if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
- if isList {
- if queryData_[idname] != nil {
- thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
- }
- } else {
- if queryData_[idname] != nil {
- thisParams[idname] = queryData_[idname].(interface{})
- }
- if len(paramslist) > 0 && Params != "" {
- s_params = make([]interface{}, 0)
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
- } else {
- }
- }
- return queryData, err
- }
- func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- queryData, err := restful.ExecQueryT(sqlstr, params, tx)
- return queryData, err
- }
- func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- // @Summary 导入excel文件到数据库,excel第一行作为参数
- // @Tags ImportExcel
- // @Accept json
- // @Produce json
- // @Param file query string true "文件名"
- // @Param name header string true "执行sql的名字"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/ImportExcel [POST]
- func ImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- //importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- fmt.Println(outentry, entry)
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- fmt.Println(sql, s_params)
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func TransfTime(timestr string) (string, error) {
- if timestr == "" {
- return time.Now().Format("2006-01-02"), nil
- }
- days, err := strconv.Atoi(timestr)
- if err != nil {
- if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
- return "20" + timestr[6:] + "-" + timestr[:5], nil
- }
- _, err := time.Parse("2006-01-02", timestr)
- if err != nil {
- t, err := time.Parse("2006/01/02", timestr)
- if err != nil {
- t, err := time.Parse("2006.01.02", timestr)
- if err != nil {
- return "", err
- } else {
- return t.Format("2006-01-02"), nil
- }
- } else {
- return t.Format("2006-01-02"), nil
- }
- } else {
- return timestr, nil
- }
- }
- times, _ := time.Parse("2006-01-02", "1899-12-30")
- times = times.AddDate(0, 0, days)
- return times.Format("2006-01-02"), nil
- }
- func Createchart(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- chart_name := fsion.Get("chart_name").ValueStr()
- desc := fsion.Get("desc").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- source_id := fsion.Get("source_id").ValueStr()
- emp := fsion.Get("emp").ValueStr()
- content := fsion.Get("content").Json()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
- ids, pastureid, chart_name, 0, emp, desc, source_id)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Updatedashboard(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- dashboard_id := fsion.Get("dashboard_id").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- content := fsion.Get("content").Json()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- layout := mapResult["layout"]
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
- if err != nil {
- println("2", err.Error())
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- if exec != nil {
- if exec[0]["content"] == nil {
- mapR := make(map[string]interface{})
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- } else {
- var mapR map[string]interface{}
- err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err2)
- }
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
- }
- }
- }
- func ExecSQL(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- content := fsion.Get("content").Json()
- pastureid := fsion.Get("pastureid").ValueStr()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- sqlstr := "select "
- groupstr := " GROUP BY "
- for _, value := range mapResult["selectedDimension"].([]interface{}) {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- }
- for _, value := range mapResult["selectedCalcul"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- if _, ok := mapResult["selectedCalcul2"]; ok {
- for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
- sqlstr = sqlstr + " where pastureid=" + pastureid
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr + " and "
- }
- println(len(mapResult["filters"].([]interface{})), sqlstr)
- for _, value := range mapResult["filters"].([]interface{}) {
- switch value.(map[string]interface{})["filterOperator"].(string) {
- case ">", "=", "<", ">=", "<=", "!=", "like":
- 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 "
- case "IN":
- sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
- for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
- sqlstr = sqlstr + value1.(string) + ","
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + ")" + " AND "
- case "BETWEEN":
- 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 "
- }
- }
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr[0 : len(sqlstr)-4]
- }
- //
- groupstr = groupstr[0 : len(groupstr)-1]
- sqlstr = sqlstr + groupstr + " "
- if len(mapResult["orderByStrs"].([]interface{})) > 0 {
- sqlstr = sqlstr + " order by "
- }
- //
- for key, value := range mapResult["orderByStrs"].([]interface{}) {
- if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
- sqlstr = sqlstr + value.(string) + " "
- } else {
- sqlstr = sqlstr + value.(string) + ","
- }
- }
- //
- sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- exec, err := tx.SQL(sqlstr).Query().List()
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Dashboards(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- //sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- //paramslist1 := strings.Split(p1, ",")
- dids := make([]interface{}, 0)
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- var mapResult map[string]interface{}
- dids = append(dids, value["dashboard_id"])
- if value["content"] != nil {
- err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
- if err1 != nil {
- println("JsonToMapDemo1 err: ", err1)
- }
- temap := make(map[string]interface{})
- tem := mapResult["layout"].([]interface{})
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- a := false
- for _, v2 := range tem {
- if v2.(map[string]interface{})["id"].(string) == va {
- a = true
- //println("va1======",va)
- }
- }
- if !a {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- } else {
- temap := make(map[string]interface{})
- tem := make([]interface{}, 0)
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- }
- }
- queryData.(map[string]interface{})["order"] = dids
- queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
- fsion := gofasion.NewFasion(parammaps)
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- body := []byte("")
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- body, _ = json.Marshal(queryData)
- }
- }
- }
- bs := bytes.NewBuffer(body)
- client := &http.Client{}
- //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
- req, err := http.NewRequest(RequestMethod,
- url,
- bs,
- )
- if err != nil {
- }
- req.Header.Set("Content-Type", "application/json;charset=utf-8")
- req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
- if err != nil {
- // handle error
- }
- resp, err := client.Do(req)
- if err != nil {
- return ""
- }
- defer resp.Body.Close()
- result_body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return ""
- }
- fmt.Println(string(result_body))
- return ""
- }
- func GetSummary(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- parammaps := fsion.Get("parammaps")
- status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
- genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
- isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
- tx := restful.Engine.NewSession()
- defer tx.Close()
- sqlnamestr := ""
- if genre == "0" {
- if status == "0" {
- sqlnamestr = "getAccuracyJSY"
- } else if status == "1" {
- sqlnamestr = "getAccuracyHFT"
- } else if status == "2" {
- sqlnamestr = "getAccuracyHNS"
- } else if status == "3" {
- sqlnamestr = "getAccuracyHSC"
- } else if status == "4" {
- sqlnamestr = "getAccuracyHCC"
- } else if status == "5" {
- sqlnamestr = "getAccuracyMC"
- } else if status == "6" {
- sqlnamestr = "getAccuracyFeedHL"
- } else if status == "7" {
- sqlnamestr = "getAccuracyRT"
- }
- } else {
- if status == "0" {
- sqlnamestr = "getAccuracySCCJSY"
- } else if status == "1" {
- sqlnamestr = "getAccuracySFT"
- } else if status == "2" {
- sqlnamestr = "getAccuracySNS"
- } else if status == "3" {
- sqlnamestr = "getAccuracySSC"
- } else if status == "4" {
- sqlnamestr = "getAccuracySCC"
- } else if status == "5" {
- sqlnamestr = "getAccuracySLCL"
- } else if status == "7" {
- sqlnamestr = "getAccuracySCCRT"
- }
- }
- if isDate == "1" {
- sqlnamestr += "Date"
- }
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- // fmt.Println(sqlnamestr, sql)
- if sql != "" {
- s_params := make([]interface{}, 0)
- // if fsion.HasKey("parammaps") {
- fmt.Println(s_params, "222", p)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // type lpplanStruct struct {
- // Id int64 `xorm:"id"`
- // Tmrname string `xorm:"tmrname"`
- // Tmrid int64 `xorm:"tmrid"`
- // Sort int64 `xorm:"sort"`
- // Sel int64 `xorm:"sel"`
- // Times int64 `xorm:"times"`
- // Ftname string `xorm:"ftname"`
- // Ftid int64 `xorm:"ftid"`
- // Maxweight float64 `xorm:"maxweight"`
- // Sumweight float64 `xorm:"sumweight"`
- // Sumcowcount int64 `xorm:"sumcowcount"`
- // Pastureid string `xorm:"pastureid"`
- // Display string `xorm:"display"`
- // Issplit int64 `xorm:"issplit"`
- // BeginTime string `xorm:"begintime"`
- // }
- func UpdateFTdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- fTChange := make(map[string]interface{}, 0)
- fpdOldDataList := make([]map[string]interface{}, 0)
- fpdDataList := make([]map[string]interface{}, 0)
- fsion := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- createdate := time.Now().Format("2006-01-02 15:04:05")
- err := json.Unmarshal(dataByte, &tempval_)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- tx := restful.Engine.NewSession()
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- if v1["name"] == "updateFPbyFTChange" {
- fTChange = v1
- continue
- }
- tempval = append(tempval, v1)
- }
- }
- }
- parammaps := fTChange["parammaps"].(map[string]interface{})
- // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- err = tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
- UNION
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
- order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- tx.Commit()
- // go func() {
- if fTChange != nil {
- parammaps := fTChange["parammaps"].(map[string]interface{})
- if parammaps["type"].(float64) == 1 {
- _, err = tx.SQL(`UPDATE feedp fp
- set
- ccountratio = ccount *(ratio /100 ),
- fp.ftweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- _, err = tx.SQL(`UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100
- WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- } else {
- _, err = tx.SQL(`UPDATE feedp fp
- SET ccountratio = ccount *(ratio /100 ),
- fp.supplyweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- _, err = tx.SQL(`UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- }
- fpdDataList, err = tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
- UNION
- SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
- order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
- lpplanList := make([]*lpplanStruct, 0)
- err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
- if err != nil {
- logs.Error(err, 1)
- return
- }
- lppidlist := []string{}
- for _, lpp := range lpplanList {
- lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
- }
- if len(lppidlist) <= 0 {
- appG.Response(http.StatusOK, e.SUCCESS, true)
- return
- }
- lpplandtl1AllList := make([]*lpplandtl1, 0)
- err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
- order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
- if err != nil {
- // tx.Rollback()
- logs.Error(err, 2, parammaps["pastureid"])
- return
- }
- var wg sync.WaitGroup
- for _, old := range fpdOldDataList {
- for _, fpd := range fpdDataList {
- wg.Add(1)
- go func(old, fpd map[string]interface{}) {
- updateLppandList := make([]*lpplandtl1, 0)
- defer wg.Done()
- if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
- fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
- // if weight > oldweight {
- // return
- // }
- var w float64
- var status int
- if weight < oldweight {
- if weight >= 0 {
- return
- }
- w = weight
- status = 0
- } else {
- if oldweight > 0 {
- return
- }
- w = weight
- status = 1
- }
- // fweight = w
- for _, lpp := range lpplanList {
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtl1, 0)
- fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
- for _, lppland := range lpplandtl1AllList {
- if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
- lpplandtl1List = append(lpplandtl1List, lppland)
- }
- }
- if len(lpplandtl1List) == 0 {
- continue
- }
- for _, lppland := range lpplandtl1List {
- lweight += lppland.Lweight
- }
- if status == 0 {
- if lweight <= 0 {
- continue
- }
- } else {
- if lpp.Maxweight <= lweight {
- continue
- }
- }
- for _, lppland := range lpplandtl1List {
- if fpdid == lppland.Fpdid {
- if status == 1 {
- // if w <= lppland.Lweight {
- if lpp.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lpp.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lpp.Maxweight - lweight)
- n := (lpp.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- updateLppandList = append(updateLppandList, lppland)
- break
- }
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
- if err != nil {
- // tx.Rollback()
- logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
- return
- }
- for _, lppland := range updateLppandList {
- fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
- if err != nil {
- fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
- // tx.Rollback()
- logs.Error(err, 3)
- return
- }
- // defer wg.Done()
- }
- updateLppandList = []*lpplandtl1{}
- if w == 0 {
- break
- }
- }
- }
- }(old, fpd)
- }
- }
- wg.Wait()
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- now := createdate
- // for _, oldFpd := range oldFpdDataList {
- for _, newFpd := range newFpdDataList {
- // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
- // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
- // go func() {
- _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- // }()
- }
- // break
- // }
- // }
- // }
- // for _, oldLpplandtl1 := range oldLpplandtl1List {
- for _, newLpplandtl1 := range newLpplandtl1List {
- // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
- // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
- // go func() {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- // }()
- // }
- // break
- // }
- // }
- }
- // for _, oldFeedp := range oldFeedpList {
- for _, newFeedp := range newFeedpList {
- // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
- // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
- // go func() {
- _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- type lpplandtlInfo struct {
- Id int64 `xorm:"id"`
- Pastureid int64 `xorm:"pastureid"`
- Lppid int64 `xorm:"lppid"`
- Barid int64 `xorm:"barid"`
- Barname string `xorm:"barname"`
- Fpdid int64 `xorm:"fpdid"`
- Fttype int64 `xorm:"fttype"`
- Lweight float64 `xorm:"lweight"`
- Sort int64 `xorm:"sort"`
- Tmrid int64 `xorm:"tmrid"`
- Tmrname string `xorm:"tmrname"`
- Cowcount int64 `xorm:"cowcount"`
- Ccountradio float64 `xorm:"ccountradio"`
- Background string `xorm:"background"`
- Lweighthis float64 `xorm:"lweighthis"`
- Maxweight float64 `xorm:"maxweight"`
- }
- func UpdateFpdetailBar(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- pastureid := fsion.Get("pastureid").ValueStr()
- id := fsion.Get("id").ValueStr()
- tx := restful.Engine.NewSession()
- tx.Begin()
- fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse from fpdetail where pastureid = ? and barid = (select barid from feedp where id = ? ) order by times `,
- pastureid, id).Query().List()
- if err != nil {
- logs.Error(err)
- }
- for _, fpd := range fpdList {
- lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
- where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
- pastureid, fpd["id"]).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- } else {
- weight := fpdweight - lweight
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- } else {
- // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
- // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- weight = 0
- break
- }
- }
- }
- }
- }
- fsionData := fsion.Get("data").Array()
- for _, list := range fsionData {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
- ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
- ftmap["times"] = list.Get("times").ValueInt64()
- ftmap["ptid"] = list.Get("ptid").ValueStr()
- ftmap["ptsid"] = list.Get("ptsid").ValueStr()
- // fmt.Println(ftmap)
- fpdDataList, err := tx.SQL(`
- SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ifnull(ptsid,-1) ) ptsid ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
- fttype := -1
- if fpd["fttype"].(string) == "1" {
- fttype = 1
- }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // continue
- if weight <= 0 {
- continue
- }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return
- }
- }
- if w == 0 {
- break
- }
- // break
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- tx.Commit()
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- for _, newLpplandtl1 := range newLpplandtl1List {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetProcessAnalysis(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- parammaps := fsion.Get("parammaps")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- tmrtnameStr := ""
- for _, tmr := range parammaps.Get("tmrtname").Array() {
- if len(tmrtnameStr) == 0 {
- tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
- } else {
- tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
- }
- }
- if len(tmrtnameStr) > 0 {
- sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
- }
- sql += " ORDER BY d.intime"
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func UpdateFeedtempletStatus(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- tx := restful.Engine.NewSession()
- tx.Begin()
- _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- tx.Commit()
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func AddFtdry(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- parammaps := fsion.Get("parammaps")
- logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- var actweight float64
- actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
- where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
- and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
- where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
- and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
- group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
- 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()
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- if len(actweightList) > 0 {
- for _, item := range actweightList {
- fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- actweight = fl
- }
- } else {
- dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
- where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
- parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- for _, item := range dryList {
- dry, err := strconv.ParseFloat(item["dry"].(string), 64)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- actweight += parammaps.Get("freshweight").ValueFloat64() * dry
- }
- }
- if sqlnamestr == "insertFtdry" {
- s_params = append(s_params, actweight)
- } else if sqlnamestr == "updateFtdry" {
- sql = fmt.Sprintf(sql, actweight)
- }
- queryData, err := execDataBySqlT(sql, s_params, tx)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func CheckDates(c *gin.Context) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- }
- }
- if err == nil {
- vmsg := ""
- for _, item := range tempval {
- for _, list := range item["resultmaps"].(map[string]interface{}) {
- for _, childrenList := range list.([]interface{}) {
- for k, children := range childrenList.(map[string]interface{}) {
- if k != "children" {
- continue
- }
- for _, v := range children.([]map[string]interface{}) {
- for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
- if k1 == "list" {
- for _, v2 := range v1.([]map[string]interface{}) {
- if v2["vmsg"].(string) != "1" {
- if len(vmsg) == 0 {
- vmsg = v2["vmsg"].(string)
- } else {
- vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- if len(vmsg) > 0 {
- appG.Response(http.StatusOK, e.SUCCESS, vmsg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusInternalServerError, e.ERROR, msg)
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- ss = ""
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- if sql != "" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if err != nil {
- return nil, err
- }
- // fmt.Println(tempValParam)
- return tempValParam.(map[string]interface{}), nil
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- func FpdImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- // importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- dataList := make(map[string][]*upFpdetail, 0)
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- // fmt.Println(outentry, entry, "aaaaaaaaaaa")
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- errExist := false
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- errExist = true
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- if !errExist {
- dataexcel := make(map[string]interface{}, 0)
- if _, ok := outentry["栏舍名称"]; ok {
- dataexcel["barname"] = outentry["栏舍名称"]
- }
- if _, ok := outentry["实际牛头数"]; ok {
- dataexcel["ccount"] = outentry["实际牛头数"]
- }
- if _, ok := outentry["系数(%)"]; ok {
- dataexcel["ratio"] = outentry["系数(%)"]
- }
- if _, ok := outentry["配方模板"]; ok {
- dataexcel["ftname"] = outentry["配方模板"]
- }
- if _, ok := outentry["补料配方"]; ok {
- dataexcel["ptsfname"] = outentry["补料配方"]
- }
- if _, ok := outentry["第一班比例(%)"]; ok {
- dataexcel["1"] = outentry["第一班比例(%)"]
- }
- if _, ok := outentry["第二班比例(%)"]; ok {
- dataexcel["2"] = outentry["第二班比例(%)"]
- }
- if _, ok := outentry["第三班比例(%)"]; ok {
- dataexcel["3"] = outentry["第三班比例(%)"]
- }
- if _, ok := outentry["第四班比例(%)"]; ok {
- dataexcel["4"] = outentry["第四班比例(%)"]
- }
- if _, ok := outentry["第五班比例(%)"]; ok {
- dataexcel["5"] = outentry["第五班比例(%)"]
- }
- if _, ok := outentry["第六班比例(%)"]; ok {
- dataexcel["6"] = outentry["第六班比例(%)"]
- }
- existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !existbar {
- continue
- }
- _, err = tx.SQL(` update feedp fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` update fpdetail fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
- return
- }
- if !existft {
- continue
- }
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- // fmt.Println(dataexcel["barname"])
- dataList[dataexcel["barname"].(string)] = upFpdetailList
- // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- for barname, v := range dataList {
- updateFpdetailByBar(pastureid, barname, v)
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- type upFpdetail struct {
- Old float64
- New float64
- Times int64
- Ptid int64
- Fweight float64
- Id int64
- // Ptsid string
- }
- func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ifnull(ptsrate,0))*weight,2),"") weight,ptuse,times from fpdetail where pastureid = ? and barname = ? order by times `,
- pastureid, barname).Query().List()
- if err != nil {
- logs.Error(err)
- }
- for _, fpd := range fpdList {
- lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
- where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
- pastureid, fpd["id"], fpd["times"]).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- weight := lweight - fpdweight
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
- WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- weight = 0
- break
- }
- }
- }
- }
- }
- for _, list := range dataList {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Old
- ftmap["new"] = list.New
- ftmap["times"] = list.Times
- ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
- ftmap["ptsid"] = ""
- // fmt.Println(ftmap)
- // 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 ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
- // UNION
- fpdDataList, err := tx.SQL(`
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
- // fttype := -1
- // if fpd["fttype"].(string) == "1" {
- fttype := 1
- // }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
- // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
- // barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:1 id:4828050527277810688 isfill:0 pastureid:1705635208 ptid:83 ptsid:-1 times:1 tratio:48.000 weight:32.0
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
- // continue
- // }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- }
- if w == 0 {
- break
- }
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- // for _, data := range dataList {
- // fttype := -1
- // if data.Ptid != -1 {
- // fttype = 1
- // }
- // var fweight float64
- // var lweight float64
- // lpplandtl1List := make([]*lpplandtlInfo, 0)
- // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
- // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
- // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // weight := data.Fweight
- // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- // var w float64
- // var status int
- // if data.New < data.Old {
- // if weight >= 0 {
- // continue
- // }
- // w = weight
- // status = 0
- // } else {
- // // if weight-(data.New-data.Old) > 0 {
- // // continue
- // // }
- // w = data.New - data.Old
- // status = 1
- // }
- // for _, lppland := range lpplandtl1List {
- // var lppdata lpplandtlInfo
- // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
- // lppland.Lppid, pastureid).GetFirst(&lppdata)
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // lweight = lppdata.Lweight
- // if status == 1 {
- // // if w <= lppland.Lweight {
- // if lppland.Maxweight <= lweight {
- // continue
- // }
- // if w+lweight <= lppland.Maxweight {
- // lppland.Lweight += w
- // lweight += w
- // fweight += w
- // w = 0
- // } else {
- // w = w - (lppland.Maxweight - lweight)
- // n := (lppland.Maxweight - lweight)
- // lppland.Lweight = lppland.Lweight + n
- // lweight += n
- // fweight += n
- // }
- // } else {
- // if lppland.Lweight == 0 {
- // continue
- // }
- // if w+lppland.Lweight >= 0 {
- // lppland.Lweight = lppland.Lweight + w
- // lweight = lweight + w
- // fweight = fweight + w
- // w = 0
- // } else {
- // w = w + lppland.Lweight
- // lweight = lweight - lppland.Lweight
- // fweight = fweight - lppland.Lweight
- // lppland.Lweight = 0
- // }
- // }
- // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // break
- // }
- // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // // if w == 0 {
- // // break
- // // }
- // // }
- // }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- return err
- }
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- for _, newLpplandtl1 := range newLpplandtl1List {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- for _, newFpd := range newFpdDataList {
- _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- for _, newFeedp := range newFeedpList {
- _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- return nil
- }
- func DeleteFTdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- ftid := parammaps.Get("ftid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if parammaps.Get("type").ValueStr() == "1" {
- _, err := tx.SQL(`UPDATE feedp fp
- set
- fp.ftweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // UPDATE fpdetail SET ptuse=0 ,weight = 0
- _, err = tx.SQL(`
- UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100,
- ptuse= 0
- WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(`UPDATE feedp fp
- SET
- fp.supplyweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0) + ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- _, err = tx.SQL(`
- UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100,
- ptsrate = 0
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func DeleteSpillageAll(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- barid := parammaps.Get("barid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- now := time.Now()
- for _, item := range lpplandtl1List {
- go func(item map[string]interface{}) {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- item["pastureid"], item["lppid"], item["barid"],
- item["barname"], item["fpdid"], item["fttype"],
- item["lweight"], item["sort"], item["tmrid"],
- item["tmrname"], item["background"], item["cowcount"],
- item["ccountradio"], item["lweighthis"], now).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }(item)
- }
- tx.Begin()
- _, 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()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetTMRListEnableTypeAll(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`SELECT
- eqcode,
- tname,
- datacaptureno,
- trim(tclassid) tclassid,
- concat(tname,' / ',eqcode) tmrmix,
- d.label tclassname,
- maxstirfeed,
- remark,
- tmr.enable,
- TRIM(tmr.id) id,
- TRIM(tmr.pastureid)pastureid
- FROM
- tmr
- left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
- WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
- ORDER BY id DESC`, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var carNum int64
- for _, sysopt := range sysoptData {
- if sysopt["inforvalue"] == nil {
- carNum = 1
- } else {
- carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
- }
- }
- id := 200
- n := 0
- for i := carNum; i > 0; i-- {
- id++
- n++
- data := make(map[string]interface{}, 0)
- data["eqcode"] = fmt.Sprintf("任意车%d", n)
- data["tname"] = fmt.Sprintf("任意车%d", n)
- data["datacaptureno"] = -2
- data["tclassid"] = -2
- data["tmrmix"] = fmt.Sprintf("任意车%d", n)
- data["tclassname"] = fmt.Sprintf("任意车%d", n)
- data["maxstirfeed"] = 100000
- data["remark"] = fmt.Sprintf("任意车%d", n)
- data["enable"] = 1
- data["id"] = fmt.Sprintf("%d", id)
- data["pastureid"] = pastureid
- dataList = append(dataList, data)
- }
- // UNION ALL
- // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- func GetFeedpHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- bar := fsion.Get("barname").ValueStr()
- startDate := fsion.Get("startDate").ValueStr()
- endDate := fsion.Get("endDate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
- DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
- and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
- (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
- and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, feedp := range feedpList {
- // LastftList, err := tx.SQL(` select tname ,id
- // from feedtemplethistory where id = ?
- // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
- DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
- and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var ftname interface{}
- ftnamestatus := 0
- ftname = feedp["ftname"]
- var lastftid int64
- if len(nextfeedpList) > 0 {
- for _, ft := range nextfeedpList {
- if ft["ftname"].(string) != feedp["ftname"].(string) {
- ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
- lastftid = ft["ftid"].(int64)
- ftnamestatus = 1
- break
- }
- }
- }
- for i, fpd := range fpdList {
- if feedp["createdate"].(string) == fpd["createdate"].(string) {
- fpd["weightstatus"] = 0
- fpd["tratiostatus"] = 0
- fpd["ftnamestatus"] = ftnamestatus
- for k, fpd2 := range fpdList {
- if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
- if fpd["weight"].(string) != fpd2["weight"].(string) {
- fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
- fpd["weightstatus"] = 1
- }
- if fpd["tratio"].(string) != fpd2["tratio"].(string) {
- fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
- fpd["tratiostatus"] = 1
- }
- break
- }
- }
- fpd["barid"] = feedp["barid"]
- fpd["barname"] = feedp["barname"]
- fpd["ccount"] = feedp["ccount"]
- fpd["ratio"] = feedp["ratio"]
- fpd["ccountratio"] = feedp["ccountratio"]
- fpd["ftid"] = feedp["ftid"]
- fpd["ftname"] = ftname
- fpd["ccountstatus"] = 0
- fpd["ccountratiostatus"] = 0
- fpd["ratiostatus"] = 0
- fpd["ftnamestatus"] = 0
- fpd["lastftid"] = lastftid
- for _, next := range nextfeedpList {
- if next["ccount"].(int64) != fpd["ccount"].(int64) {
- fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
- fpd["ccountstatus"] = 1
- }
- if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
- fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
- fpd["ccountratiostatus"] = 1
- }
- if next["ratio"].(string) != fpd["ratio"].(string) {
- fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
- fpd["ratiostatus"] = 1
- }
- // if next["ftname"].(string) != fpd["ftname"].(string) {
- // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
- // fpd["ftnamestatus"] = 1
- // }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, fpdList)
- }
- // func GetLpplandtl1History(c *gin.Context) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsion := gofasion.NewFasion(string(dataByte))
- // // parammaps := fsion.Get("parammaps")
- // barid := fsion.Get("barid").ValueStr()
- // startDate := fsion.Get("startDate").ValueStr()
- // endDate := fsion.Get("endDate").ValueStr()
- // tx := restful.Engine.NewSession()
- // defer tx.Close()
- // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
- // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
- // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
- // // if err != nil {
- // // logs.Error(err)
- // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // // return
- // // }
- // // for _, feedp := range feedpList {
- // // fmt.Println(feedp)
- // // for i, fpd := range fpdList {
- // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
- // // for k, fpd2 := range fpdList {
- // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
- // // if fpd["weight"].(string) != fpd2["weight"].(string) {
- // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
- // // }
- // // break
- // // }
- // // }
- // // fpd["barid"] = feedp["barid"]
- // // fpd["barname"] = feedp["barname"]
- // // fpd["ccount"] = feedp["ccount"]
- // // fpd["ratio"] = feedp["ratio"]
- // // fpd["ccountratio"] = feedp["ccountratio"]
- // // fpd["ftid"] = feedp["ftid"]
- // // fpd["ftname"] = feedp["ftname"]
- // // }
- // // }
- // // }
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- // }
- func GetRemind(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // pastureid = "3"
- resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- defer resp.Body.Close()
- buf := bytes.NewBuffer(make([]byte, 0, 512))
- buf.ReadFrom(resp.Body)
- fmt.Println(string(buf.Bytes()))
- respMap := make(map[string]interface{}, 0)
- err = json.Unmarshal(buf.Bytes(), &respMap)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, data := range dataList {
- r := make(map[string]interface{}, 0)
- r["sys_name"] = ""
- r["service_id"] = ""
- r["pasture_id"] = ""
- r["type_name"] = ""
- r["remind_type_id"] = ""
- r["remind_type"] = ""
- r["push_date"] = ""
- r["push_time"] = ""
- r["interval_time"] = ""
- r["push_limit"] = ""
- r["template_id"] = ""
- r["roles_id"] = ""
- r["users_id"] = ""
- r["date_type"] = ""
- r["cycle_type"] = ""
- data["data"] = r
- for _, resp := range respMap["data"].([]interface{}) {
- resp1 := resp.(map[string]interface{})
- if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
- if resp1["push_time"] == nil {
- resp1["push_time"] = ""
- }
- data["data"] = resp1
- break
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- type NoticeMsgtype struct {
- SysName string `json:"sys_name"`
- PastureId int64 `json:"pasture_id"`
- ServiceId int64 `json:"service_id"`
- TypeName string `json:"type_name"`
- RemindType int64 `json:"remind_type"`
- PushDate int64 `json:"push_date"`
- PushTime string `json:"push_time"`
- IntervalTime int64 `json:"interval_time"`
- PushLimit int64 `json:"push_limit"`
- TemplateId string `json:"template_id"`
- UsersId string `json:"users_id"`
- DateType int64 `json:"date_type"`
- CycleType int64 `json:"cycle_type"`
- DelayTime int64 `json:"delay_time"`
- Status int64 `json:"status"`
- }
- func UpdateRemind(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- // user := parammaps.Get("user").ValueStr()
- id := parammaps.Get("id").ValueInt64()
- noticeMsgtype := new(NoticeMsgtype)
- noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
- noticeMsgtype.ServiceId = id
- noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
- noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
- // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
- noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
- noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
- noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
- noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
- noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
- // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
- noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
- // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
- noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
- noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
- noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
- noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
- //TODO
- noticeMsgtype.SysName = "tmrWatch"
- userList := parammaps.Get("user").Array()
- var userstr []string
- for _, user := range userList {
- userstr = append(userstr, user.ValueStr())
- }
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // var jsonStr = []byte(noticeMsgtype
- noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
- fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
- req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println("response Body:", string(body))
- getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- defer getresp.Body.Close()
- buf := bytes.NewBuffer(make([]byte, 0, 512))
- buf.ReadFrom(getresp.Body)
- // fmt.Println(string(buf.Bytes()))
- respMap := make(map[string]interface{}, 0)
- err = json.Unmarshal(buf.Bytes(), &respMap)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, resp := range respMap["data"].([]interface{}) {
- resp1 := resp.(map[string]interface{})
- _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetSpillageallHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- barname := parammaps.Get("barname").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- startdate := parammaps.Get("startDate").ValueStr()
- enddate := parammaps.Get("endDate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
- order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- respMap := make([]map[string]interface{}, 0)
- data := make(map[interface{}]interface{})
- for _, history := range historyList {
- data[history["createdate"]] = history["createdate"]
- }
- createList := []string{}
- for _, v := range data {
- createList = append(createList, v.(string))
- }
- // sort.Sort()
- // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
- sort.Slice(createList, func(i, j int) bool {
- return createList[i] > createList[j]
- })
- for _, v := range createList {
- a := make(map[string]interface{})
- a["createdate"] = data[v]
- // createList = append(createList, v.(string))
- respMap = append(respMap, a)
- }
- number := 0
- dataMap := make([]interface{}, 0)
- for k, resp := range respMap {
- createdate := resp["createdate"].(string)
- var nextcreatedate string
- if len(respMap) > k+1 {
- nextcreatedate = respMap[k+1]["createdate"].(string)
- }
- // dataList := make(map[string][]interface{})
- // list := make(map[string]interface{})
- times := make(map[interface{}]int)
- for _, history := range historyList {
- // List := make(map[interface{}][]interface{})
- i := 0
- if history["createdate"].(string) == createdate {
- times[history["times"]]++
- data := make(map[string]interface{})
- data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
- // exist := false
- if nextcreatedate != "" {
- for _, history1 := range historyList {
- if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
- history1["times"].(int64) == history["times"].(int64) {
- data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
- break
- // exist = true
- }
- }
- }
- // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- i++
- // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
- // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
- // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
- // resp["times"] = history["times"]
- // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- data1 := make(map[string]interface{})
- data1["times"] = history["times"]
- data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- data1["createdate"] = resp["createdate"]
- // fmt.Println(dataList)
- dataMap = append(dataMap, data1)
- }
- if i > number {
- number = i
- }
- // respMap = append(respMap, dataList)
- }
- // for k, data := range dataList {
- // resp[k] = data
- // }
- // resp["data"] = dataList
- }
- // resp := make(map[string]interface{})
- // sort.Strings(createList)
- //
- // for _, create := range createList {
- // for _, r := range respMap {
- // if create == r["createdate"].(string) {
- // resp[create] = r
- // break
- // }
- // }
- // }
- sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
- var trainsList []interface{}
- for i := 0; i < number; i++ {
- trains := make(map[string]interface{})
- trains["label"] = fmt.Sprintf("第%s车", sz[i])
- trains["prop"] = fmt.Sprintf("a%d", i+1)
- trainsList = append(trainsList, trains)
- }
- respdata := make(map[string]interface{})
- respdata["data"] = dataMap
- respdata["trains"] = trainsList
- appG.Response(http.StatusOK, e.SUCCESS, respdata)
- }
- func GetRecipeTemplateRecordHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- ftid := parammaps.Get("ftid").ValueInt64()
- lastftid := parammaps.Get("lastftid").ValueInt64()
- pastureid := parammaps.Get("pastureid").ValueInt64()
- // createdate := parammaps.Get("createdate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- data := make(map[string]interface{})
- feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
- and fthis.pastureId = ?`, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- feedtemplet := make(map[string]interface{})
- for _, f := range feedtempletList {
- feedtemplet = f
- }
- fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- feedtemplet["fit"] = fitList
- data["current"] = feedtemplet
- lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
- and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- lastfeedtemplet := make(map[string]interface{})
- for _, f := range lastfeedtempletList {
- lastfeedtemplet = f
- }
- lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- lastfeedtemplet["fit"] = lastfitList
- data["last"] = lastfeedtemplet
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func GetFeedtempletHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- ftid := parammaps.Get("ftid").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueInt64()
- start := parammaps.Get("startdate").ValueStr()
- end := parammaps.Get("enddate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1,(select empname from user where id = feedtemplethistory.userId) empname from feedtemplethistory where createdate between ? and ?
- and id = ? and pastureid = ? order by createdate desc `,
- start, end, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
- ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
- for i, ft := range ftList {
- fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
- ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
- (select empname from user where id = fit.userId) empname,
-
- 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
- where fit.fitid = ?
- and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
- and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- ft["createdate"] = ft["createdate1"]
- // data["tname"] = ft["tname"]
- // data["tcode"] = ft["tcode"]
- // data["tcolor"] = ft["tcolor"]
- // data["fttype"] = ft["fttype"]
- // data["ccname"] = ft["ccname"]
- // data["source"] = ft["source"]
- // data["version"] = ft["version"]
- // data["remark"] = ft["remark"]
- for n, ft2 := range ftList {
- if i < n {
- if ft["tname"].(string) != ft2["tname"].(string) {
- ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
- }
- if _, ok := ft["tcode"]; ok {
- if _, ok := ft2["tcode"]; ok {
- if ft["tcode"].(string) != ft2["tcode"].(string) {
- ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
- }
- }
- }
- if _, ok := ft["tcolor"]; ok {
- if _, ok := ft2["tcolor"]; ok {
- if ft["tcolor"].(string) != ft2["tcolor"].(string) {
- ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
- }
- }
- }
- if _, ok := ft["fttype"]; ok {
- if _, ok := ft2["fttype"]; ok {
- if ft["fttype"].(string) != ft2["fttype"].(string) {
- ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
- }
- }
- }
- if _, ok := ft["ccname"]; ok {
- if _, ok := ft2["ccname"]; ok {
- if ft["ccname"].(string) != ft2["ccname"].(string) {
- ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
- }
- }
- }
- if _, ok := ft["source"]; ok {
- if _, ok := ft2["source"]; ok {
- if ft["source"].(string) != ft2["source"].(string) {
- ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
- }
- }
- }
- if _, ok := ft["version"]; ok {
- if _, ok := ft2["version"]; ok {
- if ft["version"].(int64) != ft2["version"].(int64) {
- ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
- }
- }
- }
- if _, ok := ft["remark"]; ok {
- if _, ok := ft2["remark"]; ok {
- if ft["remark"].(string) != ft2["remark"].(string) {
- ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
- }
- }
- }
- break
- }
- }
- dataList := make([]map[string]interface{}, 0)
- if len(fithisList) > 0 {
- for _, fit := range fithisList {
- data := make(map[string]interface{})
- data["feedgroup"] = fit["feedgroup"]
- data["fname"] = fit["fname"]
- data["empname"] = fit["empname"]
- if fit["Eweight"] != nil {
- if fit["Eweight"].(string) != fit["weight"].(string) {
- data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
- } else {
- data["fweight"] = fit["Eweight"]
- }
- data["fweightstatus"] = 1
- } else {
- data["fweight"] = fit["weight"]
- data["fweightstatus"] = 0
- }
- data["autosecond"] = fit["autosecond"]
- // data["tname"] = ft["tname"]
- // data["tcode"] = ft["tcode"]
- // data["tcolor"] = ft["tcolor"]
- // data["fttype"] = ft["fttype"]
- // data["ccname"] = ft["ccname"]
- // data["source"] = ft["source"]
- // data["version"] = ft["version"]
- // data["remark"] = ft["remark"]
- // data["createdate"] = ft["createdate1"]
- // ft["fit"] = data
- dataList = append(dataList, data)
- }
- } else {
- for _, fit := range ftdetailList {
- data := make(map[string]interface{})
- data["feedgroup"] = fit["feedgroup"]
- data["fname"] = fit["fname"]
- // if fit["Eweight"] != nil {
- // data["weight"] = fit["Eweight"]
- // } else {
- data["fweight"] = fit["fweight"]
- // }
- data["autosecond"] = fit["autosecond"]
- // ft["fit"] = data
- dataList = append(dataList, data)
- }
- }
- ft["fit"] = dataList
- }
- appG.Response(http.StatusOK, e.SUCCESS, ftList)
- }
- func UpdateMaterialTMR(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- tmrid := parammaps.Get("tmrid").ValueStr()
- tmrtype := parammaps.Get("tmrtype").ValueStr()
- lppid := parammaps.Get("lppid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
- // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
- status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- if tmrid != "1000" {
- tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var maxstirfeed float64
- for _, tmr := range tmrList {
- maxstirfeed += float64(tmr["maxstirfeed"].(int64))
- }
- if status == 0 {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- if lweight > 0 {
- lweight1 := lweight / float64(len(lpplandtl1List))
- number := 0
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- number++
- }
- }
- lweight := lweight / float64((len(lpplandtl1List) - number))
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- continue
- }
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- for _, item := range lpplandtl1List {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else if status == 1 {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- for _, item := range lpplandtl1List {
- if lweight > 0 {
- // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if fl >= lweight {
- item["lweight"] = fl - lweight
- lweight = 0
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- } else {
- lweight = lweight - fl
- _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- if status == 2 {
- lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func UpdateMaterialTMRDate(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- tmrid := parammaps.Get("tmrid").ValueStr()
- tmrtype := parammaps.Get("tmrtype").ValueStr()
- lppid := parammaps.Get("lppid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- date := parammaps.Get("date").ValueStr()
- // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
- status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- if tmrid != "1000" {
- tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var maxstirfeed float64
- for _, tmr := range tmrList {
- maxstirfeed += float64(tmr["maxstirfeed"].(int64))
- }
- if status == 0 {
- 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- if lweight > 0 {
- lweight1 := lweight / float64(len(lpplandtl1List))
- number := 0
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- number++
- }
- }
- lweight := lweight / float64((len(lpplandtl1List) - number))
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- continue
- }
- if tmrtype == "1" {
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- for _, item := range lpplandtl1List {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else if status == 1 {
- 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- for _, item := range lpplandtl1List {
- if lweight > 0 {
- // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if fl >= lweight {
- item["lweight"] = fl - lweight
- lweight = 0
- if tmrtype == "1" {
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- } else {
- lweight = lweight - fl
- _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- if status == 2 {
- lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func Decimal(value float64) float64 {
- value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
- return value
- }
- func UpdateDailyData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- pid := parammaps.Get("pid").ValueDefaultStr("0")
- weight := parammaps.Get("weight").ValueDefaultFloat64(0)
- sort := parammaps.Get("sort").ValueDefaultStr("0")
- location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
- date := parammaps.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- count, err := tx.SQL(`select count(1) from downloadedplan where pid in(select pid from downloadedplan where id= ? ) and havebutton = 1 and mydate = ?`, pid, date).Count()
- if err != nil {
- logs.Error("UpdateDailyData-error-0:", err)
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
- return
- }
- if count > 0 {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
- return
- }
- tx.Begin()
- if location == 0 {
- fid := parammaps.Get("fid").ValueStr()
- downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actualWeight := weight - num
- _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-2:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-3:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-4:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-5:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
- lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- // actual := actualWeight / float64(len(downloadedplanList))
- for _, item := range downloadedplanList {
- itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actual := itemLweight / lweight * actualWeight
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- } else {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
- // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- // if err != nil {
- // fmt.Println("Error:", err)
- // return
- // }
- for _, item := range downloadedplanList {
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
- item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- }
- } else {
- fbarid := parammaps.Get("fbarid").ValueStr()
- downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-10:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actualWeight := weight - num
- _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-11:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
- downloadedplan[0]["lweight"], actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-12:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
- where pid = ? `, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-13:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-14:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
- lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- for _, item := range downloadedplanList {
- itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actual := itemLweight / lweight * actualWeight
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- } else {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
- for _, item := range downloadedplanList {
- // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- // if err != nil {
- // fmt.Println("Error:", err)
- // return
- // }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
- item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error("UpdateDailyData-error-20:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetFormulaStatistics(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- startTime := parammaps.Get("startTime").ValueStr()
- endTime := parammaps.Get("endTime").ValueStr()
- pastureId := parammaps.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
- if err != nil {
- logs.Error("GetFormulaStatistics-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
- return
- }
- var feedtemplet, dateList []string
- for _, f := range feedtempletList {
- feedtemplet = append(feedtemplet, f["tname"].(string))
- }
- layout := "2006-01-02"
- // s := "2023-05-01"
- // e := "2023-05-23"
- start, err := time.Parse(layout, startTime)
- if err != nil {
- fmt.Println(err)
- return
- }
- end, err := time.Parse(layout, endTime)
- if err != nil {
- fmt.Println(err)
- return
- }
- end = end.AddDate(0, 0, 1)
- for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
- dateList = append(dateList, d.Format("2006-01-02"))
- }
- downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
- join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
- group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
- if err != nil {
- logs.Error("GetFormulaStatistics-error-2:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
- return
- }
- var data2 [][]interface{}
- for _, f := range feedtemplet {
- var data1 []interface{}
- for _, date := range dateList {
- exist := false
- for _, item := range downloadedplanList {
- if date == item["mydate"].(string) && f == item["tname"].(string) {
- data1 = append(data1, item["total"])
- exist = true
- break
- }
- }
- if !exist {
- data1 = append(data1, 0)
- }
- }
- data2 = append(data2, data1)
- }
- //前端让加的
- feedtemplet = append(feedtemplet, "")
- {
- var data1 []interface{}
- for _, f := range dateList {
- // f = f + "\n"
- fmt.Println(f)
- data1 = append(data1, 0)
- }
- data2 = append(data2, data1)
- }
- resp := make(map[string]interface{}, 0)
- resp["xdata"] = dateList
- resp["data1"] = feedtemplet
- resp["data2"] = data2
- appG.Response(http.StatusOK, e.SUCCESS, resp)
- }
- func GetPlanData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
- for _, item := range arr {
- trgaddressList := []string{}
- if _, ok := item["trgaddress"]; ok {
- trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
- for _, str := range trgaddressList1 {
- if str != "" {
- trgaddressList = append(trgaddressList, str)
- }
- }
- }
- item["trgaddressList"] = trgaddressList
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- // var wg sync.WaitGroup
- // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- // wg.Add(1)
- // go func(value map[string]interface{}) {
- // defer wg.Done()
- // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
- // }(value)
- // }
- // wg.Wait()
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostPlanData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBData err: ", string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- // paramslist := strings.Split(p, ",")
- // if len(paramslist) > 0 && p != "" {
- // for _, value := range paramslist {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- // }
- // _, err = tx.SQL(sql, s_params...).Execute()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- s_params = make([]interface{}, 0)
- paramslist := strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func CheckFeedTrgaddress(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- fclassid := fsion.Get("fclassid").ValueStr()
- feedId := fsion.Get("feedId").ValueStr()
- backup1 := fsion.Get("backup1").ValueStr()
- backup1List := strings.Split(backup1, ",")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- // if backup1 != "" {
- feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
- for _, feed := range feedList {
- if feed["backup1"] == "" {
- continue
- }
- feedbackupList := strings.Split(feed["backup1"], ",")
- for _, feedbackup := range feedbackupList {
- for _, backup := range backup1List {
- if feedbackup == backup {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
- return
- }
- }
- }
- }
- // }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func ThiGetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- if sqlnamestr == "getHomepageStr" {
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- var montimeList []float64
- var montime float64
- var wg sync.WaitGroup
- now := time.Now()
- for i := 0; i < 30; i++ {
- wg.Add(1)
- nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
- go func(nowstr string) {
- defer wg.Done()
- sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
- slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
- m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
- montimeList = append(montimeList, m)
- }(nowstr)
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- wg.Wait()
- for _, m := range montimeList {
- montime += m
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- if sqlnamestr == "getFeedTrgaddressList" {
- for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
- trgaddressList := []string{}
- for _, str := range trgaddressList1 {
- if str != "" {
- trgaddressList = append(trgaddressList, str)
- }
- }
- item["trgaddressList"] = trgaddressList
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // func ToggleCcount(c *gin.Context) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsion := gofasion.NewFasion(string(dataByte))
- // // 0 实际 1 软件
- // status := fsion.Get("status").ValueDefaultInt64(0)
- // pastureId := fsion.Get("pastureId").ValueStr()
- // tx := restful.Engine.NewSession()
- // err := tx.Begin()
- // defer func() {
- // switch {
- // case err != nil:
- // logging.Error("tx.Begin 事务启动失败__error:", err)
- // if tx != nil {
- // tx.Rollback()
- // }
- // default:
- // if tx != nil {
- // err = tx.Commit()
- // }
- // }
- // if tx != nil {
- // tx.Close()
- // }
- // }()
- // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // for _, bar := range barList {
- // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist {
- // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // }
- // if status == 0 {
- // tx.Exec(`update feedp set ccount = actualcount `)
- // }else{
- // tx.Exec(`update feedp set ccount = softccount `)
- // }
- // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // for _, feedpData :=range feedpList{
- // var feedpargs []interface{}
- // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
- // if _, ok := feedpData["ftname"]; ok {
- // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
- // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
- // } else {
- // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- // }
- // if _, ok := feedpData["ptsfname"]; ok {
- // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
- // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
- // } else {
- // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- // }
- // upFeedpSql += " where barname = ? and pastureid = ? "
- // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
- // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist1 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist2 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist3 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist4 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist5 {
- // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist6 {
- // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- // and pastureid = ? and times = ?`
- // var fpdargs1 []interface{}
- // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs2 []interface{}
- // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs3 []interface{}
- // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs4 []interface{}
- // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs5 []interface{}
- // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs6 []interface{}
- // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- // 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()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- // upFpdetailList := make([]*upFpdetail, 0)
- // for _, newfpd := range newList {
- // for _, oldfpd := range oldFpdList {
- // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- // var oldweight, newweight float64
- // if oldfpd["weight"] != nil {
- // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- // }
- // if newfpd["weight"] != nil {
- // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- // }
- // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- // upFpdetailList = append(upFpdetailList, &upFpdetail{
- // Old: oldweight,
- // New: newweight,
- // Times: newfpd["times"].(int64),
- // Ptid: newfpd["ptid"].(int64),
- // Fweight: fweight,
- // Id: oldfpd["id"].(int64),
- // })
- // break
- // }
- // }
- // }
- // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
- // }
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- // }
- func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
- feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
- if err != nil {
- return err
- }
- for _, item := range feedpList {
- // if item["ftid"].(string) != data["ftid"].(string) {
- _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
- if err != nil {
- return err
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
- if err != nil {
- return err
- }
- // }
- }
- return nil
- }
- func PostPlanDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBDatas err: ", string(dataByte))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- pastureId := fsions.Get("pastureid").ValueStr()
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
- for _, parammaps := range fsions.Get("arrList").Array() {
- fmt.Println(parammaps.Json())
- if parammaps.Json() == "null" {
- continue
- }
- // if !fsion.HasKey("arrList") {
- // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- // return
- // continue
- // }
- // parammaps := fsion.Get("arrList")
- s_params := make([]interface{}, 0)
- // paramslist := strings.Split(p, ",")
- // if len(paramslist) > 0 && p != "" {
- // for _, value := range paramslist {
- // if value == "pastureid" {
- // s_params = append(s_params, pastureId)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- // }
- // }
- // _, err = tx.SQL(sql, s_params...).Execute()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- s_params = make([]interface{}, 0)
- paramslist := strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func FpdBatchEdit(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- barList := fsions.Get("barList").Array()
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- for _, barFsions := range barList {
- dataexcel := make(map[string]interface{}, 0)
- dataexcel["barname"] = barFsions.Get("barname").ValueStr()
- dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
- dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
- dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
- dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
- if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
- continue
- }
- dataexcel["1"] = barFsions.Get("times1").ValueStr()
- dataexcel["2"] = barFsions.Get("times2").ValueStr()
- dataexcel["3"] = barFsions.Get("times3").ValueStr()
- dataexcel["4"] = barFsions.Get("times4").ValueStr()
- dataexcel["5"] = barFsions.Get("times5").ValueStr()
- dataexcel["6"] = barFsions.Get("times6").ValueStr()
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdBarSync(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdBarSync(pastureid, pastureinfo.Werks)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdFeedSync(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdFeedSync(pastureid, pastureinfo.Werks)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdFeedtempletPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdUtirPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdBarFeedRemainPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdMaterialIssuePush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func DelFeedTemplet(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- ftId := fsions.Get("ftId").ValueStr()
- // userId := fsions.Get("userId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- return
- }
- // barIdList, err := tx.SQL(`select barid from feedp where ftid = ? `, ftId).QueryString()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
- return
- }
- _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
- return
- }
- count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
- if count > 0 {
- _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
- return
- }
- }
- _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
- return
- }
- // var barIdStr []string
- // for _, bar := range barIdList {
- // barIdStr = append(barIdStr, bar["barid"])
- // }
- // if len(barIdStr) > 0 {
- // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- // now := time.Now()
- // for _, newFpd := range newFpdDataList {
- // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
- // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // }
- // for _, newFeedp := range newFeedpList {
- // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
- // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // }
- // }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
- data := fasion["parammaps"].(map[string]interface{})
- plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
- fmt.Println(err)
- plancount1, err := tx.SQL(`SELECT
- count( 1 )
- FROM
- (
- SELECT
- d.id
- FROM
- downloadedplan d
- JOIN downloadplandtl1 d1 ON d1.pid = d.id
- JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
- JOIN downloadplandtl2 d2 ON d2.pid = d.id
- WHERE
- d.mydate = ?
- AND d.havebutton = 0
- AND lpplantype IN ( 0, 1, 2 )
- AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id ) =
- ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.pid and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 )
- GROUP BY
- d.id
- ) d
- `,
- data["startTime"]).Count()
- fmt.Println(err)
- if plancount != plancount1 && number < 10 {
- number++
- ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
- checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
- }
- }
- func EditPlanSort(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- planIdStr := fsions.Get("planId").ValueStr()
- mydate := fsions.Get("mydate").ValueStr()
- sort := fsions.Get("sort").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- type downloadedplan struct {
- Id int64 `xorm:"id"`
- Sort int `xorm:"sort"`
- Pid int64 `xorm:"pid"`
- }
- planInfo := new(downloadedplan)
- err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- sort1, _ := strconv.Atoi(sort)
- if sort1 == planInfo.Sort {
- appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
- tx.Rollback()
- return
- }
- count1, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and mydate = ? `, sort, mydate, mydate).Count()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- if count1 == 0 {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
- return
- }
- count, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and havebutton = 1 and mydate = ? `, sort, mydate, mydate).Count()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- if count > 0 {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
- return
- }
- if planInfo.Sort > sort1 {
- minSortList, err := tx.SQL(`select min(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- var minSort, pidCount int
- for _, sort := range minSortList {
- minSort, _ = strconv.Atoi(sort["sort"])
- }
- planList := make([]*downloadedplan, 0)
- err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort >= ? order by sort`, mydate, minSort).Find(&planList)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- planPid := planInfo.Pid
- planList1 := make([]*downloadedplan, 0)
- planList2 := make([]*downloadedplan, 0)
- for _, plan := range planList {
- if plan.Pid == planPid {
- pidCount++
- planList1 = append(planList1, plan)
- } else {
- planList2 = append(planList2, plan)
- }
- }
- planList1 = append(planList1, planList2...)
- for i, plan := range planList1 {
- _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- } else {
- maxSortList, err := tx.SQL(`select max(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- var maxSort int
- for _, sort := range maxSortList {
- maxSort, _ = strconv.Atoi(sort["sort"])
- }
- planList := make([]*downloadedplan, 0)
- err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort <= ? order by sort`, mydate, maxSort).Find(&planList)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- planPid := planInfo.Pid
- planList1 := make([]*downloadedplan, 0)
- planList2 := make([]*downloadedplan, 0)
- for _, plan := range planList {
- if plan.Pid == planPid {
- // pidCount++
- planList1 = append(planList1, plan)
- } else {
- planList2 = append(planList2, plan)
- }
- }
- planList2 = append(planList2, planList1...)
- for i, plan := range planList2 {
- _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func EditDownloadedplanArtificial(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- planIdStr := fsions.Get("planId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- planIdList := strings.Split(planIdStr, ",")
- for _, planId := range planIdList {
- _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- type PlanRFID struct {
- RFID string `json:"RFID"`
- Lweight string `json:"lweight"`
- Gear string `json:"gear"`
- Speed string `json:"speed"`
- }
- func GetPlanRFID(c *gin.Context) {
- appG := app.Gin{C: c}
- RFIDStr := c.Query("RFID")
- planRFIDList := make([]*PlanRFID, 0)
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1411.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1322.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1904.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1870.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "2041.1",
- Gear: "1",
- Speed: "10",
- })
- appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
- }
- type tmrEquipmentMuster struct {
- A string
- N string
- }
- func GetTmrEquipmentMuster(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Query("id")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
- for _, data := range dataList {
- json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
- for _, g := range tmrEquipmentMusterList {
- a, _ := strconv.ParseFloat(g.A, 64)
- n, _ := strconv.ParseFloat(g.N, 64)
- a1, n1 := ddmmtoddd(a, n)
- g.A = fmt.Sprintf("%f", n1)
- g.N = fmt.Sprintf("%f", a1)
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
- }
- func ddmmtoddd(lng, lat float64) (float64, float64) {
- lngDegree := fmt.Sprintf("%f", lng/100)
- lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
- lngDegreeInt := int(lngDegreefloat * 1000000)
- dd := lngDegreeInt / 100 * 100 / 60
- fmt.Println(dd)
- lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
- latDegree := fmt.Sprintf("%f", lat/100)
- // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
- latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
- latDegreeInt := int(latDegreefloat * 1000000)
- latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
- a, _ := strconv.ParseFloat(lngStr, 64)
- b, _ := strconv.ParseFloat(latStr, 64)
- return coordtransform.WGS84toGCJ02(b, a)
- }
|