ops.go 403 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "path"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "tmr-watch/conf/setting"
  20. "tmr-watch/http/handle/gm"
  21. "tmr-watch/http/handle/jpud"
  22. "tmr-watch/http/handle/restful"
  23. "tmr-watch/models"
  24. "tmr-watch/module"
  25. "tmr-watch/pkg/app"
  26. "tmr-watch/pkg/e"
  27. "tmr-watch/pkg/logging"
  28. "github.com/360EntSecGroup-Skylar/excelize"
  29. "github.com/Anderson-Lu/gofasion/gofasion"
  30. "github.com/astaxie/beego/logs"
  31. "github.com/gin-gonic/gin"
  32. "github.com/qichengzx/coordtransform"
  33. "github.com/tealeg/xlsx"
  34. "github.com/xormplus/xorm"
  35. excelizexuri "github.com/xuri/excelize/v2"
  36. )
  37. // @Summary 根据SQL执行得到数据集
  38. // @Tags getData
  39. // @Accept json
  40. // @Produce json
  41. // @Param sql query string true "sql"
  42. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  43. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  44. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  45. // @Router /data/getdata [POST]
  46. func GetData(c *gin.Context) {
  47. appG := app.Gin{C: c}
  48. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  49. fsion := gofasion.NewFasion(string(dataByte))
  50. sqlstr := fsion.Get("sql").ValueStr()
  51. offset := fsion.Get("offset").ValueDefaultInt(0)
  52. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  53. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  54. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  55. if err != nil {
  56. appG.Response(http.StatusOK, e.ERROR, err.Error())
  57. } else {
  58. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  59. }
  60. }
  61. func Testpartitions(c *gin.Context) {
  62. appG := app.Gin{C: c}
  63. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  64. fsion := gofasion.NewFasion(string(dataByte))
  65. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  66. user := fsion.Get("user").ValueStr() //获取新数据库用户
  67. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  68. host := fsion.Get("host").ValueStr() //获取新数据库名称
  69. port := fsion.Get("port").ValueStr() //获取新数据库名称
  70. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  71. if sqls == nil || err1 != nil {
  72. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  73. }
  74. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  75. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  76. mydb, err := sql.Open("mysql", connecting) //连接新连接
  77. if err != nil {
  78. println("err1", err.Error())
  79. }
  80. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  81. if err != nil {
  82. println("err2", err.Error())
  83. }
  84. mydb.Close()
  85. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  86. mydb, err = sql.Open("mysql", connecting)
  87. if err != nil {
  88. println("err3", err.Error())
  89. }
  90. defer mydb.Close()
  91. if err == nil {
  92. mydb.SetMaxOpenConns(10)
  93. mydb.SetMaxIdleConns(10)
  94. }
  95. errmsg := ""
  96. if err == nil {
  97. //tx ,_ :=mydb.Begin()
  98. for _, sqlstr := range sqlstrs {
  99. //println("sqlstr---",sqlstr)
  100. if sqlstr == "" {
  101. continue
  102. }
  103. _, err = mydb.Exec(sqlstr)
  104. if err != nil {
  105. println("err4", err.Error())
  106. errmsg = err.Error()
  107. //err1 :=tx.Rollback()
  108. }
  109. }
  110. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  111. //err =tx.Commit()
  112. }
  113. if errmsg == "" {
  114. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  115. } else {
  116. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  117. }
  118. }
  119. func TestData(c *gin.Context) {
  120. appG := app.Gin{C: c}
  121. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  122. fsion := gofasion.NewFasion(string(dataByte))
  123. sqlstr := fsion.Get("sql").ValueStr()
  124. token := ""
  125. if tempv, exists := c.Get("jwt_username"); exists {
  126. token = tempv.(string)
  127. }
  128. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  129. }
  130. // @Summary 根据APISQL表中SQL执行得到数据集
  131. // @Tags GetDataByName
  132. // @Accept json
  133. // @Produce json
  134. // @Param sqlname body string true "sqlname"
  135. // @Param offset body int true "offset"
  136. // @Param pagecount body int true "pagecount"
  137. // @Param returntype body string true "returntype"
  138. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  139. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  140. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  141. // @Router /data/GetDataByName [POST]
  142. func GetDataByName(c *gin.Context) {
  143. appG := app.Gin{C: c}
  144. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  145. fsion := gofasion.NewFasion(string(dataByte))
  146. sqlnamestr := fsion.Get("name").ValueStr()
  147. offset := fsion.Get("offset").ValueDefaultInt(0)
  148. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  149. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  150. tx := restful.Engine.NewSession()
  151. err := tx.Begin()
  152. defer func() {
  153. switch {
  154. case err != nil:
  155. logging.Error("tx.Begin 事务启动失败__error:", err)
  156. if tx != nil {
  157. tx.Rollback()
  158. }
  159. default:
  160. if tx != nil {
  161. err = tx.Commit()
  162. }
  163. }
  164. if tx != nil {
  165. tx.Close()
  166. }
  167. }()
  168. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  169. if sql != "" {
  170. s_params := make([]interface{}, 0)
  171. if fsion.HasKey("parammaps") {
  172. parammaps := fsion.Get("parammaps")
  173. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  174. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  175. }
  176. paramslist := strings.Split(p, ",")
  177. if len(paramslist) > 0 && p != "" {
  178. for _, value := range paramslist {
  179. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  180. if tempv, exists := c.Get("jwt_username"); exists {
  181. s_params = append(s_params, tempv.(string))
  182. } else {
  183. s_params = append(s_params, "")
  184. }
  185. } else {
  186. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  187. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  188. // tmrNameList := []string{}
  189. // for _, tmr := range tmrArray {
  190. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  191. // }
  192. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  193. // } else {
  194. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  195. // }
  196. }
  197. }
  198. }
  199. } else if fsion.HasKey("params") {
  200. params := fsion.Get("params").Array()
  201. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  202. for _, v_params := range params {
  203. s_params = append(s_params, v_params.ValueStr())
  204. }
  205. }
  206. if returntype == "xlsx" {
  207. var xlsxfile *xlsx.File
  208. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  209. //c.File("c:/dd.xlsx")
  210. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  211. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  212. c.Header("Content-Transfer-Encoding", "binary")
  213. _ = xlsxfile.Write(c.Writer)
  214. } else {
  215. if sqlnamestr == "getHomepageStr" {
  216. parammaps := fsion.Get("parammaps")
  217. pastureid := parammaps.Get("pastureid").ValueStr()
  218. var montimeList []float64
  219. var montime float64
  220. var wg sync.WaitGroup
  221. now := time.Now()
  222. for i := 0; i < 30; i++ {
  223. wg.Add(1)
  224. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  225. go func(nowstr string) {
  226. defer wg.Done()
  227. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  228. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  229. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  230. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  231. montimeList = append(montimeList, m)
  232. }
  233. }(nowstr)
  234. }
  235. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  236. if err != nil {
  237. logging.Error("GetDataByName err: ", err)
  238. msg := geterrmsg(err.Error())
  239. appG.Response(http.StatusOK, e.ERROR, msg)
  240. }
  241. wg.Wait()
  242. for _, m := range montimeList {
  243. montime += m
  244. }
  245. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  246. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  247. return
  248. }
  249. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  250. if err != nil {
  251. logging.Error("GetDataByName err: ", err)
  252. msg := geterrmsg(err.Error())
  253. appG.Response(http.StatusOK, e.ERROR, msg)
  254. } else {
  255. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  256. }
  257. }
  258. } else {
  259. appG.Response(http.StatusOK, e.SUCCESS, nil)
  260. }
  261. }
  262. // @Summary 根据APISQL表中SQL执行得到数据集
  263. // @Tags GetDataByName
  264. // @Accept json
  265. // @Produce json
  266. // @Param sqlname body string true "sqlname"
  267. // @Param offset body int true "offset"
  268. // @Param pagecount body int true "pagecount"
  269. // @Param returntype body string true "returntype"
  270. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  271. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  272. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  273. // @Router /data/GetDataByName [POST]
  274. func GetDataBySqlIN(c *gin.Context) {
  275. appG := app.Gin{C: c}
  276. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  277. fsion := gofasion.NewFasion(string(dataByte))
  278. sqlnamestr := fsion.Get("name").ValueStr()
  279. offset := fsion.Get("offset").ValueDefaultInt(0)
  280. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  281. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  282. tx := restful.Engine.NewSession()
  283. err := tx.Begin()
  284. defer func() {
  285. switch {
  286. case err != nil:
  287. logging.Error("tx.Begin 事务启动失败__error:", err)
  288. if tx != nil {
  289. tx.Rollback()
  290. }
  291. default:
  292. if tx != nil {
  293. err = tx.Commit()
  294. }
  295. }
  296. if tx != nil {
  297. tx.Close()
  298. }
  299. }()
  300. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  301. if sql != "" {
  302. s_params := make([]interface{}, 0)
  303. if fsion.HasKey("parammaps") {
  304. parammaps := fsion.Get("parammaps")
  305. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  306. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  307. }
  308. paramslist := strings.Split(p, ",")
  309. if len(paramslist) > 0 && p != "" {
  310. for _, value := range paramslist {
  311. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  312. if tempv, exists := c.Get("jwt_username"); exists {
  313. s_params = append(s_params, tempv.(string))
  314. } else {
  315. s_params = append(s_params, "")
  316. }
  317. } else {
  318. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  319. }
  320. }
  321. }
  322. } else if fsion.HasKey("params") {
  323. params := fsion.Get("params").Array()
  324. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  325. for _, v_params := range params {
  326. s_params = append(s_params, v_params.ValueStr())
  327. }
  328. }
  329. if returntype == "xlsx" {
  330. var xlsxfile *xlsx.File
  331. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  332. //c.File("c:/dd.xlsx")
  333. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  334. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  335. c.Header("Content-Transfer-Encoding", "binary")
  336. _ = xlsxfile.Write(c.Writer)
  337. } else {
  338. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  339. if err != nil {
  340. logging.Error("GetDataByName err: ", err)
  341. msg := geterrmsg(err.Error())
  342. appG.Response(http.StatusOK, e.ERROR, msg)
  343. } else {
  344. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  345. }
  346. }
  347. } else {
  348. appG.Response(http.StatusOK, e.SUCCESS, nil)
  349. }
  350. }
  351. // 错误处理
  352. // 将报错信息处理成汉字
  353. func geterrmsg(errstr string) (msgstr string) {
  354. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  355. rs := []rune(errstr)
  356. if hzRegexp.MatchString(string(rs[0])) {
  357. msgstr = errstr
  358. return
  359. }
  360. if strings.Contains(errstr, "Duplicate entry") {
  361. strs := strings.Split(errstr, ` key '`)
  362. if len(strs) > 1 {
  363. if len(strs[len(strs)-1]) > 1 {
  364. errstr = "Duplicate entry :" + strs[len(strs)-1]
  365. }
  366. }
  367. }
  368. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  369. if err != nil {
  370. msgstr = errstr
  371. return
  372. }
  373. if msg == nil || len(msg) == 0 {
  374. var param []interface{}
  375. param = append(param, errstr, errstr)
  376. go func() {
  377. tx := restful.Engine.NewSession()
  378. err := tx.Begin()
  379. defer func() {
  380. switch {
  381. case err != nil:
  382. logging.Error("tx.Begin 事务启动失败__error:", err)
  383. if tx != nil {
  384. tx.Rollback()
  385. }
  386. default:
  387. if tx != nil {
  388. err = tx.Commit()
  389. }
  390. }
  391. if tx != nil {
  392. tx.Close()
  393. }
  394. }()
  395. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  396. if err != nil {
  397. logging.Error("insert into err_msg(err,msg) err", err)
  398. }
  399. }()
  400. msgstr = errstr
  401. } else {
  402. msgstr = msg[0]["msg"]
  403. }
  404. return
  405. }
  406. // @Summary 根据APISQL表中SQL执行得到数据集
  407. // @Tags GetDataByNameForm
  408. // @Accept json
  409. // @Produce json
  410. // @Param sqlname body json true "sqlname"
  411. // @Param offset query int true "offset"
  412. // @Param pagecount query int true "pagecount"
  413. // @Param returntype query string true "returntype"
  414. // @Param s formData json true "ss"
  415. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  416. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  417. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  418. // @Router /data/GetDataByNameForm [POST]
  419. func GetDataByNameForm(c *gin.Context) {
  420. appG := app.Gin{C: c}
  421. //sqlnamestr := c.PostForm("measureNumber")
  422. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  423. //fsion := gofasion.NewFasion(string(dataByte))
  424. //sqlnamestr := fsion.Get("name").ValueStr()
  425. //offset := fsion.Get("offset").ValueInt()
  426. //pagecount := fsion.Get("pagecount").ValueInt()
  427. //returntype := fsion.Get("returntype").ValueStr()
  428. //params := fsion.Get("params").Array()
  429. c.Request.ParseForm()
  430. params := c.Request.Form
  431. offset := 0
  432. pageSize_ := 0
  433. returntype := params.Get("page")
  434. if returntype == "" {
  435. returntype = "0"
  436. }
  437. if tempv, exists := c.Get("jwt_username"); exists {
  438. params.Set("JwtUserName", tempv.(string))
  439. } else {
  440. params.Set("JwtUserName", "")
  441. }
  442. sqlnamestr := params.Get("name")
  443. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  444. s_params := make([]interface{}, 0)
  445. if returntype == "1" {
  446. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  447. if error != nil {
  448. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  449. }
  450. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  451. if error != nil {
  452. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  453. }
  454. pageSize_ = pageSize
  455. offset = pageNum
  456. }
  457. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  458. paramslist := strings.Split(p, ",")
  459. if len(paramslist) > 0 && p != "" {
  460. for _, value := range paramslist {
  461. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  462. }
  463. }
  464. if sql != "" {
  465. if returntype == "xlsx" {
  466. var xlsxfile *xlsx.File
  467. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  468. c.Header("Content-Type", "application/octet-stream")
  469. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  470. c.Header("Content-Transfer-Encoding", "binary")
  471. _ = xlsxfile.Write(c.Writer)
  472. } else {
  473. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  474. if err != nil {
  475. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  476. } else {
  477. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  478. }
  479. }
  480. } else {
  481. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  482. }
  483. }
  484. // @Summary 递归获取所有
  485. // @Tags menu
  486. // @Accept json
  487. // @Produce json
  488. // @Param Ton query string true "Ton"
  489. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  490. // @Router /authdata/GetRoleMenus [GET]
  491. func GetRecuDataByName(c *gin.Context) {
  492. appG := app.Gin{C: c}
  493. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  494. fsion := gofasion.NewFasion(string(dataByte))
  495. sqlnamestr := fsion.Get("name").ValueStr()
  496. parentidname := fsion.Get("idname").ValueStr()
  497. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  498. params := make(map[string]interface{})
  499. s_params := make([]interface{}, 0)
  500. if fsion.HasKey("params") {
  501. for _, v_params := range fsion.Get("params").Array() {
  502. s_params = append(s_params, v_params.ValueStr())
  503. }
  504. params["params"] = s_params
  505. } else {
  506. jparams := fsion.Get("parammaps")
  507. paramslist := strings.Split(p, ",")
  508. if len(paramslist) > 0 && p != "" {
  509. for _, value := range paramslist {
  510. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  511. if tempv, exists := c.Get("jwt_username"); exists {
  512. params[value] = tempv.(string)
  513. } else {
  514. params[value] = ""
  515. }
  516. } else {
  517. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  518. }
  519. }
  520. }
  521. }
  522. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  523. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  524. if err != nil {
  525. appG.Response(http.StatusOK, e.ERROR, err.Error())
  526. }
  527. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  528. }
  529. // @Summary 根据APISQL表中SQL执行得到数据集
  530. // @Tags GetDataByNames
  531. // @Accept json
  532. // @Produce json
  533. // @RequestBody sqlname query string true "sqlname"
  534. // @Param offset query int true "offset"
  535. // @Param pagecount query int true "pagecount"
  536. // @Param returntype query string true "returntype"
  537. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  538. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  539. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  540. // @Router /data/GetDataByNames [POST]
  541. func GetDataByNames(c *gin.Context) {
  542. appG := app.Gin{C: c}
  543. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  544. fsion := gofasion.NewFasion(string(dataByte))
  545. sqlParams := fsion.Array()
  546. queryData := make(map[string]interface{})
  547. for _, v := range sqlParams {
  548. fsion2 := gofasion.NewFasion(v.Json())
  549. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  550. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  551. if sql == "" {
  552. errorm := make(map[string]interface{})
  553. errorm["code"] = e.ERROR
  554. errorm["message"] = "sql没找到"
  555. queryData[fsion2.Get("name").ValueStr()] = errorm
  556. continue
  557. } else if sql != "" {
  558. offset := fsion2.Get("offset").ValueInt()
  559. pagecount := fsion2.Get("pagecount").ValueInt()
  560. returntype := fsion2.Get("returntype").ValueStr()
  561. s_params := make([]interface{}, 0)
  562. if fsion2.HasKey("parammaps") {
  563. parammaps := fsion2.Get("parammaps")
  564. paramslist := strings.Split(p, ",")
  565. if len(paramslist) > 0 && p != "" {
  566. for _, value := range paramslist {
  567. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  568. if tempv, exists := c.Get("jwt_username"); exists {
  569. s_params = append(s_params, tempv.(string))
  570. } else {
  571. s_params = append(s_params, "")
  572. }
  573. } else {
  574. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  575. }
  576. }
  577. }
  578. } else if fsion2.HasKey("params") {
  579. params := fsion2.Get("params").Array()
  580. for _, v_params := range params {
  581. s_params = append(s_params, v_params.ValueStr())
  582. }
  583. }
  584. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  585. if err != nil {
  586. errorm := make(map[string]interface{})
  587. errorm["code"] = e.ERROR
  588. errorm["message"] = err.Error()
  589. queryData[fsion2.Get("name").ValueStr()] = errorm
  590. logging.Error("GetDataByNames err: ", err)
  591. continue
  592. } else {
  593. queryData[fsion2.Get("name").ValueStr()] = queryData1
  594. }
  595. }
  596. }
  597. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  598. }
  599. // @Summary 根据APISQL表中SQL执行得到数据集
  600. // @Tags PostDataByNameForm
  601. // @Accept json
  602. // @Produce json
  603. // @Param sqlname query string true "sqlname"
  604. // @Param offset query int true "offset"
  605. // @Param pagecount query int true "pagecount"
  606. // @Param returntype query string true "returntype"
  607. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  608. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  609. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  610. // @Router /data/PostDataByNameForm [POST]
  611. func PostDataByNameForm(c *gin.Context) {
  612. appG := app.Gin{C: c}
  613. c.Request.ParseForm()
  614. params := c.Request.Form
  615. sqlnamestr := params.Get("name")
  616. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  617. s_params := make([]interface{}, 0)
  618. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  619. paramslist := strings.Split(p, ",")
  620. if len(paramslist) > 0 {
  621. for _, value := range paramslist {
  622. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  623. }
  624. }
  625. if sql != "" {
  626. queryData, err := execDataBySql(sql, s_params)
  627. if err != nil {
  628. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  629. } else {
  630. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  631. }
  632. } else {
  633. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  634. }
  635. }
  636. // GetReportform 将数据集转换格式
  637. // @Tags PostDataByNameForm
  638. // @Accept json
  639. // @Produce json
  640. // @Param sqlname query string true "sqlname"
  641. // @Param offset query int true "offset"
  642. // @Param pagecount query int true "pagecount"
  643. // @Param returntype query string true "returntype"
  644. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  645. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  646. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  647. func GetReportform(c *gin.Context) {
  648. appG := app.Gin{C: c}
  649. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  650. fsion := gofasion.NewFasion(string(dataByte))
  651. sqlnamestr := fsion.Get("name").ValueStr()
  652. checked := fsion.Get("checked").ValueStr()
  653. offset := fsion.Get("offset").ValueDefaultInt(0)
  654. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  655. parammaps := fsion.Get("parammaps")
  656. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  657. mode := parammaps.Get("mode").ValueDefaultInt(0)
  658. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  659. tx := restful.Engine.NewSession()
  660. err := tx.Begin()
  661. defer func() {
  662. switch {
  663. case err != nil:
  664. if tx != nil {
  665. tx.Rollback()
  666. }
  667. default:
  668. if tx != nil {
  669. err = tx.Commit()
  670. }
  671. }
  672. if tx != nil {
  673. tx.Close()
  674. }
  675. }()
  676. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  677. if err != nil {
  678. appG.Response(http.StatusOK, e.ERROR, err.Error())
  679. } else {
  680. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  681. }
  682. }
  683. // GetUpkeepPlan 保养计划
  684. func GetUpkeepPlan(c *gin.Context) {
  685. appG := app.Gin{C: c}
  686. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  687. fsion := gofasion.NewFasion(string(dataByte))
  688. sqlnamestr := fsion.Get("name").ValueStr()
  689. offset := fsion.Get("offset").ValueDefaultInt(0)
  690. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  691. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  692. month := fsion.Get("month").ValueDefaultStr("map")
  693. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  694. tx := restful.Engine.NewSession()
  695. err := tx.Begin()
  696. defer func() {
  697. switch {
  698. case err != nil:
  699. if tx != nil {
  700. tx.Rollback()
  701. }
  702. default:
  703. if tx != nil {
  704. err = tx.Commit()
  705. }
  706. }
  707. if tx != nil {
  708. tx.Close()
  709. }
  710. }()
  711. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  712. if sql != "" {
  713. s_params := make([]interface{}, 0)
  714. if fsion.HasKey("parammaps") {
  715. parammaps := fsion.Get("parammaps")
  716. paramslist := strings.Split(p, ",")
  717. if len(paramslist) > 0 && p != "" {
  718. for _, value := range paramslist {
  719. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  720. if tempv, exists := c.Get("jwt_username"); exists {
  721. s_params = append(s_params, tempv.(string))
  722. } else {
  723. s_params = append(s_params, "")
  724. }
  725. } else {
  726. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  727. }
  728. }
  729. }
  730. } else if fsion.HasKey("params") {
  731. params := fsion.Get("params").Array()
  732. for _, v_params := range params {
  733. s_params = append(s_params, v_params.ValueStr())
  734. }
  735. }
  736. if returntype == "xlsx" {
  737. var xlsxfile *xlsx.File
  738. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  739. //c.File("c:/dd.xlsx")
  740. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  741. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  742. c.Header("Content-Transfer-Encoding", "binary")
  743. _ = xlsxfile.Write(c.Writer)
  744. } else {
  745. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  746. if err != nil {
  747. appG.Response(http.StatusOK, e.ERROR, err.Error())
  748. } else {
  749. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  750. if v, ok := value["id"]; ok {
  751. //month = "2020-03"
  752. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  753. if seviceplans != nil {
  754. for _, va := range seviceplans { //根据保养计划获取保养单
  755. //day,_ :=strconv.Atoi(va["day"])
  756. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  757. //buk := make(map[string]map[string]string)
  758. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  759. jstr := ""
  760. if bu["plantime"][8:9] == "0" {
  761. jstr = "m" + bu["plantime"][9:]
  762. } else {
  763. jstr = "m" + bu["plantime"][8:]
  764. }
  765. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  766. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  767. } else {
  768. if bu["flowCompeleted"] >= "2" {
  769. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  770. } else {
  771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. }
  779. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  780. }
  781. }
  782. } else {
  783. appG.Response(http.StatusOK, e.SUCCESS, nil)
  784. }
  785. }
  786. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  787. // todo 优化性能 children统一查询
  788. // @Tags PostDataByNameForm
  789. // @Accept json
  790. // @Produce json
  791. // @Param sqlname query string true "sqlname"
  792. // @Param offset query int true "offset"
  793. // @Param pagecount query int true "pagecount"
  794. // @Param returntype query string true "returntype"
  795. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  796. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  797. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  798. func GetArrList(c *gin.Context) {
  799. appG := app.Gin{C: c}
  800. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  801. fsion := gofasion.NewFasion(string(dataByte))
  802. sqlnamestr := fsion.Get("name").ValueStr()
  803. sqlnamestr1 := fsion.Get("name1").ValueStr()
  804. offset := fsion.Get("offset").ValueDefaultInt(0)
  805. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  806. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  807. month := fsion.Get("month").ValueDefaultStr("map")
  808. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  809. tx := restful.Engine.NewSession()
  810. err := tx.Begin()
  811. defer func() {
  812. switch {
  813. case err != nil:
  814. if tx != nil {
  815. tx.Rollback()
  816. }
  817. default:
  818. if tx != nil {
  819. err = tx.Commit()
  820. }
  821. }
  822. if tx != nil {
  823. tx.Close()
  824. }
  825. }()
  826. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  827. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  828. if sql != "" {
  829. s_params := make([]interface{}, 0)
  830. if fsion.HasKey("parammaps") {
  831. parammaps := fsion.Get("parammaps")
  832. paramslist := strings.Split(p, ",")
  833. if len(paramslist) > 0 && p != "" {
  834. for _, value := range paramslist {
  835. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  836. if tempv, exists := c.Get("jwt_username"); exists {
  837. s_params = append(s_params, tempv.(string))
  838. } else {
  839. s_params = append(s_params, "")
  840. }
  841. } else {
  842. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  843. }
  844. }
  845. }
  846. }
  847. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  848. if err != nil {
  849. appG.Response(http.StatusOK, e.ERROR, err.Error())
  850. } else {
  851. paramslist1 := strings.Split(p1, ",")
  852. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  853. s_params1 := make([]interface{}, 0)
  854. if len(paramslist1) > 0 && p1 != "" {
  855. for _, v := range paramslist1 {
  856. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  857. }
  858. }
  859. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  860. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  861. }
  862. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  863. }
  864. } else {
  865. appG.Response(http.StatusOK, e.SUCCESS, nil)
  866. }
  867. }
  868. func GetAccount(c *gin.Context) {
  869. appG := app.Gin{C: c}
  870. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  871. fsion := gofasion.NewFasion(string(dataByte))
  872. sqlnamestr := fsion.Get("name").ValueStr()
  873. offset := fsion.Get("offset").ValueDefaultInt(0)
  874. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  875. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  876. tx := restful.Engine.NewSession()
  877. err := tx.Begin()
  878. defer func() {
  879. switch {
  880. case err != nil:
  881. logging.Error("tx.Begin 事务启动失败__error:", err)
  882. if tx != nil {
  883. tx.Rollback()
  884. }
  885. default:
  886. if tx != nil {
  887. err = tx.Commit()
  888. }
  889. }
  890. if tx != nil {
  891. tx.Close()
  892. }
  893. }()
  894. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  895. if sql != "" {
  896. s_params := make([]interface{}, 0)
  897. if fsion.HasKey("parammaps") {
  898. parammaps := fsion.Get("parammaps")
  899. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  900. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  901. }
  902. paramslist := strings.Split(p, ",")
  903. if len(paramslist) > 0 && p != "" {
  904. for _, value := range paramslist {
  905. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  906. if tempv, exists := c.Get("jwt_username"); exists {
  907. s_params = append(s_params, tempv.(string))
  908. } else {
  909. s_params = append(s_params, "")
  910. }
  911. } else {
  912. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  913. }
  914. }
  915. }
  916. } else if fsion.HasKey("params") {
  917. params := fsion.Get("params").Array()
  918. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  919. for _, v_params := range params {
  920. s_params = append(s_params, v_params.ValueStr())
  921. }
  922. }
  923. if returntype == "xlsx" {
  924. var xlsxfile *xlsx.File
  925. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  926. //c.File("c:/dd.xlsx")
  927. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  928. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  929. c.Header("Content-Transfer-Encoding", "binary")
  930. _ = xlsxfile.Write(c.Writer)
  931. } else {
  932. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  933. if err != nil {
  934. logging.Error("GetDataByName err: ", err)
  935. msg := geterrmsg(err.Error())
  936. appG.Response(http.StatusOK, e.ERROR, msg)
  937. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  938. } else {
  939. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  940. }
  941. }
  942. } else {
  943. appG.Response(http.StatusOK, e.SUCCESS, nil)
  944. }
  945. }
  946. // PostDataByName 根据APISQL表中SQL执行得到数据集
  947. // @Accept json
  948. // @Produce json
  949. // @Param sqlname query string true "sqlname"
  950. // @Param offset query int true "offset"
  951. // @Param pagecount query int true "pagecount"
  952. // @Param returntype query string true "returntype"
  953. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  954. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  955. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  956. // @Router /data/PostDataByName [POST]
  957. func PostDataByName(c *gin.Context) {
  958. appG := app.Gin{C: c}
  959. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  960. fsion := gofasion.NewFasion(string(dataByte))
  961. var err error
  962. queryData, err := module.PostDataByName(c, fsion)
  963. if err != nil {
  964. appG.Response(http.StatusOK, e.ERROR, err.Error())
  965. return
  966. }
  967. var (
  968. keyWord string
  969. )
  970. switch fsion.Get("name").ValueStr() {
  971. case "insertFeedclass":
  972. keyWord = "feed"
  973. err = module.GroupCategorySync(keyWord, fsion)
  974. case "deleteFeedclass":
  975. keyWord = "feed_delete"
  976. err = module.GroupCategoryDelete(keyWord, fsion)
  977. case "insertCowclass":
  978. keyWord = "cow"
  979. err = module.GroupCategorySync(keyWord, fsion)
  980. case "deleteCowclass":
  981. keyWord = "cow_delete"
  982. err = module.GroupCategoryDelete(keyWord, fsion)
  983. // case "updateFT":
  984. // FtdetailSurplus(fsion)
  985. // case "updateFeed":
  986. // FeedSurplus(fsion)
  987. default:
  988. }
  989. if err != nil {
  990. logging.Error(keyWord, err)
  991. }
  992. if queryData != nil {
  993. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  994. return
  995. }
  996. appG.Response(http.StatusOK, e.SUCCESS, nil)
  997. }
  998. //人脸识别/格润富德接口
  999. func GetRJSBData(c *gin.Context) {
  1000. appG := app.Gin{C: c}
  1001. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1002. fsion := gofasion.NewFasion(string(dataByte))
  1003. sqlnamestr := fsion.Get("name").ValueStr()
  1004. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1005. offset := fsion.Get("offset").ValueDefaultInt(0)
  1006. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1007. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1008. month := fsion.Get("month").ValueDefaultStr("map")
  1009. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1010. pagecount = 1
  1011. tx := restful.Engine.NewSession()
  1012. err := tx.Begin()
  1013. defer func() {
  1014. switch {
  1015. case err != nil:
  1016. if tx != nil {
  1017. tx.Rollback()
  1018. }
  1019. default:
  1020. if tx != nil {
  1021. err = tx.Commit()
  1022. }
  1023. }
  1024. if tx != nil {
  1025. tx.Close()
  1026. }
  1027. }()
  1028. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1029. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1030. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1031. if sql != "" {
  1032. s_params := make([]interface{}, 0)
  1033. if fsion.HasKey("parammaps") {
  1034. parammaps := fsion.Get("parammaps")
  1035. paramslist := strings.Split(p, ",")
  1036. if len(paramslist) > 0 && p != "" {
  1037. for _, value := range paramslist {
  1038. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1039. if tempv, exists := c.Get("jwt_username"); exists {
  1040. s_params = append(s_params, tempv.(string))
  1041. } else {
  1042. s_params = append(s_params, "")
  1043. }
  1044. } else {
  1045. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1046. }
  1047. }
  1048. }
  1049. }
  1050. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1051. if err != nil {
  1052. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1053. } else {
  1054. paramslist1 := strings.Split(p1, ",")
  1055. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1056. s_params1 := make([]interface{}, 0)
  1057. if len(paramslist1) > 0 && p1 != "" {
  1058. for _, v := range paramslist1 {
  1059. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1060. }
  1061. }
  1062. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1063. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1064. }
  1065. var wg sync.WaitGroup
  1066. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1067. wg.Add(1)
  1068. go func(value map[string]interface{}) {
  1069. defer wg.Done()
  1070. // ,havebutton = 1
  1071. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1072. }(value)
  1073. }
  1074. wg.Wait()
  1075. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1076. }
  1077. } else {
  1078. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1079. }
  1080. }
  1081. func PostRJSBData(c *gin.Context) {
  1082. appG := app.Gin{C: c}
  1083. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1084. fsion := gofasion.NewFasion(string(dataByte))
  1085. logging.Info("PostRJSBData err: ", string(dataByte))
  1086. s_params := make([]interface{}, 0)
  1087. tx := restful.Engine.NewSession()
  1088. err := tx.Begin()
  1089. defer func() {
  1090. switch {
  1091. case err != nil:
  1092. if tx != nil {
  1093. tx.Rollback()
  1094. }
  1095. default:
  1096. if tx != nil {
  1097. err = tx.Commit()
  1098. }
  1099. }
  1100. if tx != nil {
  1101. tx.Close()
  1102. }
  1103. }()
  1104. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1105. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1106. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1107. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1108. if !fsion.HasKey("parammaps") {
  1109. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1110. return
  1111. }
  1112. parammaps := fsion.Get("parammaps")
  1113. paramslist := strings.Split(p, ",")
  1114. if len(paramslist) > 0 && p != "" {
  1115. for _, value := range paramslist {
  1116. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1117. }
  1118. }
  1119. projuctid := parammaps.Get("projuctid").ValueStr()
  1120. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1121. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1122. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1123. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1124. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1125. if err != nil {
  1126. logging.Error("PostRJSBData-0 err: ", err)
  1127. msg := geterrmsg(err.Error())
  1128. // appG.Response(http.StatusOK, e.ERROR, msg)
  1129. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1130. return
  1131. }
  1132. _, err = tx.SQL(sql, s_params...).Execute()
  1133. if err != nil {
  1134. logging.Error("PostRJSBData err: ", err)
  1135. msg := geterrmsg(err.Error())
  1136. // appG.Response(http.StatusOK, e.ERROR, msg)
  1137. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1138. return
  1139. }
  1140. s_params = make([]interface{}, 0)
  1141. paramslist = strings.Split(p1, ",")
  1142. if len(paramslist) > 0 && p1 != "" {
  1143. for _, value := range paramslist {
  1144. // if value == "ID" {
  1145. // id := parammaps.Get("ID").ValueStr()
  1146. // pastureid := parammaps.Get("pastureid").ValueStr()
  1147. // 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
  1148. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1149. // if err != nil {
  1150. // logging.Error("PostRJSBData err: ", err)
  1151. // msg := geterrmsg(err.Error())
  1152. // appG.Response(http.StatusOK, e.ERROR, msg)
  1153. // return
  1154. // }
  1155. // for _, item := range datalist {
  1156. // id = item["id"]
  1157. // }
  1158. // s_params = append(s_params, id)
  1159. // } else {
  1160. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1161. // }
  1162. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1163. }
  1164. }
  1165. _, err = tx.SQL(sql1, s_params...).Execute()
  1166. if err != nil {
  1167. logging.Error("PostRJSBData1 err: ", err)
  1168. msg := geterrmsg(err.Error())
  1169. appG.Response(http.StatusOK, e.ERROR, msg)
  1170. return
  1171. }
  1172. s_params = make([]interface{}, 0)
  1173. paramslist = strings.Split(p2, ",")
  1174. if len(paramslist) > 0 && p2 != "" {
  1175. for _, value := range paramslist {
  1176. if value == "ID" {
  1177. id := parammaps.Get("ID").ValueStr()
  1178. pastureid := parammaps.Get("pastureid").ValueStr()
  1179. 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
  1180. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1181. if err != nil {
  1182. logging.Error("PostRJSBData err: ", err)
  1183. msg := geterrmsg(err.Error())
  1184. appG.Response(http.StatusOK, e.ERROR, msg)
  1185. return
  1186. }
  1187. for _, item := range datalist {
  1188. id = item["id"]
  1189. }
  1190. s_params = append(s_params, id)
  1191. } else {
  1192. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1193. }
  1194. }
  1195. }
  1196. _, err = tx.SQL(sql2, s_params...).Execute()
  1197. if err != nil {
  1198. logging.Error("PostRJSBData2 err: ", err)
  1199. msg := geterrmsg(err.Error())
  1200. appG.Response(http.StatusOK, e.ERROR, msg)
  1201. return
  1202. }
  1203. s_params = make([]interface{}, 0)
  1204. paramslist = strings.Split(p3, ",")
  1205. if len(paramslist) > 0 && p3 != "" {
  1206. for _, value := range paramslist {
  1207. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1208. }
  1209. }
  1210. _, err = tx.SQL(sql3, s_params...).Execute()
  1211. if err != nil {
  1212. logging.Error("PostRJSBData3 err: ", err)
  1213. msg := geterrmsg(err.Error())
  1214. appG.Response(http.StatusOK, e.ERROR, msg)
  1215. return
  1216. }
  1217. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1218. }
  1219. func PostRJSBDatas(c *gin.Context) {
  1220. appG := app.Gin{C: c}
  1221. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1222. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1223. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1224. fmt.Println(string(dataByte))
  1225. tx := restful.Engine.NewSession()
  1226. err := tx.Begin()
  1227. defer func() {
  1228. switch {
  1229. case err != nil:
  1230. if tx != nil {
  1231. tx.Rollback()
  1232. }
  1233. default:
  1234. if tx != nil {
  1235. err = tx.Commit()
  1236. }
  1237. }
  1238. if tx != nil {
  1239. tx.Close()
  1240. }
  1241. }()
  1242. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1243. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1244. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1245. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1246. for _, fsion := range fsions {
  1247. if !fsion.HasKey("parammaps") {
  1248. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1249. return
  1250. }
  1251. parammaps := fsion.Get("parammaps")
  1252. ID := parammaps.Get("ID").ValueStr()
  1253. if ID == "" {
  1254. continue
  1255. }
  1256. s_params := make([]interface{}, 0)
  1257. paramslist := strings.Split(p, ",")
  1258. if len(paramslist) > 0 && p != "" {
  1259. for _, value := range paramslist {
  1260. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1261. }
  1262. }
  1263. // ALTER TABLE `tmr`
  1264. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1265. projuctid := parammaps.Get("projuctid").ValueStr()
  1266. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1267. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1268. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1269. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1270. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData-0 err: ", err)
  1273. msg := geterrmsg(err.Error())
  1274. // appG.Response(http.StatusOK, e.ERROR, msg)
  1275. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1276. return
  1277. }
  1278. _, err = tx.SQL(sql, s_params...).Execute()
  1279. if err != nil {
  1280. logging.Error("PostRJSBData err: ", err)
  1281. msg := geterrmsg(err.Error())
  1282. // appG.Response(http.StatusOK, e.ERROR, msg)
  1283. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1284. return
  1285. }
  1286. s_params = make([]interface{}, 0)
  1287. paramslist = strings.Split(p1, ",")
  1288. if len(paramslist) > 0 && p1 != "" {
  1289. for _, value := range paramslist {
  1290. // if value == "ID" {
  1291. // id := parammaps.Get("ID").ValueStr()
  1292. // pastureid := parammaps.Get("pastureid").ValueStr()
  1293. // 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
  1294. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1295. // if err != nil {
  1296. // logging.Error("PostRJSBData err: ", err)
  1297. // msg := geterrmsg(err.Error())
  1298. // appG.Response(http.StatusOK, e.ERROR, msg)
  1299. // return
  1300. // }
  1301. // for _, item := range datalist {
  1302. // id = item["id"]
  1303. // }
  1304. // s_params = append(s_params, id)
  1305. // } else {
  1306. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1307. // }
  1308. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1309. }
  1310. }
  1311. _, err = tx.SQL(sql1, s_params...).Execute()
  1312. if err != nil {
  1313. logging.Error("PostRJSBData1 err: ", err)
  1314. msg := geterrmsg(err.Error())
  1315. appG.Response(http.StatusOK, e.ERROR, msg)
  1316. return
  1317. }
  1318. s_params = make([]interface{}, 0)
  1319. paramslist = strings.Split(p2, ",")
  1320. if len(paramslist) > 0 && p2 != "" {
  1321. for _, value := range paramslist {
  1322. if value == "ID" {
  1323. id := parammaps.Get("ID").ValueStr()
  1324. pastureid := parammaps.Get("pastureid").ValueStr()
  1325. 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
  1326. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1327. if err != nil {
  1328. logging.Error("PostRJSBData err: ", err)
  1329. msg := geterrmsg(err.Error())
  1330. appG.Response(http.StatusOK, e.ERROR, msg)
  1331. return
  1332. }
  1333. for _, item := range datalist {
  1334. id = item["id"]
  1335. }
  1336. s_params = append(s_params, id)
  1337. } else {
  1338. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1339. }
  1340. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1341. }
  1342. }
  1343. _, err = tx.SQL(sql2, s_params...).Execute()
  1344. if err != nil {
  1345. logging.Error("PostRJSBData2 err: ", err)
  1346. msg := geterrmsg(err.Error())
  1347. appG.Response(http.StatusOK, e.ERROR, msg)
  1348. return
  1349. }
  1350. s_params = make([]interface{}, 0)
  1351. paramslist = strings.Split(p3, ",")
  1352. if len(paramslist) > 0 && p3 != "" {
  1353. for _, value := range paramslist {
  1354. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1355. }
  1356. }
  1357. _, err = tx.SQL(sql3, s_params...).Execute()
  1358. if err != nil {
  1359. logging.Error("PostRJSBData3 err: ", err)
  1360. msg := geterrmsg(err.Error())
  1361. appG.Response(http.StatusOK, e.ERROR, msg)
  1362. return
  1363. }
  1364. }
  1365. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1366. }
  1367. // @Summary 根据APISQL表中SQL执行得到数据集
  1368. // @Tags ExecDataByConfig
  1369. // @Accept json
  1370. // @Produce json
  1371. // @Param sqlname query string true "sqlname"
  1372. // @Param offset query int true "offset"
  1373. // @Param pagecount query int true "pagecount"
  1374. // @Param returntype query string true "returntype"
  1375. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1376. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1377. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1378. // @Router /data/PostDataByName [POST]
  1379. func ExecDataByConfig(c *gin.Context) {
  1380. appG := app.Gin{C: c}
  1381. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1382. tempval_ := make(map[string]interface{})
  1383. tempCommon := make(map[string]interface{})
  1384. tempval := make([]map[string]interface{}, 0)
  1385. err := json.Unmarshal(dataByte, &tempval_)
  1386. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1387. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1388. if err != nil {
  1389. } else {
  1390. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1391. tempCommon = v
  1392. }
  1393. if v, ok := tempval_["data"].([]interface{}); ok {
  1394. for _, Tvalue := range v {
  1395. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1396. tempval = append(tempval, v1)
  1397. }
  1398. }
  1399. }
  1400. tx := restful.Engine.NewSession()
  1401. err := tx.Begin()
  1402. if err != nil {
  1403. logging.Error("tx.Begin 事务启动失败__error:", err)
  1404. }
  1405. defer func() {
  1406. switch {
  1407. case err != nil:
  1408. if tx != nil {
  1409. tx.Rollback()
  1410. }
  1411. default:
  1412. if tx != nil {
  1413. err = tx.Commit()
  1414. }
  1415. }
  1416. if tx != nil {
  1417. tx.Close()
  1418. }
  1419. }()
  1420. if err == nil {
  1421. if tempv, exists := c.Get("jwt_username"); exists {
  1422. tempCommon["jwt_username"] = tempv.(string)
  1423. }
  1424. for _, paramvalue := range tempval {
  1425. fmt.Println(paramvalue["name"])
  1426. if paramvalue["name"].(string) == "updateBigFP" {
  1427. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1428. if err != nil {
  1429. msg := geterrmsg(err.Error())
  1430. appG.Response(http.StatusOK, e.ERROR, msg)
  1431. return
  1432. }
  1433. }
  1434. }
  1435. for _, paramvalue := range tempval {
  1436. if _, ok := paramvalue["resultname"]; !ok {
  1437. paramvalue["resultname"] = paramvalue["name"]
  1438. }
  1439. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1440. if err != nil {
  1441. logging.Error("ExecDataParam error:", err)
  1442. break
  1443. }
  1444. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1445. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1446. // }
  1447. }
  1448. if err == nil {
  1449. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1450. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1451. } else {
  1452. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1453. }
  1454. } else {
  1455. msg := geterrmsg(err.Error())
  1456. appG.Response(http.StatusOK, e.ERROR, msg)
  1457. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1458. }
  1459. }
  1460. }
  1461. if err != nil {
  1462. msg := geterrmsg(err.Error())
  1463. appG.Response(http.StatusOK, e.ERROR, msg)
  1464. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1465. }
  1466. }
  1467. func interfacetostring(val interface{}) string {
  1468. switch val.(type) {
  1469. case string:
  1470. ss := val.(string)
  1471. return ss
  1472. break
  1473. case int:
  1474. ss := val.(int)
  1475. return strconv.Itoa(ss)
  1476. break
  1477. case int64:
  1478. ss := val.(int64)
  1479. return strconv.FormatInt(ss, 10)
  1480. break
  1481. case float64:
  1482. ss := val.(float64)
  1483. return strconv.FormatFloat(ss, 'E', -1, 32)
  1484. break
  1485. }
  1486. return ""
  1487. }
  1488. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1489. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1490. tempstrb := strings.IndexAny(valuestring, "@")
  1491. tempstre := strings.IndexAny(valuestring, ".")
  1492. if tempstrb > -1 && tempstre > -1 {
  1493. for _, ParamMapList := range ParamMap {
  1494. if v, ok := ParamMapList["resultname"]; ok {
  1495. if v == valuestring[tempstrb+1:tempstre] {
  1496. if v1, ok := ParamMapList["resultmaps"]; ok {
  1497. if newA, ok := v1.([]map[string]interface{}); ok {
  1498. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1499. } else if newA, ok := v1.(map[string]interface{}); ok {
  1500. return interfacetostring(newA[valuestring[tempstre+1:]])
  1501. }
  1502. }
  1503. }
  1504. }
  1505. }
  1506. } else {
  1507. return valuestring
  1508. }
  1509. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1510. return fmt.Sprintf("%f", valuestring)
  1511. }
  1512. return ""
  1513. }
  1514. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1515. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1516. tempstrb := strings.IndexAny(valuestring, "@")
  1517. tempstre := strings.IndexAny(valuestring, ".")
  1518. if tempstrb > -1 && tempstre > -1 {
  1519. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1520. if s, ok := v.(string); ok {
  1521. return s
  1522. } else if s, ok := v.(float64); ok {
  1523. return strconv.FormatFloat(s, 'f', -1, 64)
  1524. // return strconv.FormatInt(int64(s), 10)
  1525. }
  1526. }
  1527. }
  1528. }
  1529. return ""
  1530. }
  1531. 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) {
  1532. sqlname := fasion["name"].(string)
  1533. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1534. if v, ok := fasion["type"]; ok {
  1535. sqltype = v.(string)
  1536. }
  1537. sql := ""
  1538. p := ""
  1539. s_params := make([]interface{}, 0)
  1540. if sqltype != "" {
  1541. sql, p = restful.GetSqlByName(sqlname, tx)
  1542. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1543. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1544. paramslist := strings.Split(p, ",")
  1545. if len(paramslist) > 0 && p != "" {
  1546. for _, value := range paramslist {
  1547. ss := ""
  1548. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1549. ids, err := setting.SnowIds.NextId()
  1550. if err != nil {
  1551. ids = time.Now().UnixNano()
  1552. logging.Info("create SnowIds err", err)
  1553. }
  1554. s_params = append(s_params, ids)
  1555. } else {
  1556. if ss == "" && CommonParamMap != nil {
  1557. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1558. ss = valuestring
  1559. tempstrb := strings.IndexAny(valuestring, "@")
  1560. tempstre := strings.IndexAny(valuestring, ".")
  1561. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1562. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1563. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1564. }
  1565. } else {
  1566. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1567. ss = ""
  1568. }
  1569. }
  1570. }
  1571. }
  1572. if ss == "" && ParentParamMap != nil {
  1573. ss = getParamValue_(v, value, ParentParamMap)
  1574. }
  1575. if ss == "" && sameParamMap != nil {
  1576. ss = getParamValue(v, value, sameParamMap)
  1577. }
  1578. if ss == "" && ParamMap != nil {
  1579. ss = getParamValue(v, value, ParamMap)
  1580. }
  1581. s_params = append(s_params, ss)
  1582. }
  1583. }
  1584. }
  1585. }
  1586. }
  1587. if sql == "" {
  1588. sqltype = ""
  1589. }
  1590. if sqltype == "s1" {
  1591. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1592. if v, ok := tempValParam.(map[string]interface{}); ok {
  1593. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1594. }
  1595. if err != nil {
  1596. return nil, err
  1597. }
  1598. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1599. if err != nil {
  1600. return nil, err
  1601. }
  1602. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1603. } else if sqltype == "sm" {
  1604. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1605. if v, ok := tempValParam.(map[string]interface{}); ok {
  1606. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1607. } else {
  1608. }
  1609. if err != nil {
  1610. return nil, err
  1611. }
  1612. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1613. if err != nil {
  1614. return nil, err
  1615. }
  1616. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1617. } else if sqltype == "v" {
  1618. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1619. if v, ok := tempValParam.(map[string]interface{}); ok {
  1620. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1621. } else {
  1622. }
  1623. if err != nil {
  1624. return nil, err
  1625. }
  1626. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1627. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1628. }
  1629. } else if sqltype == "e" {
  1630. tempVal_arrary := make([]map[string]interface{}, 0)
  1631. tempVal_map := make(map[string]interface{})
  1632. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1633. if err == nil {
  1634. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1635. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1636. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1637. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1638. return tempVal_arrary, err
  1639. }
  1640. return nil, err
  1641. } else {
  1642. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1643. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1644. if err != nil {
  1645. return nil, err
  1646. }
  1647. return nil, err
  1648. }
  1649. }
  1650. return nil, nil
  1651. }
  1652. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1653. var err error
  1654. subarray, ok := fasion["children"]
  1655. if ok {
  1656. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1657. tempVal_arrary := make([]map[string]interface{}, 0)
  1658. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1659. tempVal_ := make(map[string]interface{})
  1660. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1661. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1662. } else {
  1663. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1664. }
  1665. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1666. if err != nil {
  1667. return err
  1668. }
  1669. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1670. }
  1671. v.(map[string]interface{})["children"] = tempVal_arrary
  1672. }
  1673. }
  1674. return nil
  1675. }
  1676. // @Summary 删除图片
  1677. // @Tags RemovePicByName
  1678. // @Accept json
  1679. // @Produce json
  1680. // @Param sqlname query string true "sqlname"
  1681. // @Param offset query int true "offset"
  1682. // @Param pagecount query int true "pagecount"
  1683. // @Param returntype query string true "returntype"
  1684. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1685. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1686. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1687. // @Router /data/PostDataByName [POST]
  1688. func RemovePicByName(c *gin.Context) {
  1689. logging.Info("RemovePicByName ", c.Keys)
  1690. appG := app.Gin{C: c}
  1691. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1692. fsion := gofasion.NewFasion(string(dataByte))
  1693. sqlnamestr := fsion.Get("name").ValueStr()
  1694. picname := fsion.Get("picname").ValueStr()
  1695. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1696. params := fsion.Get("params").Array()
  1697. s_params := make([]interface{}, 0)
  1698. for _, v_params := range params {
  1699. s_params = append(s_params, v_params.ValueStr())
  1700. }
  1701. if sql != "" {
  1702. queryData, err := execDataBySql(sql, s_params)
  1703. if picname != "" {
  1704. // Destination
  1705. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1706. err := os.Remove(distPath) //删除文件test.txt
  1707. if err != nil {
  1708. //如果删除失败则输出 file remove Error!
  1709. fmt.Println("file remove Error!")
  1710. //输出错误详细信息
  1711. fmt.Printf("%s", err)
  1712. } else {
  1713. //如果删除成功则输出 file remove OK!
  1714. fmt.Print("file remove OK!")
  1715. }
  1716. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1717. err = os.Remove(distPath) //删除文件test.txt
  1718. if err != nil {
  1719. //如果删除失败则输出 file remove Error!
  1720. fmt.Println("file remove Error!")
  1721. //输出错误详细信息
  1722. fmt.Printf("%s", err)
  1723. } else {
  1724. //如果删除成功则输出 file remove OK!
  1725. fmt.Print("file remove OK!")
  1726. }
  1727. }
  1728. if err != nil {
  1729. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1730. } else {
  1731. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1732. }
  1733. } else {
  1734. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1735. }
  1736. }
  1737. // @Summary 删除文件
  1738. // @Tags RemoveFileByName
  1739. // @Accept json
  1740. // @Produce json
  1741. // @Param sqlname query string true "sqlname"
  1742. // @Param offset query int true "offset"
  1743. // @Param pagecount query int true "pagecount"
  1744. // @Param returntype query string true "returntype"
  1745. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1746. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1747. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1748. // @Router /data/PostDataByName [POST]
  1749. func RemoveFileByName(c *gin.Context) {
  1750. appG := app.Gin{C: c}
  1751. id := c.Param("id")
  1752. logging.Info("DownloadFile ", c.Keys, id)
  1753. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1754. if eqdoc == nil {
  1755. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1756. return
  1757. }
  1758. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1759. err = os.Remove(distPath) //删除文件test.txt
  1760. if err != nil {
  1761. //如果删除失败则输出 file remove Error!
  1762. fmt.Println("file remove Error!")
  1763. //输出错误详细信息
  1764. fmt.Printf("%s", err)
  1765. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1766. return
  1767. }
  1768. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1769. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1770. }
  1771. // @Summary 根据APISQL表中SQL执行得到数据集
  1772. // @Tags PostDataByName
  1773. // @Accept json
  1774. // @Produce json
  1775. // @Param sqlname query string true "sqlname"
  1776. // @Param offset query int true "offset"
  1777. // @Param pagecount query int true "pagecount"
  1778. // @Param returntype query string true "returntype"
  1779. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1780. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1781. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1782. // @Router /data/PostDataByName [POST]
  1783. func UpdateDataRelation(c *gin.Context) {
  1784. appG := app.Gin{C: c}
  1785. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1786. fsion := gofasion.NewFasion(string(dataByte))
  1787. tablename := fsion.Get("name").ValueStr()
  1788. dataname := fsion.Get("dataname").ValueStr()
  1789. datavalue := fsion.Get("datavalue").ValueStr()
  1790. valuename := fsion.Get("valuename").ValueStr()
  1791. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1792. values := fsion.Get("values").Array()
  1793. tx := restful.Engine.NewSession()
  1794. err := tx.Begin()
  1795. defer func() {
  1796. switch {
  1797. case err != nil:
  1798. if tx != nil {
  1799. tx.Rollback()
  1800. }
  1801. default:
  1802. if tx != nil {
  1803. err = tx.Commit()
  1804. }
  1805. }
  1806. if tx != nil {
  1807. tx.Close()
  1808. }
  1809. }()
  1810. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1811. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1812. d_params := make([]interface{}, 4)
  1813. d_params[0] = datavalue
  1814. s_params := ""
  1815. for _, v_values := range values {
  1816. d_params[1] = v_values.ValueStr()
  1817. if s_params == "" {
  1818. s_params = v_values.ValueStr()
  1819. } else {
  1820. s_params = s_params + "," + v_values.ValueStr()
  1821. }
  1822. d_params[2] = d_params[1]
  1823. d_params[3] = d_params[0]
  1824. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1825. if err != nil {
  1826. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1827. break
  1828. }
  1829. }
  1830. if s_params != "" {
  1831. deleteSqlstr := "delete from " + tablename + " " +
  1832. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1833. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1834. if err != nil {
  1835. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1836. } else if err == nil {
  1837. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1838. }
  1839. } else {
  1840. deleteSqlstr := "delete from " + tablename + " " +
  1841. " where " + dataname + " = " + datavalue
  1842. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1843. if err != nil {
  1844. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1845. } else if err == nil {
  1846. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1847. }
  1848. }
  1849. }
  1850. // @Summary 根据APISQL表中SQL执行得到数据集
  1851. // @Tags PostDatasByName
  1852. // @Accept json
  1853. // @Produce json
  1854. // @Param sqlname query string true "sqlname"
  1855. // @Param offset query int true "offset"
  1856. // @Param pagecount query int true "pagecount"
  1857. // @Param returntype query string true "returntype"
  1858. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1859. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1860. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1861. // @Router /data/PostDatasByName [POST]
  1862. func PostDataByNames(c *gin.Context) {
  1863. appG := app.Gin{C: c}
  1864. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1865. fsion := gofasion.NewFasion(string(dataByte))
  1866. sqlParams := fsion.Get("array").Array()
  1867. queryData := make(map[string]interface{})
  1868. for _, v := range sqlParams {
  1869. fsion2 := gofasion.NewFasion(v.Json())
  1870. ss := fsion2.Get("name")
  1871. aa := fsion2.Get("params")
  1872. fmt.Println(ss, aa)
  1873. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1874. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1875. if sql == "" {
  1876. errorm := make(map[string]interface{})
  1877. errorm["code"] = e.ERROR
  1878. errorm["message"] = "sql没有找到"
  1879. errorm["param"] = ""
  1880. queryData[fsion2.Get("name").ValueStr()] = errorm
  1881. continue
  1882. } else if sql != "" {
  1883. s_params := make([]interface{}, 0)
  1884. if fsion2.HasKey("parammaps") {
  1885. parammaps := fsion2.Get("parammaps")
  1886. paramslist := strings.Split(p, ",")
  1887. if len(paramslist) > 0 && p != "" {
  1888. for _, value := range paramslist {
  1889. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1890. if tempv, exists := c.Get("jwt_username"); exists {
  1891. s_params = append(s_params, tempv.(string))
  1892. } else {
  1893. s_params = append(s_params, "")
  1894. }
  1895. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1896. ids, err := setting.SnowIds.NextId()
  1897. if err != nil {
  1898. ids = time.Now().UnixNano()
  1899. logging.Info("create SnowIds err", err)
  1900. }
  1901. s_params = append(s_params, ids)
  1902. } else {
  1903. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1904. }
  1905. }
  1906. }
  1907. } else if fsion2.HasKey("params") {
  1908. params := fsion2.Get("params").Array()
  1909. //ids,err := setting.SnowIds.NextId()
  1910. //if err !=nil{
  1911. // ids = time.Now().UnixNano()
  1912. // logging.Info("create SnowIds err",err)
  1913. //}
  1914. //s_params = append(s_params, ids)
  1915. for _, v_params := range params {
  1916. s_params = append(s_params, v_params.ValueStr())
  1917. }
  1918. }
  1919. _, err := execDataBySql(sql, s_params)
  1920. if err != nil {
  1921. logging.Error("PostDataByName err: ", err)
  1922. errorm := make(map[string]interface{})
  1923. errorm["code"] = e.ERROR
  1924. errorm["message"] = err.Error()
  1925. errorm["param"] = s_params
  1926. queryData[fsion2.Get("name").ValueStr()] = errorm
  1927. continue
  1928. } else {
  1929. errorm := make(map[string]interface{})
  1930. errorm["code"] = e.SUCCESS
  1931. errorm["message"] = "success"
  1932. queryData[fsion2.Get("name").ValueStr()] = errorm
  1933. continue
  1934. }
  1935. } else {
  1936. errorm := make(map[string]interface{})
  1937. errorm["code"] = e.ERROR
  1938. errorm["message"] = "NO SQL"
  1939. errorm["param"] = ""
  1940. queryData[fsion2.Get("name").ValueStr()] = errorm
  1941. }
  1942. }
  1943. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1944. }
  1945. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1946. if offset > 0 {
  1947. offset = offset - 1
  1948. }
  1949. //if pagecount == 0 {
  1950. // pagecount = setting.AppSetting.PageSize
  1951. //}else if pagecount>setting.AppSetting.PageSize{
  1952. // pagecount = setting.AppSetting.PageSize
  1953. //}
  1954. if returntype == "list" {
  1955. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1956. return queryData, err
  1957. } else if returntype == "listlist" {
  1958. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1959. return queryData, err
  1960. } else {
  1961. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1962. return queryData, err
  1963. }
  1964. }
  1965. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1966. if offset > 0 {
  1967. offset = offset - 1
  1968. }
  1969. //if pagecount == 0 {
  1970. // pagecount = setting.AppSetting.PageSize
  1971. //}else if pagecount>setting.AppSetting.PageSize{
  1972. // pagecount = setting.AppSetting.PageSize
  1973. //}
  1974. if returntype == "list" {
  1975. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1976. return queryData, err
  1977. } else if returntype == "listlist" {
  1978. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1979. return queryData, err
  1980. } else {
  1981. fmt.Println(params)
  1982. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1983. return queryData, err
  1984. }
  1985. }
  1986. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1987. paramslist := strings.Split(Params, ",")
  1988. s_params := make([]interface{}, 0)
  1989. if isList {
  1990. for _, v_params := range thisParams["params"].([]interface{}) {
  1991. s_params = append(s_params, v_params)
  1992. }
  1993. } else {
  1994. paramslist := strings.Split(Params, ",")
  1995. if len(paramslist) > 0 && Params != "" {
  1996. for _, value := range paramslist {
  1997. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1998. }
  1999. }
  2000. }
  2001. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2002. for _, queryData_ := range queryData {
  2003. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2004. if isList {
  2005. if queryData_[idname] != nil {
  2006. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2007. }
  2008. } else {
  2009. if queryData_[idname] != nil {
  2010. thisParams[idname] = queryData_[idname].(interface{})
  2011. }
  2012. if len(paramslist) > 0 && Params != "" {
  2013. s_params = make([]interface{}, 0)
  2014. for _, value := range paramslist {
  2015. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2016. }
  2017. }
  2018. }
  2019. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2020. } else {
  2021. }
  2022. }
  2023. return queryData, err
  2024. }
  2025. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2026. queryData, err := restful.ExecQuery(sqlstr, params)
  2027. return queryData, err
  2028. }
  2029. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2030. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2031. return queryData, err
  2032. }
  2033. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2034. queryData, err := restful.ExecQuery(sqlstr, params)
  2035. return queryData, err
  2036. }
  2037. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2038. // @Tags ImportExcel
  2039. // @Accept json
  2040. // @Produce json
  2041. // @Param file query string true "文件名"
  2042. // @Param name header string true "执行sql的名字"
  2043. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2044. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2045. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2046. // @Router /data/ImportExcel [POST]
  2047. func ImportExcel(c *gin.Context) {
  2048. appG := app.Gin{C: c}
  2049. inputdata := ""
  2050. c.Request.ParseForm()
  2051. params := c.Request.Form
  2052. file, _, err := c.Request.FormFile("file")
  2053. if err != nil {
  2054. appG.Response(http.StatusOK, e.ERROR, err)
  2055. return
  2056. }
  2057. sqlnamestrs := params.Get("name")
  2058. sheetname := params.Get("sheetname")
  2059. pastureid := params.Get("pastureid")
  2060. //importParams := params.Get("importParams")
  2061. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2062. // 必输项参数 (字符串格式 "field1,field2,field3")
  2063. requiredParams := params.Get("requiredParams")
  2064. // 日期参数
  2065. dateParams := params.Get("dateParams")
  2066. // 数字参数
  2067. numParams := params.Get("numParams")
  2068. //将字符串分割开
  2069. dateParamslist := strings.Split(dateParams, ",")
  2070. requiredParamslist := strings.Split(requiredParams, ",")
  2071. numParamslist := strings.Split(numParams, ",")
  2072. queryData := make([]interface{}, 0)
  2073. sqlslist := strings.Split(sqlnamestrs, ",")
  2074. xlsx1, err := excelize.OpenReader(file)
  2075. if err != nil {
  2076. fmt.Println(err)
  2077. return
  2078. }
  2079. ok := 0
  2080. error := 0
  2081. isdone := true
  2082. rows := xlsx1.GetRows(sheetname)
  2083. // 限制10000条,多余的截取掉
  2084. if len(rows) > 10000 {
  2085. rows = rows[:10000]
  2086. }
  2087. for i, row := range rows {
  2088. if i > 0 {
  2089. entry := make(map[string]interface{})
  2090. outentry := make(map[string]interface{})
  2091. for j, colCell := range rows[0] {
  2092. for k, colCell1 := range row {
  2093. if j == k {
  2094. outentry[colCell] = colCell1
  2095. entry[colCell] = colCell1
  2096. }
  2097. }
  2098. }
  2099. inputdata = ""
  2100. a := ""
  2101. fmt.Println(outentry, entry)
  2102. //校验日期格式
  2103. for _, v := range dateParamslist {
  2104. if v == "" {
  2105. continue
  2106. }
  2107. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2108. dtime, err := TransfTime(d.(string))
  2109. if err != nil {
  2110. a = strings.Trim(v, " ")
  2111. break
  2112. }
  2113. outentry[strings.Trim(v, " ")] = dtime
  2114. }
  2115. }
  2116. if a != "" {
  2117. outentry["error_msg"] = a + " 格式错误"
  2118. error++
  2119. queryData = append(queryData, outentry)
  2120. continue
  2121. }
  2122. a = ""
  2123. //校验必填格式
  2124. for _, v := range requiredParamslist {
  2125. if v == "" {
  2126. continue
  2127. }
  2128. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2129. a = strings.Trim(v, " ")
  2130. break
  2131. }
  2132. }
  2133. if a != "" {
  2134. outentry["error_msg"] = a + " 未填或格式错误"
  2135. error++
  2136. queryData = append(queryData, outentry)
  2137. continue
  2138. }
  2139. a = ""
  2140. //校验数字格式
  2141. for _, v := range numParamslist {
  2142. if v == "" {
  2143. continue
  2144. }
  2145. d, ok := outentry[strings.Trim(v, " ")]
  2146. if !ok || d == "" {
  2147. outentry[strings.Trim(v, " ")] = 0
  2148. } else {
  2149. var fl float64
  2150. switch d.(type) {
  2151. case string:
  2152. fl, err = strconv.ParseFloat(d.(string), 64)
  2153. }
  2154. if err != nil || fl < 0 {
  2155. a = strings.Trim(v, " ")
  2156. break
  2157. }
  2158. }
  2159. }
  2160. if a != "" {
  2161. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2162. error++
  2163. queryData = append(queryData, outentry)
  2164. continue
  2165. }
  2166. tx := restful.Engine.NewSession()
  2167. err := tx.Begin()
  2168. for _, sqlnamestr := range sqlslist {
  2169. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2170. paramslist := strings.Split(paramslists, ",")
  2171. if len(paramslist) > 0 {
  2172. s_params := make([]interface{}, 0)
  2173. for _, value := range paramslist {
  2174. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2175. if tempv, exists := c.Get("jwt_username"); exists {
  2176. s_params = append(s_params, tempv.(string))
  2177. } else {
  2178. s_params = append(s_params, "")
  2179. }
  2180. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2181. s_params = append(s_params, pastureid)
  2182. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2183. ids, err := setting.SnowIds.NextId()
  2184. if err != nil {
  2185. ids = time.Now().UnixNano()
  2186. logging.Info("create SnowIds err", err)
  2187. }
  2188. s_params = append(s_params, ids)
  2189. } else {
  2190. if outentry[strings.Trim(value, " ")] == nil {
  2191. s_params = append(s_params, "")
  2192. } else {
  2193. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2194. }
  2195. }
  2196. }
  2197. outentry["input"] = inputdata
  2198. fmt.Println(sql, s_params)
  2199. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2200. if err != nil {
  2201. if tx != nil {
  2202. tx.Rollback()
  2203. }
  2204. if tx != nil {
  2205. tx.Close()
  2206. }
  2207. msg := geterrmsg(err.Error())
  2208. outentry["error_msg"] = msg
  2209. error++
  2210. queryData = append(queryData, outentry)
  2211. isdone = true
  2212. break
  2213. } else {
  2214. if len(returnmsgmap1) > 0 {
  2215. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2216. if tx != nil {
  2217. tx.Rollback()
  2218. }
  2219. if tx != nil {
  2220. tx.Close()
  2221. }
  2222. msg := geterrmsg(va.(string))
  2223. outentry["error_msg"] = msg
  2224. error++
  2225. queryData = append(queryData, outentry)
  2226. isdone = true
  2227. break
  2228. }
  2229. }
  2230. isdone = false
  2231. }
  2232. }
  2233. }
  2234. switch {
  2235. case err != nil:
  2236. if tx != nil {
  2237. tx.Rollback()
  2238. }
  2239. default:
  2240. if tx != nil {
  2241. err = tx.Commit()
  2242. }
  2243. }
  2244. if tx != nil {
  2245. tx.Close()
  2246. }
  2247. }
  2248. if !isdone {
  2249. ok++
  2250. isdone = true
  2251. }
  2252. }
  2253. data := make(map[string]interface{})
  2254. data["result"] = queryData
  2255. data["success"] = ok
  2256. data["err_count"] = error
  2257. appG.Response(http.StatusOK, e.SUCCESS, data)
  2258. }
  2259. func TransfTime(timestr string) (string, error) {
  2260. if timestr == "" {
  2261. return time.Now().Format("2006-01-02"), nil
  2262. }
  2263. days, err := strconv.Atoi(timestr)
  2264. if err != nil {
  2265. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2266. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2267. }
  2268. _, err := time.Parse("2006-01-02", timestr)
  2269. if err != nil {
  2270. t, err := time.Parse("2006/01/02", timestr)
  2271. if err != nil {
  2272. t, err := time.Parse("2006.01.02", timestr)
  2273. if err != nil {
  2274. return "", err
  2275. } else {
  2276. return t.Format("2006-01-02"), nil
  2277. }
  2278. } else {
  2279. return t.Format("2006-01-02"), nil
  2280. }
  2281. } else {
  2282. return timestr, nil
  2283. }
  2284. }
  2285. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2286. times = times.AddDate(0, 0, days)
  2287. return times.Format("2006-01-02"), nil
  2288. }
  2289. func Createchart(c *gin.Context) {
  2290. appG := app.Gin{C: c}
  2291. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2292. fsion := gofasion.NewFasion(string(dataByte))
  2293. chart_name := fsion.Get("chart_name").ValueStr()
  2294. desc := fsion.Get("desc").ValueStr()
  2295. pastureid := fsion.Get("pastureid").ValueStr()
  2296. source_id := fsion.Get("source_id").ValueStr()
  2297. emp := fsion.Get("emp").ValueStr()
  2298. content := fsion.Get("content").Json()
  2299. var mapResult map[string]interface{}
  2300. err1 := json.Unmarshal([]byte(content), &mapResult)
  2301. if err1 != nil {
  2302. fmt.Println("JsonToMapDemo err: ", err1)
  2303. }
  2304. tx := restful.Engine.NewSession()
  2305. err := tx.Begin()
  2306. defer func() {
  2307. switch {
  2308. case err != nil:
  2309. logging.Error("tx.Begin 事务启动失败__error:", err)
  2310. if tx != nil {
  2311. tx.Rollback()
  2312. }
  2313. default:
  2314. if tx != nil {
  2315. err = tx.Commit()
  2316. }
  2317. }
  2318. if tx != nil {
  2319. tx.Close()
  2320. }
  2321. }()
  2322. ids, err := setting.SnowIds.NextId()
  2323. if err != nil {
  2324. ids = time.Now().UnixNano()
  2325. logging.Info("create SnowIds err", err)
  2326. }
  2327. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2328. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2329. if err != nil {
  2330. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2331. } else {
  2332. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2333. }
  2334. }
  2335. func Updatedashboard(c *gin.Context) {
  2336. appG := app.Gin{C: c}
  2337. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2338. fsion := gofasion.NewFasion(string(dataByte))
  2339. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2340. pastureid := fsion.Get("pastureid").ValueStr()
  2341. content := fsion.Get("content").Json()
  2342. var mapResult map[string]interface{}
  2343. err1 := json.Unmarshal([]byte(content), &mapResult)
  2344. if err1 != nil {
  2345. fmt.Println("JsonToMapDemo err: ", err1)
  2346. }
  2347. layout := mapResult["layout"]
  2348. tx := restful.Engine.NewSession()
  2349. err := tx.Begin()
  2350. defer func() {
  2351. switch {
  2352. case err != nil:
  2353. logging.Error("tx.Begin 事务启动失败__error:", err)
  2354. if tx != nil {
  2355. tx.Rollback()
  2356. }
  2357. default:
  2358. if tx != nil {
  2359. err = tx.Commit()
  2360. }
  2361. }
  2362. if tx != nil {
  2363. tx.Close()
  2364. }
  2365. }()
  2366. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2367. if err != nil {
  2368. println("2", err.Error())
  2369. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2370. } else {
  2371. if exec != nil {
  2372. if exec[0]["content"] == nil {
  2373. mapR := make(map[string]interface{})
  2374. mapR["layout"] = layout
  2375. mjson, _ := json.Marshal(mapR)
  2376. mString := string(mjson)
  2377. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2378. if err3 != nil {
  2379. println("3", err3.Error())
  2380. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2381. } else {
  2382. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2383. }
  2384. } else {
  2385. var mapR map[string]interface{}
  2386. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2387. if err1 != nil {
  2388. fmt.Println("JsonToMapDemo err: ", err2)
  2389. }
  2390. mapR["layout"] = layout
  2391. mjson, _ := json.Marshal(mapR)
  2392. mString := string(mjson)
  2393. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2394. if err3 != nil {
  2395. println("3", err3.Error())
  2396. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2397. } else {
  2398. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2399. }
  2400. }
  2401. } else {
  2402. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2403. }
  2404. }
  2405. }
  2406. func ExecSQL(c *gin.Context) {
  2407. appG := app.Gin{C: c}
  2408. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2409. fsion := gofasion.NewFasion(string(dataByte))
  2410. content := fsion.Get("content").Json()
  2411. pastureid := fsion.Get("pastureid").ValueStr()
  2412. var mapResult map[string]interface{}
  2413. err1 := json.Unmarshal([]byte(content), &mapResult)
  2414. if err1 != nil {
  2415. fmt.Println("JsonToMapDemo err: ", err1)
  2416. }
  2417. sqlstr := "select "
  2418. groupstr := " GROUP BY "
  2419. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2420. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2421. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2422. }
  2423. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2424. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2425. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2426. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2427. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2428. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2429. sqlstr = sqlstr + tem + ","
  2430. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2431. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2432. sqlstr = sqlstr + tem + ","
  2433. } else {
  2434. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2435. sqlstr = sqlstr + tem + ","
  2436. }
  2437. }
  2438. if _, ok := mapResult["selectedCalcul2"]; ok {
  2439. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2440. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2441. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2442. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2443. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2444. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2445. sqlstr = sqlstr + tem + ","
  2446. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2447. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2448. sqlstr = sqlstr + tem + ","
  2449. } else {
  2450. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2451. sqlstr = sqlstr + tem + ","
  2452. }
  2453. }
  2454. }
  2455. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2456. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2457. sqlstr = sqlstr + " where pastureid=" + pastureid
  2458. if len(mapResult["filters"].([]interface{})) > 0 {
  2459. sqlstr = sqlstr + " and "
  2460. }
  2461. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2462. for _, value := range mapResult["filters"].([]interface{}) {
  2463. switch value.(map[string]interface{})["filterOperator"].(string) {
  2464. case ">", "=", "<", ">=", "<=", "!=", "like":
  2465. 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 "
  2466. case "IN":
  2467. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2468. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2469. sqlstr = sqlstr + value1.(string) + ","
  2470. }
  2471. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2472. sqlstr = sqlstr + ")" + " AND "
  2473. case "BETWEEN":
  2474. 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 "
  2475. }
  2476. }
  2477. if len(mapResult["filters"].([]interface{})) > 0 {
  2478. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2479. }
  2480. //
  2481. groupstr = groupstr[0 : len(groupstr)-1]
  2482. sqlstr = sqlstr + groupstr + " "
  2483. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2484. sqlstr = sqlstr + " order by "
  2485. }
  2486. //
  2487. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2488. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2489. sqlstr = sqlstr + value.(string) + " "
  2490. } else {
  2491. sqlstr = sqlstr + value.(string) + ","
  2492. }
  2493. }
  2494. //
  2495. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2496. tx := restful.Engine.NewSession()
  2497. err := tx.Begin()
  2498. defer func() {
  2499. switch {
  2500. case err != nil:
  2501. logging.Error("tx.Begin 事务启动失败__error:", err)
  2502. if tx != nil {
  2503. tx.Rollback()
  2504. }
  2505. default:
  2506. if tx != nil {
  2507. err = tx.Commit()
  2508. }
  2509. }
  2510. if tx != nil {
  2511. tx.Close()
  2512. }
  2513. }()
  2514. exec, err := tx.SQL(sqlstr).Query().List()
  2515. if err != nil {
  2516. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2517. } else {
  2518. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2519. }
  2520. }
  2521. func Dashboards(c *gin.Context) {
  2522. appG := app.Gin{C: c}
  2523. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2524. fsion := gofasion.NewFasion(string(dataByte))
  2525. sqlnamestr := fsion.Get("name").ValueStr()
  2526. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2527. offset := fsion.Get("offset").ValueDefaultInt(0)
  2528. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2529. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2530. month := fsion.Get("month").ValueDefaultStr("map")
  2531. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2532. tx := restful.Engine.NewSession()
  2533. err := tx.Begin()
  2534. defer func() {
  2535. switch {
  2536. case err != nil:
  2537. if tx != nil {
  2538. tx.Rollback()
  2539. }
  2540. default:
  2541. if tx != nil {
  2542. err = tx.Commit()
  2543. }
  2544. }
  2545. if tx != nil {
  2546. tx.Close()
  2547. }
  2548. }()
  2549. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2550. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2551. if sql != "" {
  2552. s_params := make([]interface{}, 0)
  2553. if fsion.HasKey("parammaps") {
  2554. parammaps := fsion.Get("parammaps")
  2555. paramslist := strings.Split(p, ",")
  2556. if len(paramslist) > 0 && p != "" {
  2557. for _, value := range paramslist {
  2558. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2559. if tempv, exists := c.Get("jwt_username"); exists {
  2560. s_params = append(s_params, tempv.(string))
  2561. } else {
  2562. s_params = append(s_params, "")
  2563. }
  2564. } else {
  2565. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2566. }
  2567. }
  2568. }
  2569. }
  2570. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2571. if err != nil {
  2572. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2573. } else {
  2574. //paramslist1 := strings.Split(p1, ",")
  2575. dids := make([]interface{}, 0)
  2576. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2577. var mapResult map[string]interface{}
  2578. dids = append(dids, value["dashboard_id"])
  2579. if value["content"] != nil {
  2580. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2581. if err1 != nil {
  2582. println("JsonToMapDemo1 err: ", err1)
  2583. }
  2584. temap := make(map[string]interface{})
  2585. tem := mapResult["layout"].([]interface{})
  2586. if v, ok := value["chartids"]; ok {
  2587. chartids := strings.Split(v.(string), ",")
  2588. for _, va := range chartids {
  2589. a := false
  2590. for _, v2 := range tem {
  2591. if v2.(map[string]interface{})["id"].(string) == va {
  2592. a = true
  2593. //println("va1======",va)
  2594. }
  2595. }
  2596. if !a {
  2597. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2598. va + "\",\"id\":\"" + va +
  2599. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2600. var mapTem map[string]interface{}
  2601. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2602. if err1 != nil {
  2603. println("JsonToMapDemo err: ", err1)
  2604. }
  2605. tem = append(tem, mapTem)
  2606. }
  2607. }
  2608. temap["layout"] = tem
  2609. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2610. }
  2611. } else {
  2612. temap := make(map[string]interface{})
  2613. tem := make([]interface{}, 0)
  2614. if v, ok := value["chartids"]; ok {
  2615. chartids := strings.Split(v.(string), ",")
  2616. for _, va := range chartids {
  2617. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2618. va + "\",\"id\":\"" + va +
  2619. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2620. var mapTem map[string]interface{}
  2621. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2622. if err1 != nil {
  2623. println("JsonToMapDemo err: ", err1)
  2624. }
  2625. tem = append(tem, mapTem)
  2626. }
  2627. temap["layout"] = tem
  2628. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2629. }
  2630. }
  2631. }
  2632. queryData.(map[string]interface{})["order"] = dids
  2633. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2634. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2635. }
  2636. } else {
  2637. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2638. }
  2639. }
  2640. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2641. fsion := gofasion.NewFasion(parammaps)
  2642. sqlnamestr := fsion.Get("name").ValueStr()
  2643. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2644. offset := fsion.Get("offset").ValueDefaultInt(0)
  2645. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2646. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2647. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2648. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2649. body := []byte("")
  2650. if sql != "" {
  2651. s_params := make([]interface{}, 0)
  2652. if fsion.HasKey("parammaps") {
  2653. parammaps := fsion.Get("parammaps")
  2654. paramslist := strings.Split(p, ",")
  2655. if len(paramslist) > 0 && p != "" {
  2656. for _, value := range paramslist {
  2657. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2658. }
  2659. }
  2660. }
  2661. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2662. if err != nil {
  2663. } else {
  2664. paramslist1 := strings.Split(p1, ",")
  2665. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2666. s_params1 := make([]interface{}, 0)
  2667. if len(paramslist1) > 0 && p1 != "" {
  2668. for _, v := range paramslist1 {
  2669. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2670. }
  2671. }
  2672. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2673. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2674. body, _ = json.Marshal(queryData)
  2675. }
  2676. }
  2677. }
  2678. bs := bytes.NewBuffer(body)
  2679. client := &http.Client{}
  2680. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2681. req, err := http.NewRequest(RequestMethod,
  2682. url,
  2683. bs,
  2684. )
  2685. if err != nil {
  2686. }
  2687. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2688. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2689. if err != nil {
  2690. // handle error
  2691. }
  2692. resp, err := client.Do(req)
  2693. if err != nil {
  2694. return ""
  2695. }
  2696. defer resp.Body.Close()
  2697. result_body, err := ioutil.ReadAll(resp.Body)
  2698. if err != nil {
  2699. return ""
  2700. }
  2701. fmt.Println(string(result_body))
  2702. return ""
  2703. }
  2704. func GetSummary(c *gin.Context) {
  2705. appG := app.Gin{C: c}
  2706. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2707. fsion := gofasion.NewFasion(string(dataByte))
  2708. offset := fsion.Get("offset").ValueDefaultInt(0)
  2709. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2710. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2711. parammaps := fsion.Get("parammaps")
  2712. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2713. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2714. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2715. tx := restful.Engine.NewSession()
  2716. defer tx.Close()
  2717. sqlnamestr := ""
  2718. if genre == "0" {
  2719. if status == "0" {
  2720. sqlnamestr = "getAccuracyJSY"
  2721. } else if status == "1" {
  2722. sqlnamestr = "getAccuracyHFT"
  2723. } else if status == "2" {
  2724. sqlnamestr = "getAccuracyHNS"
  2725. } else if status == "3" {
  2726. sqlnamestr = "getAccuracyHSC"
  2727. } else if status == "4" {
  2728. sqlnamestr = "getAccuracyHCC"
  2729. } else if status == "5" {
  2730. sqlnamestr = "getAccuracyMC"
  2731. } else if status == "6" {
  2732. sqlnamestr = "getAccuracyFeedHL"
  2733. } else if status == "7" {
  2734. sqlnamestr = "getAccuracyRT"
  2735. }
  2736. } else {
  2737. if status == "0" {
  2738. sqlnamestr = "getAccuracySCCJSY"
  2739. } else if status == "1" {
  2740. sqlnamestr = "getAccuracySFT"
  2741. } else if status == "2" {
  2742. sqlnamestr = "getAccuracySNS"
  2743. } else if status == "3" {
  2744. sqlnamestr = "getAccuracySSC"
  2745. } else if status == "4" {
  2746. sqlnamestr = "getAccuracySCC"
  2747. } else if status == "5" {
  2748. sqlnamestr = "getAccuracySLCL"
  2749. } else if status == "7" {
  2750. sqlnamestr = "getAccuracySCCRT"
  2751. }
  2752. }
  2753. if isDate == "1" {
  2754. sqlnamestr += "Date"
  2755. }
  2756. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2757. // fmt.Println(sqlnamestr, sql)
  2758. if sql != "" {
  2759. s_params := make([]interface{}, 0)
  2760. // if fsion.HasKey("parammaps") {
  2761. fmt.Println(s_params, "222", p)
  2762. paramslist := strings.Split(p, ",")
  2763. if len(paramslist) > 0 && p != "" {
  2764. for _, value := range paramslist {
  2765. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2766. if tempv, exists := c.Get("jwt_username"); exists {
  2767. s_params = append(s_params, tempv.(string))
  2768. } else {
  2769. s_params = append(s_params, "")
  2770. }
  2771. } else {
  2772. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2773. }
  2774. }
  2775. }
  2776. if returntype == "xlsx" {
  2777. var xlsxfile *xlsx.File
  2778. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2779. //c.File("c:/dd.xlsx")
  2780. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2781. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2782. c.Header("Content-Transfer-Encoding", "binary")
  2783. _ = xlsxfile.Write(c.Writer)
  2784. } else {
  2785. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2786. if err != nil {
  2787. logging.Error("GetDataByName err: ", err)
  2788. msg := geterrmsg(err.Error())
  2789. appG.Response(http.StatusOK, e.ERROR, msg)
  2790. } else {
  2791. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2792. }
  2793. }
  2794. } else {
  2795. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2796. }
  2797. }
  2798. // type lpplanStruct struct {
  2799. // Id int64 `xorm:"id"`
  2800. // Tmrname string `xorm:"tmrname"`
  2801. // Tmrid int64 `xorm:"tmrid"`
  2802. // Sort int64 `xorm:"sort"`
  2803. // Sel int64 `xorm:"sel"`
  2804. // Times int64 `xorm:"times"`
  2805. // Ftname string `xorm:"ftname"`
  2806. // Ftid int64 `xorm:"ftid"`
  2807. // Maxweight float64 `xorm:"maxweight"`
  2808. // Sumweight float64 `xorm:"sumweight"`
  2809. // Sumcowcount int64 `xorm:"sumcowcount"`
  2810. // Pastureid string `xorm:"pastureid"`
  2811. // Display string `xorm:"display"`
  2812. // Issplit int64 `xorm:"issplit"`
  2813. // BeginTime string `xorm:"begintime"`
  2814. // }
  2815. func UpdateFTdetail(c *gin.Context) {
  2816. appG := app.Gin{C: c}
  2817. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2818. tempval_ := make(map[string]interface{})
  2819. tempCommon := make(map[string]interface{})
  2820. tempval := make([]map[string]interface{}, 0)
  2821. fTChange := make(map[string]interface{}, 0)
  2822. fpdOldDataList := make([]map[string]interface{}, 0)
  2823. fpdDataList := make([]map[string]interface{}, 0)
  2824. fsion := gofasion.NewFasion(string(dataByte))
  2825. // parammaps := fsion.Get("parammaps")
  2826. createdate := time.Now().Format("2006-01-02 15:04:05")
  2827. err := json.Unmarshal(dataByte, &tempval_)
  2828. if err != nil {
  2829. appG.Response(http.StatusOK, e.ERROR, false)
  2830. return
  2831. }
  2832. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2833. tx := restful.Engine.NewSession()
  2834. if v, ok := tempval_["data"].([]interface{}); ok {
  2835. for _, Tvalue := range v {
  2836. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2837. if v1["name"] == "updateFPbyFTChange" {
  2838. fTChange = v1
  2839. continue
  2840. }
  2841. tempval = append(tempval, v1)
  2842. }
  2843. }
  2844. }
  2845. parammaps := fTChange["parammaps"].(map[string]interface{})
  2846. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2847. // if err != nil {
  2848. // logs.Error(err)
  2849. // appG.Response(http.StatusOK, e.ERROR, false)
  2850. // return
  2851. // }
  2852. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2853. // if err != nil {
  2854. // logs.Error(err)
  2855. // appG.Response(http.StatusOK, e.ERROR, false)
  2856. // return
  2857. // }
  2858. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2859. // if err != nil {
  2860. // logs.Error(err)
  2861. // appG.Response(http.StatusOK, e.ERROR, false)
  2862. // return
  2863. // }
  2864. err = tx.Begin()
  2865. if err != nil {
  2866. logging.Error("tx.Begin 事务启动失败__error:", err)
  2867. }
  2868. defer func() {
  2869. if err != nil {
  2870. if tx != nil {
  2871. tx.Rollback()
  2872. }
  2873. }
  2874. if tx != nil {
  2875. tx.Close()
  2876. }
  2877. }()
  2878. if err != nil {
  2879. } else {
  2880. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2881. tempCommon = v
  2882. }
  2883. 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 ,
  2884. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2885. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2886. UNION
  2887. 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 ,
  2888. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2889. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2890. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2891. if err == nil {
  2892. if tempv, exists := c.Get("jwt_username"); exists {
  2893. tempCommon["jwt_username"] = tempv.(string)
  2894. }
  2895. for _, paramvalue := range tempval {
  2896. if _, ok := paramvalue["resultname"]; !ok {
  2897. paramvalue["resultname"] = paramvalue["name"]
  2898. }
  2899. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2900. if err != nil {
  2901. logging.Error("ExecDataParam error:", err)
  2902. break
  2903. }
  2904. }
  2905. if err != nil {
  2906. msg := geterrmsg(err.Error())
  2907. appG.Response(http.StatusOK, e.ERROR, msg)
  2908. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2909. }
  2910. }
  2911. }
  2912. tx.Commit()
  2913. // go func() {
  2914. if fTChange != nil {
  2915. parammaps := fTChange["parammaps"].(map[string]interface{})
  2916. if parammaps["type"].(float64) == 1 {
  2917. _, err = tx.SQL(`UPDATE feedp fp
  2918. set
  2919. ccountratio = ccount *(ratio /100 ),
  2920. fp.ftweight= IFNULL(IF(
  2921. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2922. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2923. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2924. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2925. ),0),fp.feedweight = IFNULL(IF(
  2926. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2927. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2928. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2929. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2930. ),0) +ifnull(fp.supplyweight,0)
  2931. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2932. _, err = tx.SQL(`UPDATE fpdetail fpd
  2933. INNER JOIN feedp fp
  2934. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2935. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2936. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2937. } else {
  2938. _, err = tx.SQL(`UPDATE feedp fp
  2939. SET ccountratio = ccount *(ratio /100 ),
  2940. fp.supplyweight= IFNULL(IF(
  2941. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2942. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2943. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2944. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2945. ),0),fp.feedweight = IFNULL(IF(
  2946. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2947. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2948. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2949. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2950. ),0) +ifnull(fp.supplyweight,0)
  2951. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2952. _, err = tx.SQL(`UPDATE fpdetail fpd
  2953. INNER JOIN feedp fp
  2954. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2955. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2956. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2957. }
  2958. 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 ,
  2959. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2960. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2961. UNION
  2962. 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 ,
  2963. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2964. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2965. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2966. lpplanList := make([]*lpplanStruct, 0)
  2967. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2968. if err != nil {
  2969. logs.Error(err, 1)
  2970. return
  2971. }
  2972. lppidlist := []string{}
  2973. for _, lpp := range lpplanList {
  2974. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2975. }
  2976. if len(lppidlist) <= 0 {
  2977. appG.Response(http.StatusOK, e.SUCCESS, true)
  2978. return
  2979. }
  2980. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2981. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2982. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2983. if err != nil {
  2984. // tx.Rollback()
  2985. logs.Error(err, 2, parammaps["pastureid"])
  2986. return
  2987. }
  2988. // for _, lpp := range lpplandtl1AllList {
  2989. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  2990. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  2991. // if err != nil {
  2992. // logs.Error(err)
  2993. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  2994. // return
  2995. // }
  2996. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  2997. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  2998. // if err != nil {
  2999. // logs.Error(err)
  3000. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3001. // return
  3002. // }
  3003. // }
  3004. var wg sync.WaitGroup
  3005. for _, old := range fpdOldDataList {
  3006. for _, fpd := range fpdDataList {
  3007. wg.Add(1)
  3008. go func(old, fpd map[string]interface{}) {
  3009. updateLppandList := make([]*lpplandtl1, 0)
  3010. defer wg.Done()
  3011. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3012. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3013. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3014. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3015. // if weight > oldweight {
  3016. // return
  3017. // }
  3018. var w float64
  3019. var status int
  3020. if weight < oldweight {
  3021. if weight >= 0 {
  3022. return
  3023. }
  3024. w = weight
  3025. status = 0
  3026. } else {
  3027. if oldweight > 0 {
  3028. return
  3029. }
  3030. w = weight
  3031. status = 1
  3032. }
  3033. // fweight = w
  3034. for _, lpp := range lpplanList {
  3035. var fweight float64
  3036. var lweight float64
  3037. lpplandtl1List := make([]*lpplandtl1, 0)
  3038. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3039. for _, lppland := range lpplandtl1AllList {
  3040. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3041. lpplandtl1List = append(lpplandtl1List, lppland)
  3042. }
  3043. }
  3044. if len(lpplandtl1List) == 0 {
  3045. continue
  3046. }
  3047. for _, lppland := range lpplandtl1List {
  3048. lweight += lppland.Lweight
  3049. }
  3050. if status == 0 {
  3051. if lweight <= 0 {
  3052. continue
  3053. }
  3054. } else {
  3055. if lpp.Maxweight <= lweight {
  3056. continue
  3057. }
  3058. }
  3059. for _, lppland := range lpplandtl1List {
  3060. if fpdid == lppland.Fpdid {
  3061. if status == 1 {
  3062. // if w <= lppland.Lweight {
  3063. if lpp.Maxweight <= lweight {
  3064. continue
  3065. }
  3066. if w+lweight <= lpp.Maxweight {
  3067. lppland.Lweight += w
  3068. lweight += w
  3069. fweight += w
  3070. w = 0
  3071. } else {
  3072. w = w - (lpp.Maxweight - lweight)
  3073. n := (lpp.Maxweight - lweight)
  3074. lppland.Lweight = lppland.Lweight + n
  3075. lweight += n
  3076. fweight += n
  3077. }
  3078. } else {
  3079. if lppland.Lweight == 0 {
  3080. continue
  3081. }
  3082. if w+lppland.Lweight >= 0 {
  3083. lppland.Lweight = lppland.Lweight + w
  3084. lweight = lweight + w
  3085. fweight = fweight + w
  3086. w = 0
  3087. } else {
  3088. w = w + lppland.Lweight
  3089. lweight = lweight - lppland.Lweight
  3090. fweight = fweight - lppland.Lweight
  3091. lppland.Lweight = 0
  3092. }
  3093. }
  3094. updateLppandList = append(updateLppandList, lppland)
  3095. break
  3096. }
  3097. }
  3098. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3099. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3100. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3101. if err != nil {
  3102. // tx.Rollback()
  3103. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3104. return
  3105. }
  3106. for _, lppland := range updateLppandList {
  3107. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3108. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3109. if err != nil {
  3110. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3111. // tx.Rollback()
  3112. logs.Error(err, 3)
  3113. return
  3114. }
  3115. // defer wg.Done()
  3116. }
  3117. updateLppandList = []*lpplandtl1{}
  3118. if w == 0 {
  3119. break
  3120. }
  3121. }
  3122. }
  3123. }(old, fpd)
  3124. }
  3125. }
  3126. wg.Wait()
  3127. }
  3128. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3129. if err != nil {
  3130. logs.Error(err)
  3131. appG.Response(http.StatusOK, e.ERROR, false)
  3132. return
  3133. }
  3134. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3135. if err != nil {
  3136. logs.Error(err)
  3137. appG.Response(http.StatusOK, e.ERROR, false)
  3138. return
  3139. }
  3140. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3141. if err != nil {
  3142. logs.Error(err)
  3143. appG.Response(http.StatusOK, e.ERROR, false)
  3144. return
  3145. }
  3146. now := createdate
  3147. // for _, oldFpd := range oldFpdDataList {
  3148. for _, newFpd := range newFpdDataList {
  3149. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3150. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3151. // go func() {
  3152. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3153. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3154. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3155. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3156. if err != nil {
  3157. logs.Error(err)
  3158. appG.Response(http.StatusOK, e.ERROR, false)
  3159. return
  3160. }
  3161. // }()
  3162. }
  3163. // break
  3164. // }
  3165. // }
  3166. // }
  3167. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3168. for _, newLpplandtl1 := range newLpplandtl1List {
  3169. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3170. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3171. // go func() {
  3172. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3173. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3174. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3175. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3176. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3177. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3178. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3179. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3180. if err != nil {
  3181. logs.Error(err)
  3182. appG.Response(http.StatusOK, e.ERROR, false)
  3183. return
  3184. }
  3185. // }()
  3186. // }
  3187. // break
  3188. // }
  3189. // }
  3190. }
  3191. // for _, oldFeedp := range oldFeedpList {
  3192. for _, newFeedp := range newFeedpList {
  3193. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3194. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3195. // go func() {
  3196. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3197. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3198. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3199. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3200. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3201. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3202. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3203. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3204. if err != nil {
  3205. logs.Error(err)
  3206. appG.Response(http.StatusOK, e.ERROR, false)
  3207. return
  3208. }
  3209. }
  3210. // ,,parammaps["ftid"])
  3211. // surplus, surplusId, id, pastureId string
  3212. // FtdetailSurplusFt(parammaps["ftid"].)
  3213. ftList1, err := tx.SQL(` SELECT
  3214. f.id,
  3215. f.surplus surplusId,
  3216. f.pastureid,
  3217. s.surplus
  3218. FROM
  3219. feedtemplet f
  3220. JOIN surplus s ON s.id = f.surplus
  3221. WHERE
  3222. f.id = ?`, parammaps["ftid"]).QueryString()
  3223. for _, ft := range ftList1 {
  3224. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3225. }
  3226. appG.Response(http.StatusOK, e.SUCCESS, true)
  3227. }
  3228. type lpplandtlInfo struct {
  3229. Id int64 `xorm:"id"`
  3230. Pastureid int64 `xorm:"pastureid"`
  3231. Lppid int64 `xorm:"lppid"`
  3232. Barid int64 `xorm:"barid"`
  3233. Barname string `xorm:"barname"`
  3234. Fpdid int64 `xorm:"fpdid"`
  3235. Fttype int64 `xorm:"fttype"`
  3236. Lweight float64 `xorm:"lweight"`
  3237. Sort int64 `xorm:"sort"`
  3238. Tmrid int64 `xorm:"tmrid"`
  3239. Tmrname string `xorm:"tmrname"`
  3240. Cowcount int64 `xorm:"cowcount"`
  3241. Ccountradio float64 `xorm:"ccountradio"`
  3242. Background string `xorm:"background"`
  3243. Lweighthis float64 `xorm:"lweighthis"`
  3244. Maxweight float64 `xorm:"maxweight"`
  3245. }
  3246. func UpdateFpdetailBar(c *gin.Context) {
  3247. appG := app.Gin{C: c}
  3248. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3249. fsion := gofasion.NewFasion(string(dataByte))
  3250. pastureid := fsion.Get("pastureid").ValueStr()
  3251. id := fsion.Get("id").ValueStr()
  3252. tx := restful.Engine.NewSession()
  3253. tx.Begin()
  3254. 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 `,
  3255. pastureid, id).Query().List()
  3256. if err != nil {
  3257. logs.Error(err)
  3258. }
  3259. for _, fpd := range fpdList {
  3260. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3261. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3262. pastureid, fpd["id"]).Query().List()
  3263. if err != nil {
  3264. tx.Rollback()
  3265. logs.Error(err)
  3266. appG.Response(http.StatusOK, e.ERROR, false)
  3267. return
  3268. }
  3269. var lweight float64
  3270. for _, lppland := range lpplandList {
  3271. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3272. lweight += lweight1
  3273. }
  3274. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3275. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3276. if fpdweight >= ptuse && lweight == ptuse {
  3277. continue
  3278. } else {
  3279. if lweight <= fpdweight {
  3280. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3281. if err != nil {
  3282. tx.Rollback()
  3283. logs.Error(err)
  3284. appG.Response(http.StatusOK, e.ERROR, false)
  3285. return
  3286. }
  3287. } else {
  3288. weight := fpdweight - lweight
  3289. for _, lppland := range lpplandList {
  3290. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3291. if weight >= lpplandlweight {
  3292. weight = weight - lpplandlweight
  3293. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3294. if err != nil {
  3295. tx.Rollback()
  3296. logs.Error(err)
  3297. appG.Response(http.StatusOK, e.ERROR, false)
  3298. return
  3299. }
  3300. } else {
  3301. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3302. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3303. // if err != nil {
  3304. // tx.Rollback()
  3305. // logs.Error(err)
  3306. // appG.Response(http.StatusOK, e.ERROR, false)
  3307. // return
  3308. // }
  3309. weight = 0
  3310. break
  3311. }
  3312. }
  3313. }
  3314. }
  3315. }
  3316. fsionData := fsion.Get("data").Array()
  3317. for _, list := range fsionData {
  3318. ftmap := make(map[string]interface{})
  3319. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3320. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3321. ftmap["times"] = list.Get("times").ValueInt64()
  3322. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3323. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3324. // fmt.Println(ftmap)
  3325. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3326. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3327. if count == 1 {
  3328. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3329. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3330. if err != nil {
  3331. tx.Rollback()
  3332. logs.Error(err)
  3333. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3334. return
  3335. }
  3336. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3337. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3338. if err != nil {
  3339. tx.Rollback()
  3340. logs.Error(err)
  3341. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3342. return
  3343. }
  3344. }
  3345. fpdDataList, err := tx.SQL(`
  3346. 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 ,
  3347. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3348. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3349. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3350. if err != nil {
  3351. tx.Rollback()
  3352. logs.Error(err)
  3353. }
  3354. for _, fpd := range fpdDataList {
  3355. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3356. fttype := -1
  3357. if fpd["fttype"].(string) == "1" {
  3358. fttype = 1
  3359. }
  3360. var fweight float64
  3361. var lweight float64
  3362. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3363. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3364. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3365. join tmr t on t.id = lpp.tmrid
  3366. where lppland.fpdid =?
  3367. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3368. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3369. if err != nil {
  3370. tx.Rollback()
  3371. logs.Error(err)
  3372. }
  3373. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3374. var w float64
  3375. var status int
  3376. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3377. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3378. if weight >= 0 {
  3379. continue
  3380. }
  3381. w = weight
  3382. status = 0
  3383. } else {
  3384. // continue
  3385. if weight <= 0 {
  3386. continue
  3387. }
  3388. w = weight
  3389. status = 1
  3390. }
  3391. // for _, lppland := range lpplandtl1List {
  3392. // lweight += lppland.Lweight
  3393. // }
  3394. for _, lppland := range lpplandtl1List {
  3395. lpplandInfo := new(lpplandtlInfo)
  3396. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3397. lweight = lpplandInfo.Lweight
  3398. if status == 1 {
  3399. // if w <= lppland.Lweight {
  3400. if lppland.Maxweight <= lweight {
  3401. continue
  3402. }
  3403. if w+lweight <= lppland.Maxweight {
  3404. lppland.Lweight += w
  3405. lweight += w
  3406. fweight += w
  3407. w = 0
  3408. } else {
  3409. w = w - (lppland.Maxweight - lweight)
  3410. n := (lppland.Maxweight - lweight)
  3411. lppland.Lweight = lppland.Lweight + n
  3412. lweight += n
  3413. fweight += n
  3414. }
  3415. } else {
  3416. if lppland.Lweight == 0 {
  3417. continue
  3418. }
  3419. if w+lppland.Lweight >= 0 {
  3420. lppland.Lweight = lppland.Lweight + w
  3421. lweight = lweight + w
  3422. fweight = fweight + w
  3423. w = 0
  3424. } else {
  3425. w = w + lppland.Lweight
  3426. lweight = lweight - lppland.Lweight
  3427. fweight = fweight - lppland.Lweight
  3428. lppland.Lweight = 0
  3429. }
  3430. }
  3431. if lppland.Lweight > 0 {
  3432. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3433. if err != nil {
  3434. tx.Rollback()
  3435. logs.Error(err)
  3436. return
  3437. }
  3438. } else {
  3439. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3440. if err != nil {
  3441. tx.Rollback()
  3442. logs.Error(err)
  3443. return
  3444. }
  3445. }
  3446. if w == 0 {
  3447. break
  3448. }
  3449. // break
  3450. }
  3451. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3452. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3453. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3454. if err != nil {
  3455. tx.Rollback()
  3456. logs.Error(err)
  3457. }
  3458. if w == 0 {
  3459. break
  3460. }
  3461. }
  3462. }
  3463. }
  3464. tx.Commit()
  3465. now := time.Now()
  3466. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3467. if err != nil {
  3468. logs.Error(err)
  3469. appG.Response(http.StatusOK, e.ERROR, false)
  3470. return
  3471. }
  3472. for _, newLpplandtl1 := range newLpplandtl1List {
  3473. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3474. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3475. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3476. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3477. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3478. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3479. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3480. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3481. if err != nil {
  3482. logs.Error(err)
  3483. appG.Response(http.StatusOK, e.ERROR, false)
  3484. return
  3485. }
  3486. }
  3487. appG.Response(http.StatusOK, e.SUCCESS, true)
  3488. }
  3489. func GetProcessAnalysis(c *gin.Context) {
  3490. appG := app.Gin{C: c}
  3491. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3492. fsion := gofasion.NewFasion(string(dataByte))
  3493. sqlnamestr := fsion.Get("name").ValueStr()
  3494. offset := fsion.Get("offset").ValueDefaultInt(0)
  3495. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3496. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3497. parammaps := fsion.Get("parammaps")
  3498. tx := restful.Engine.NewSession()
  3499. err := tx.Begin()
  3500. defer func() {
  3501. switch {
  3502. case err != nil:
  3503. logging.Error("tx.Begin 事务启动失败__error:", err)
  3504. if tx != nil {
  3505. tx.Rollback()
  3506. }
  3507. default:
  3508. if tx != nil {
  3509. err = tx.Commit()
  3510. }
  3511. }
  3512. if tx != nil {
  3513. tx.Close()
  3514. }
  3515. }()
  3516. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3517. s_params := make([]interface{}, 0)
  3518. paramslist := strings.Split(p, ",")
  3519. if len(paramslist) > 0 && p != "" {
  3520. for _, value := range paramslist {
  3521. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3522. if tempv, exists := c.Get("jwt_username"); exists {
  3523. s_params = append(s_params, tempv.(string))
  3524. } else {
  3525. s_params = append(s_params, "")
  3526. }
  3527. } else {
  3528. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3529. }
  3530. }
  3531. }
  3532. tmrtnameStr := ""
  3533. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3534. if len(tmrtnameStr) == 0 {
  3535. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3536. } else {
  3537. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3538. }
  3539. }
  3540. if len(tmrtnameStr) > 0 {
  3541. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3542. }
  3543. sql += " ORDER BY d.intime"
  3544. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3545. if err != nil {
  3546. logging.Error("GetDataByName err: ", err)
  3547. msg := geterrmsg(err.Error())
  3548. appG.Response(http.StatusOK, e.ERROR, msg)
  3549. } else {
  3550. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3551. }
  3552. }
  3553. func UpdateFeedtempletStatus(c *gin.Context) {
  3554. appG := app.Gin{C: c}
  3555. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3556. fsion := gofasion.NewFasion(string(dataByte))
  3557. parammaps := fsion.Get("parammaps")
  3558. tx := restful.Engine.NewSession()
  3559. tx.Begin()
  3560. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3561. if err != nil {
  3562. tx.Rollback()
  3563. logs.Error(err)
  3564. appG.Response(http.StatusOK, e.ERROR, err)
  3565. return
  3566. }
  3567. tx.Commit()
  3568. appG.Response(http.StatusOK, e.SUCCESS, true)
  3569. }
  3570. func AddFtdry(c *gin.Context) {
  3571. appG := app.Gin{C: c}
  3572. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3573. fsion := gofasion.NewFasion(string(dataByte))
  3574. sqlnamestr := fsion.Get("name").ValueStr()
  3575. s_params := make([]interface{}, 0)
  3576. tx := restful.Engine.NewSession()
  3577. err := tx.Begin()
  3578. defer func() {
  3579. switch {
  3580. case err != nil:
  3581. if tx != nil {
  3582. tx.Rollback()
  3583. }
  3584. default:
  3585. if tx != nil {
  3586. err = tx.Commit()
  3587. }
  3588. }
  3589. if tx != nil {
  3590. tx.Close()
  3591. }
  3592. }()
  3593. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3594. if sql != "" {
  3595. parammaps := fsion.Get("parammaps")
  3596. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3597. paramslist := strings.Split(p, ",")
  3598. if len(paramslist) > 0 && p != "" {
  3599. for _, value := range paramslist {
  3600. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3601. if tempv, exists := c.Get("jwt_username"); exists {
  3602. s_params = append(s_params, tempv.(string))
  3603. } else {
  3604. s_params = append(s_params, "")
  3605. }
  3606. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3607. ids, err := setting.SnowIds.NextId()
  3608. if err != nil {
  3609. ids = time.Now().UnixNano()
  3610. logging.Info("create SnowIds err", err)
  3611. }
  3612. s_params = append(s_params, ids)
  3613. } else {
  3614. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3615. }
  3616. }
  3617. }
  3618. var actweight float64
  3619. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3620. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3621. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3622. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3623. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3624. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3625. 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()
  3626. if err != nil {
  3627. logging.Error("AddFtdry err: ", err)
  3628. msg := geterrmsg(err.Error())
  3629. appG.Response(http.StatusOK, e.ERROR, msg)
  3630. }
  3631. if len(actweightList) > 0 {
  3632. for _, item := range actweightList {
  3633. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3634. if err != nil {
  3635. logging.Error("AddFtdry err: ", err)
  3636. msg := geterrmsg(err.Error())
  3637. appG.Response(http.StatusOK, e.ERROR, msg)
  3638. }
  3639. actweight = fl
  3640. }
  3641. } else {
  3642. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3643. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3644. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3645. if err != nil {
  3646. logging.Error("AddFtdry err: ", err)
  3647. msg := geterrmsg(err.Error())
  3648. appG.Response(http.StatusOK, e.ERROR, msg)
  3649. }
  3650. for _, item := range dryList {
  3651. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3652. if err != nil {
  3653. logging.Error("AddFtdry err: ", err)
  3654. msg := geterrmsg(err.Error())
  3655. appG.Response(http.StatusOK, e.ERROR, msg)
  3656. }
  3657. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3658. }
  3659. }
  3660. if sqlnamestr == "insertFtdry" {
  3661. s_params = append(s_params, actweight)
  3662. } else if sqlnamestr == "updateFtdry" {
  3663. sql = fmt.Sprintf(sql, actweight)
  3664. }
  3665. queryData, err := execDataBySqlT(sql, s_params, tx)
  3666. if err != nil {
  3667. logging.Error("AddFtdry err: ", err)
  3668. msg := geterrmsg(err.Error())
  3669. appG.Response(http.StatusOK, e.ERROR, msg)
  3670. } else {
  3671. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3672. }
  3673. } else {
  3674. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3675. }
  3676. }
  3677. func CheckDates(c *gin.Context) {
  3678. tx := restful.Engine.NewSession()
  3679. defer tx.Close()
  3680. appG := app.Gin{C: c}
  3681. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3682. tempval_ := make(map[string]interface{})
  3683. tempCommon := make(map[string]interface{})
  3684. tempval := make([]map[string]interface{}, 0)
  3685. err := json.Unmarshal(dataByte, &tempval_)
  3686. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3687. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3688. if err != nil {
  3689. } else {
  3690. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3691. tempCommon = v
  3692. }
  3693. if v, ok := tempval_["data"].([]interface{}); ok {
  3694. for _, Tvalue := range v {
  3695. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3696. tempval = append(tempval, v1)
  3697. }
  3698. }
  3699. }
  3700. if err == nil {
  3701. if tempv, exists := c.Get("jwt_username"); exists {
  3702. tempCommon["jwt_username"] = tempv.(string)
  3703. }
  3704. for _, paramvalue := range tempval {
  3705. if _, ok := paramvalue["resultname"]; !ok {
  3706. paramvalue["resultname"] = paramvalue["name"]
  3707. }
  3708. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3709. if err != nil {
  3710. logging.Error("ExecDataParam error:", err)
  3711. }
  3712. }
  3713. if err == nil {
  3714. vmsg := ""
  3715. for _, item := range tempval {
  3716. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3717. for _, childrenList := range list.([]interface{}) {
  3718. for k, children := range childrenList.(map[string]interface{}) {
  3719. if k != "children" {
  3720. continue
  3721. }
  3722. for _, v := range children.([]map[string]interface{}) {
  3723. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3724. if k1 == "list" {
  3725. for _, v2 := range v1.([]map[string]interface{}) {
  3726. if v2["vmsg"].(string) != "1" {
  3727. if len(vmsg) == 0 {
  3728. vmsg = v2["vmsg"].(string)
  3729. } else {
  3730. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3731. }
  3732. }
  3733. }
  3734. }
  3735. }
  3736. }
  3737. }
  3738. }
  3739. }
  3740. }
  3741. if len(vmsg) > 0 {
  3742. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3743. } else {
  3744. appG.Response(http.StatusOK, e.SUCCESS, true)
  3745. }
  3746. } else {
  3747. msg := geterrmsg(err.Error())
  3748. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3749. }
  3750. }
  3751. }
  3752. if err != nil {
  3753. msg := geterrmsg(err.Error())
  3754. appG.Response(http.StatusOK, e.ERROR, msg)
  3755. }
  3756. }
  3757. 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) {
  3758. sqlname := fasion["name"].(string)
  3759. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3760. if v, ok := fasion["type"]; ok {
  3761. sqltype = v.(string)
  3762. }
  3763. sql := ""
  3764. p := ""
  3765. s_params := make([]interface{}, 0)
  3766. if sqltype != "" {
  3767. sql, p = restful.GetSqlByName(sqlname, tx)
  3768. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3769. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3770. paramslist := strings.Split(p, ",")
  3771. if len(paramslist) > 0 && p != "" {
  3772. for _, value := range paramslist {
  3773. ss := ""
  3774. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3775. ids, err := setting.SnowIds.NextId()
  3776. if err != nil {
  3777. ids = time.Now().UnixNano()
  3778. logging.Info("create SnowIds err", err)
  3779. }
  3780. s_params = append(s_params, ids)
  3781. } else {
  3782. if ss == "" && CommonParamMap != nil {
  3783. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3784. ss = valuestring
  3785. tempstrb := strings.IndexAny(valuestring, "@")
  3786. tempstre := strings.IndexAny(valuestring, ".")
  3787. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3788. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3789. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3790. }
  3791. } else {
  3792. ss = ""
  3793. }
  3794. }
  3795. }
  3796. if ss == "" && ParentParamMap != nil {
  3797. ss = getParamValue_(v, value, ParentParamMap)
  3798. }
  3799. if ss == "" && sameParamMap != nil {
  3800. ss = getParamValue(v, value, sameParamMap)
  3801. }
  3802. if ss == "" && ParamMap != nil {
  3803. ss = getParamValue(v, value, ParamMap)
  3804. }
  3805. s_params = append(s_params, ss)
  3806. }
  3807. }
  3808. }
  3809. }
  3810. }
  3811. if sql == "" {
  3812. sqltype = ""
  3813. }
  3814. if sql != "" {
  3815. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3816. if err != nil {
  3817. return nil, err
  3818. }
  3819. // fmt.Println(tempValParam)
  3820. return tempValParam.(map[string]interface{}), nil
  3821. } else {
  3822. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3823. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3824. if err != nil {
  3825. return nil, err
  3826. }
  3827. return nil, err
  3828. }
  3829. }
  3830. return nil, nil
  3831. }
  3832. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3833. var err error
  3834. subarray, ok := fasion["children"]
  3835. if ok {
  3836. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3837. tempVal_arrary := make([]map[string]interface{}, 0)
  3838. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3839. tempVal_ := make(map[string]interface{})
  3840. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3841. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3842. } else {
  3843. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3844. }
  3845. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3846. if err != nil {
  3847. return err
  3848. }
  3849. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3850. }
  3851. v.(map[string]interface{})["children"] = tempVal_arrary
  3852. }
  3853. }
  3854. return nil
  3855. }
  3856. func FpdImportExcel(c *gin.Context) {
  3857. appG := app.Gin{C: c}
  3858. inputdata := ""
  3859. c.Request.ParseForm()
  3860. params := c.Request.Form
  3861. file, _, err := c.Request.FormFile("file")
  3862. if err != nil {
  3863. appG.Response(http.StatusOK, e.ERROR, err)
  3864. return
  3865. }
  3866. sqlnamestrs := params.Get("name")
  3867. sheetname := params.Get("sheetname")
  3868. pastureid := params.Get("pastureid")
  3869. // importParams := params.Get("importParams")
  3870. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3871. // 必输项参数 (字符串格式 "field1,field2,field3")
  3872. requiredParams := params.Get("requiredParams")
  3873. // 日期参数
  3874. dateParams := params.Get("dateParams")
  3875. // 数字参数
  3876. numParams := params.Get("numParams")
  3877. //将字符串分割开
  3878. dateParamslist := strings.Split(dateParams, ",")
  3879. requiredParamslist := strings.Split(requiredParams, ",")
  3880. numParamslist := strings.Split(numParams, ",")
  3881. queryData := make([]interface{}, 0)
  3882. sqlslist := strings.Split(sqlnamestrs, ",")
  3883. xlsx1, err := excelize.OpenReader(file)
  3884. if err != nil {
  3885. fmt.Println(err)
  3886. return
  3887. }
  3888. ok := 0
  3889. error := 0
  3890. isdone := true
  3891. tx := restful.Engine.NewSession()
  3892. defer tx.Close()
  3893. languageStatus := GetLanguageStatus()
  3894. if languageStatus == "0" {
  3895. 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
  3896. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3897. if err != nil {
  3898. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3899. return
  3900. }
  3901. rows := xlsx1.GetRows(sheetname)
  3902. // 限制10000条,多余的截取掉
  3903. if len(rows) > 10000 {
  3904. rows = rows[:10000]
  3905. }
  3906. dataList := make(map[string][]*upFpdetail, 0)
  3907. for i, row := range rows {
  3908. if i > 0 {
  3909. entry := make(map[string]interface{})
  3910. outentry := make(map[string]interface{})
  3911. for j, colCell := range rows[0] {
  3912. for k, colCell1 := range row {
  3913. if j == k {
  3914. outentry[colCell] = colCell1
  3915. entry[colCell] = colCell1
  3916. }
  3917. }
  3918. }
  3919. inputdata = ""
  3920. a := ""
  3921. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3922. //校验日期格式
  3923. for _, v := range dateParamslist {
  3924. if v == "" {
  3925. continue
  3926. }
  3927. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3928. dtime, err := TransfTime(d.(string))
  3929. if err != nil {
  3930. a = strings.Trim(v, " ")
  3931. break
  3932. }
  3933. outentry[strings.Trim(v, " ")] = dtime
  3934. }
  3935. }
  3936. if a != "" {
  3937. outentry["error_msg"] = a + " 格式错误"
  3938. error++
  3939. queryData = append(queryData, outentry)
  3940. continue
  3941. }
  3942. a = ""
  3943. //校验必填格式
  3944. for _, v := range requiredParamslist {
  3945. if v == "" {
  3946. continue
  3947. }
  3948. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3949. a = strings.Trim(v, " ")
  3950. break
  3951. }
  3952. }
  3953. if a != "" {
  3954. outentry["error_msg"] = a + " 未填或格式错误"
  3955. error++
  3956. queryData = append(queryData, outentry)
  3957. continue
  3958. }
  3959. a = ""
  3960. //校验数字格式
  3961. for _, v := range numParamslist {
  3962. if v == "" {
  3963. continue
  3964. }
  3965. d, ok := outentry[strings.Trim(v, " ")]
  3966. if !ok || d == "" {
  3967. outentry[strings.Trim(v, " ")] = 0
  3968. } else {
  3969. var fl float64
  3970. switch d.(type) {
  3971. case string:
  3972. fl, err = strconv.ParseFloat(d.(string), 64)
  3973. }
  3974. if err != nil || fl < 0 {
  3975. a = strings.Trim(v, " ")
  3976. break
  3977. }
  3978. }
  3979. }
  3980. if a != "" {
  3981. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3982. error++
  3983. queryData = append(queryData, outentry)
  3984. continue
  3985. }
  3986. errExist := false
  3987. for _, sqlnamestr := range sqlslist {
  3988. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3989. paramslist := strings.Split(paramslists, ",")
  3990. if len(paramslist) > 0 {
  3991. s_params := make([]interface{}, 0)
  3992. for _, value := range paramslist {
  3993. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3994. if tempv, exists := c.Get("jwt_username"); exists {
  3995. s_params = append(s_params, tempv.(string))
  3996. } else {
  3997. s_params = append(s_params, "")
  3998. }
  3999. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4000. s_params = append(s_params, pastureid)
  4001. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4002. ids, err := setting.SnowIds.NextId()
  4003. if err != nil {
  4004. ids = time.Now().UnixNano()
  4005. logging.Info("create SnowIds err", err)
  4006. }
  4007. s_params = append(s_params, ids)
  4008. } else {
  4009. if outentry[strings.Trim(value, " ")] == nil {
  4010. s_params = append(s_params, "")
  4011. } else {
  4012. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4013. }
  4014. }
  4015. }
  4016. outentry["input"] = inputdata
  4017. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4018. if err != nil {
  4019. errExist = true
  4020. // if tx != nil {
  4021. // tx.Rollback()
  4022. // }
  4023. // if tx != nil {
  4024. // tx.Close()
  4025. // }
  4026. msg := geterrmsg(err.Error())
  4027. outentry["error_msg"] = msg
  4028. error++
  4029. queryData = append(queryData, outentry)
  4030. isdone = true
  4031. break
  4032. } else {
  4033. if len(returnmsgmap1) > 0 {
  4034. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4035. // if tx != nil {
  4036. // tx.Rollback()
  4037. // }
  4038. // if tx != nil {
  4039. // tx.Close()
  4040. // }
  4041. msg := geterrmsg(va.(string))
  4042. outentry["error_msg"] = msg
  4043. error++
  4044. queryData = append(queryData, outentry)
  4045. isdone = true
  4046. break
  4047. }
  4048. }
  4049. isdone = false
  4050. }
  4051. }
  4052. }
  4053. if !errExist {
  4054. dataexcel := make(map[string]interface{}, 0)
  4055. if _, ok := outentry["栏舍名称"]; ok {
  4056. dataexcel["barname"] = outentry["栏舍名称"]
  4057. }
  4058. if _, ok := outentry["实际牛头数"]; ok {
  4059. dataexcel["ccount"] = outentry["实际牛头数"]
  4060. }
  4061. if _, ok := outentry["系数(%)"]; ok {
  4062. dataexcel["ratio"] = outentry["系数(%)"]
  4063. }
  4064. if _, ok := outentry["配方模板"]; ok {
  4065. dataexcel["ftname"] = outentry["配方模板"]
  4066. }
  4067. if _, ok := outentry["补料配方"]; ok {
  4068. dataexcel["ptsfname"] = outentry["补料配方"]
  4069. }
  4070. if _, ok := outentry["第一班比例(%)"]; ok {
  4071. dataexcel["1"] = outentry["第一班比例(%)"]
  4072. }
  4073. if _, ok := outentry["第二班比例(%)"]; ok {
  4074. dataexcel["2"] = outentry["第二班比例(%)"]
  4075. }
  4076. if _, ok := outentry["第三班比例(%)"]; ok {
  4077. dataexcel["3"] = outentry["第三班比例(%)"]
  4078. }
  4079. if _, ok := outentry["第四班比例(%)"]; ok {
  4080. dataexcel["4"] = outentry["第四班比例(%)"]
  4081. }
  4082. if _, ok := outentry["第五班比例(%)"]; ok {
  4083. dataexcel["5"] = outentry["第五班比例(%)"]
  4084. }
  4085. if _, ok := outentry["第六班比例(%)"]; ok {
  4086. dataexcel["6"] = outentry["第六班比例(%)"]
  4087. }
  4088. dataWeight := new(models.FpdetailEdit)
  4089. // dataWeightMap := make(map[string]interface{}, 0)
  4090. if _, ok := outentry["第一班重量"]; ok {
  4091. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4092. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4093. }
  4094. if _, ok := outentry["第二班重量"]; ok {
  4095. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4096. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4097. }
  4098. if _, ok := outentry["第三班重量"]; ok {
  4099. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4100. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4101. }
  4102. if _, ok := outentry["第四班重量"]; ok {
  4103. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4104. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4105. }
  4106. if _, ok := outentry["第五班重量"]; ok {
  4107. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4108. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4109. }
  4110. if _, ok := outentry["第六班重量"]; ok {
  4111. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4112. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4113. }
  4114. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4115. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4116. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4117. // fmt.Println(err)
  4118. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4119. if weight > 0 {
  4120. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4121. if err != nil {
  4122. logs.Error(err)
  4123. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4124. return
  4125. }
  4126. if !existbar {
  4127. continue
  4128. }
  4129. _, 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()
  4130. if err != nil {
  4131. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4132. return
  4133. }
  4134. _, 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()
  4135. if err != nil {
  4136. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4137. return
  4138. }
  4139. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4140. if err != nil {
  4141. logs.Error(err)
  4142. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4143. return
  4144. }
  4145. if !existft {
  4146. continue
  4147. }
  4148. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4149. if err != nil {
  4150. logs.Error(err)
  4151. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4152. return
  4153. }
  4154. if !ftexist {
  4155. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4156. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4157. if err != nil {
  4158. logs.Error(err)
  4159. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4160. return
  4161. }
  4162. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4163. if err != nil {
  4164. logs.Error(err)
  4165. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4166. return
  4167. }
  4168. }
  4169. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4170. if err != nil {
  4171. logs.Error(err)
  4172. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4173. return
  4174. }
  4175. if !exist {
  4176. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4177. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4178. if err != nil {
  4179. logs.Error(err)
  4180. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4181. return
  4182. }
  4183. }
  4184. var feedpargs []interface{}
  4185. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4186. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4187. if _, ok := dataexcel["ftname"]; ok {
  4188. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4189. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4190. // upFeedpSql += `,ftweight = ? `
  4191. // feedpargs = append(feedpargs, weight)
  4192. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4193. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4194. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4195. } else {
  4196. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4197. }
  4198. if _, ok := dataexcel["ptsfname"]; ok {
  4199. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4200. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4201. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4202. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4203. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4204. } else {
  4205. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4206. }
  4207. upFeedpSql += " where barname = ? and pastureid = ? "
  4208. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4209. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4210. if err != nil {
  4211. logs.Error(err)
  4212. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4213. return
  4214. }
  4215. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4216. if err != nil {
  4217. logs.Error(err)
  4218. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4219. return
  4220. }
  4221. if !exist1 {
  4222. _, 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) `,
  4223. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4224. if err != nil {
  4225. logs.Error(err)
  4226. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4227. return
  4228. }
  4229. }
  4230. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4231. if err != nil {
  4232. logs.Error(err)
  4233. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4234. return
  4235. }
  4236. if !exist2 {
  4237. _, 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) `,
  4238. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4239. if err != nil {
  4240. logs.Error(err)
  4241. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4242. return
  4243. }
  4244. }
  4245. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4246. if err != nil {
  4247. logs.Error(err)
  4248. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4249. return
  4250. }
  4251. if !exist3 {
  4252. _, 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) `,
  4253. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4254. if err != nil {
  4255. logs.Error(err)
  4256. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4257. return
  4258. }
  4259. }
  4260. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4261. if err != nil {
  4262. logs.Error(err)
  4263. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4264. return
  4265. }
  4266. if !exist4 {
  4267. _, 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) `,
  4268. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4269. if err != nil {
  4270. logs.Error(err)
  4271. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4272. return
  4273. }
  4274. }
  4275. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4276. if err != nil {
  4277. logs.Error(err)
  4278. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4279. return
  4280. }
  4281. if !exist5 {
  4282. _, 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) `,
  4283. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4284. if err != nil {
  4285. logs.Error(err)
  4286. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4287. return
  4288. }
  4289. }
  4290. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4291. if err != nil {
  4292. logs.Error(err)
  4293. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4294. return
  4295. }
  4296. if !exist6 {
  4297. _, 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) `,
  4298. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4299. if err != nil {
  4300. logs.Error(err)
  4301. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4302. return
  4303. }
  4304. }
  4305. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4306. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4307. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4308. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4309. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4310. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4311. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4312. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4313. and pastureid = ? and times = ?`
  4314. var fpdargs1 []interface{}
  4315. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4316. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4317. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4318. if err != nil {
  4319. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4320. return
  4321. }
  4322. var fpdargs2 []interface{}
  4323. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4324. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4325. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4326. if err != nil {
  4327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4328. return
  4329. }
  4330. var fpdargs3 []interface{}
  4331. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4332. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4333. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4334. if err != nil {
  4335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4336. return
  4337. }
  4338. var fpdargs4 []interface{}
  4339. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4340. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4341. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4342. if err != nil {
  4343. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4344. return
  4345. }
  4346. var fpdargs5 []interface{}
  4347. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4348. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4349. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4350. if err != nil {
  4351. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4352. return
  4353. }
  4354. var fpdargs6 []interface{}
  4355. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4356. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4357. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4358. if err != nil {
  4359. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4360. return
  4361. }
  4362. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4363. 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()
  4364. if err != nil {
  4365. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4366. return
  4367. }
  4368. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4369. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4370. upFpdetailList := make([]*upFpdetail, 0)
  4371. for _, newfpd := range newList {
  4372. for _, oldfpd := range oldFpdList {
  4373. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4374. var oldweight, newweight float64
  4375. if oldfpd["weight"] != nil {
  4376. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4377. }
  4378. if newfpd["weight"] != nil {
  4379. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4380. }
  4381. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4382. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4383. Old: oldweight,
  4384. New: newweight,
  4385. Times: newfpd["times"].(int64),
  4386. Ptid: newfpd["ptid"].(int64),
  4387. Fweight: fweight,
  4388. Id: oldfpd["id"].(int64),
  4389. })
  4390. break
  4391. }
  4392. }
  4393. }
  4394. // fmt.Println(dataexcel["barname"])
  4395. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4396. } else {
  4397. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4398. if err != nil {
  4399. logs.Error(err)
  4400. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4401. return
  4402. }
  4403. if !existbar {
  4404. continue
  4405. }
  4406. _, 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()
  4407. if err != nil {
  4408. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4409. return
  4410. }
  4411. _, 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()
  4412. if err != nil {
  4413. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4414. return
  4415. }
  4416. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4417. if err != nil {
  4418. logs.Error(err)
  4419. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4420. return
  4421. }
  4422. if !existft {
  4423. continue
  4424. }
  4425. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4426. if err != nil {
  4427. logs.Error(err)
  4428. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4429. return
  4430. }
  4431. if !ftexist {
  4432. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4433. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4434. if err != nil {
  4435. logs.Error(err)
  4436. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4437. return
  4438. }
  4439. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4440. if err != nil {
  4441. logs.Error(err)
  4442. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4443. return
  4444. }
  4445. }
  4446. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4447. if err != nil {
  4448. logs.Error(err)
  4449. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4450. return
  4451. }
  4452. if !exist {
  4453. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4454. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4455. if err != nil {
  4456. logs.Error(err)
  4457. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4458. return
  4459. }
  4460. }
  4461. var feedpargs []interface{}
  4462. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4463. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4464. if _, ok := dataexcel["ftname"]; ok {
  4465. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4466. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4467. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4468. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4469. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4470. } else {
  4471. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4472. }
  4473. if _, ok := dataexcel["ptsfname"]; ok {
  4474. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4475. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4476. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4477. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4478. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4479. } else {
  4480. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4481. }
  4482. upFeedpSql += " where barname = ? and pastureid = ? "
  4483. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4484. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4485. if err != nil {
  4486. logs.Error(err)
  4487. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4488. return
  4489. }
  4490. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4491. if err != nil {
  4492. logs.Error(err)
  4493. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4494. return
  4495. }
  4496. if !exist1 {
  4497. _, 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) `,
  4498. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4499. if err != nil {
  4500. logs.Error(err)
  4501. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4502. return
  4503. }
  4504. }
  4505. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4506. if err != nil {
  4507. logs.Error(err)
  4508. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4509. return
  4510. }
  4511. if !exist2 {
  4512. _, 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) `,
  4513. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4514. if err != nil {
  4515. logs.Error(err)
  4516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4517. return
  4518. }
  4519. }
  4520. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4521. if err != nil {
  4522. logs.Error(err)
  4523. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4524. return
  4525. }
  4526. if !exist3 {
  4527. _, 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) `,
  4528. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4529. if err != nil {
  4530. logs.Error(err)
  4531. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4532. return
  4533. }
  4534. }
  4535. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4536. if err != nil {
  4537. logs.Error(err)
  4538. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4539. return
  4540. }
  4541. if !exist4 {
  4542. _, 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) `,
  4543. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4544. if err != nil {
  4545. logs.Error(err)
  4546. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4547. return
  4548. }
  4549. }
  4550. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4551. if err != nil {
  4552. logs.Error(err)
  4553. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4554. return
  4555. }
  4556. if !exist5 {
  4557. _, 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) `,
  4558. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4559. if err != nil {
  4560. logs.Error(err)
  4561. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4562. return
  4563. }
  4564. }
  4565. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4566. if err != nil {
  4567. logs.Error(err)
  4568. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4569. return
  4570. }
  4571. if !exist6 {
  4572. _, 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) `,
  4573. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4574. if err != nil {
  4575. logs.Error(err)
  4576. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4577. return
  4578. }
  4579. }
  4580. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4581. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4582. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4583. and pastureid = ? and times = ?`
  4584. var fpdargs1 []interface{}
  4585. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4586. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4587. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4588. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4589. if err != nil {
  4590. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4591. return
  4592. }
  4593. var fpdargs2 []interface{}
  4594. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4595. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4596. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4597. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4598. if err != nil {
  4599. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4600. return
  4601. }
  4602. var fpdargs3 []interface{}
  4603. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4604. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4605. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4606. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4607. if err != nil {
  4608. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4609. return
  4610. }
  4611. var fpdargs4 []interface{}
  4612. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4613. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4614. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4615. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4616. if err != nil {
  4617. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4618. return
  4619. }
  4620. var fpdargs5 []interface{}
  4621. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4622. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4623. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4624. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4625. if err != nil {
  4626. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4627. return
  4628. }
  4629. var fpdargs6 []interface{}
  4630. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4631. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4632. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4633. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4634. if err != nil {
  4635. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4636. return
  4637. }
  4638. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4639. 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()
  4640. if err != nil {
  4641. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4642. return
  4643. }
  4644. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4645. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4646. upFpdetailList := make([]*upFpdetail, 0)
  4647. for _, newfpd := range newList {
  4648. for _, oldfpd := range oldFpdList {
  4649. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4650. var oldweight, newweight float64
  4651. if oldfpd["weight"] != nil {
  4652. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4653. }
  4654. if newfpd["weight"] != nil {
  4655. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4656. }
  4657. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4658. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4659. Old: oldweight,
  4660. New: newweight,
  4661. Times: newfpd["times"].(int64),
  4662. Ptid: newfpd["ptid"].(int64),
  4663. Fweight: fweight,
  4664. Id: oldfpd["id"].(int64),
  4665. })
  4666. break
  4667. }
  4668. }
  4669. }
  4670. // fmt.Println(dataexcel["barname"])
  4671. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4672. }
  4673. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4674. }
  4675. }
  4676. if !isdone {
  4677. ok++
  4678. isdone = true
  4679. }
  4680. }
  4681. for barname, v := range dataList {
  4682. for _, v1 := range v {
  4683. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4684. and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4685. if count == 1 {
  4686. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4687. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4688. if err != nil {
  4689. logs.Error(err)
  4690. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4691. return
  4692. }
  4693. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4694. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4695. if err != nil {
  4696. logs.Error(err)
  4697. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4698. return
  4699. }
  4700. }
  4701. }
  4702. updateFpdetailByBar(pastureid, barname, v)
  4703. }
  4704. } else {
  4705. 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
  4706. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4707. if err != nil {
  4708. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4709. return
  4710. }
  4711. rows := xlsx1.GetRows(sheetname)
  4712. // 限制10000条,多余的截取掉
  4713. if len(rows) > 10000 {
  4714. rows = rows[:10000]
  4715. }
  4716. dataList := make(map[string][]*upFpdetail, 0)
  4717. for i, row := range rows {
  4718. if i > 0 {
  4719. entry := make(map[string]interface{})
  4720. outentry := make(map[string]interface{})
  4721. for j, colCell := range rows[0] {
  4722. for k, colCell1 := range row {
  4723. if j == k {
  4724. outentry[colCell] = colCell1
  4725. entry[colCell] = colCell1
  4726. }
  4727. }
  4728. }
  4729. inputdata = ""
  4730. a := ""
  4731. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4732. //校验日期格式
  4733. for _, v := range dateParamslist {
  4734. if v == "" {
  4735. continue
  4736. }
  4737. if d, ok := outentry[v]; ok {
  4738. dtime, err := TransfTime(d.(string))
  4739. if err != nil {
  4740. a = v
  4741. break
  4742. }
  4743. outentry[v] = dtime
  4744. }
  4745. }
  4746. if a != "" {
  4747. outentry["error_msg"] = a + " format error"
  4748. error++
  4749. queryData = append(queryData, outentry)
  4750. continue
  4751. }
  4752. a = ""
  4753. //校验必填格式
  4754. for _, v := range requiredParamslist {
  4755. if v == "" {
  4756. continue
  4757. }
  4758. if d, ok := outentry[v]; !ok || d == "" {
  4759. a = v
  4760. break
  4761. }
  4762. }
  4763. if a != "" {
  4764. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4765. error++
  4766. queryData = append(queryData, outentry)
  4767. continue
  4768. }
  4769. a = ""
  4770. //校验数字格式
  4771. for _, v := range numParamslist {
  4772. if v == "" {
  4773. continue
  4774. }
  4775. d, ok := outentry[v]
  4776. if !ok || d == "" {
  4777. outentry[v] = 0
  4778. } else {
  4779. var fl float64
  4780. switch d.(type) {
  4781. case string:
  4782. fl, err = strconv.ParseFloat(d.(string), 64)
  4783. }
  4784. if err != nil || fl < 0 {
  4785. a = v
  4786. break
  4787. }
  4788. }
  4789. }
  4790. if a != "" {
  4791. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4792. error++
  4793. queryData = append(queryData, outentry)
  4794. continue
  4795. }
  4796. errExist := false
  4797. for _, sqlnamestr := range sqlslist {
  4798. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4799. paramslist := strings.Split(paramslists, ",")
  4800. if len(paramslist) > 0 {
  4801. s_params := make([]interface{}, 0)
  4802. for _, value := range paramslist {
  4803. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4804. if tempv, exists := c.Get("jwt_username"); exists {
  4805. s_params = append(s_params, tempv.(string))
  4806. } else {
  4807. s_params = append(s_params, "")
  4808. }
  4809. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4810. s_params = append(s_params, pastureid)
  4811. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4812. ids, err := setting.SnowIds.NextId()
  4813. if err != nil {
  4814. ids = time.Now().UnixNano()
  4815. logging.Info("create SnowIds err", err)
  4816. }
  4817. s_params = append(s_params, ids)
  4818. } else {
  4819. if outentry[strings.Trim(value, " ")] == nil {
  4820. s_params = append(s_params, "")
  4821. } else {
  4822. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4823. }
  4824. }
  4825. }
  4826. outentry["input"] = inputdata
  4827. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4828. if err != nil {
  4829. errExist = true
  4830. // if tx != nil {
  4831. // tx.Rollback()
  4832. // }
  4833. // if tx != nil {
  4834. // tx.Close()
  4835. // }
  4836. msg := geterrmsg(err.Error())
  4837. outentry["error_msg"] = msg
  4838. error++
  4839. queryData = append(queryData, outentry)
  4840. isdone = true
  4841. break
  4842. } else {
  4843. if len(returnmsgmap1) > 0 {
  4844. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4845. // if tx != nil {
  4846. // tx.Rollback()
  4847. // }
  4848. // if tx != nil {
  4849. // tx.Close()
  4850. // }
  4851. msg := geterrmsg(va.(string))
  4852. outentry["error_msg"] = msg
  4853. error++
  4854. queryData = append(queryData, outentry)
  4855. isdone = true
  4856. break
  4857. }
  4858. }
  4859. isdone = false
  4860. }
  4861. }
  4862. }
  4863. if !errExist {
  4864. dataexcel := make(map[string]interface{}, 0)
  4865. if _, ok := outentry["Pen Name"]; ok {
  4866. dataexcel["barname"] = outentry["Pen Name"]
  4867. }
  4868. if _, ok := outentry["Actual Cattle Number"]; ok {
  4869. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4870. }
  4871. if _, ok := outentry["Coefficient(%)"]; ok {
  4872. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4873. }
  4874. if _, ok := outentry["Formula Template"]; ok {
  4875. dataexcel["ftname"] = outentry["Formula Template"]
  4876. }
  4877. if _, ok := outentry["Supplement Formula"]; ok {
  4878. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4879. }
  4880. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4881. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4882. }
  4883. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4884. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4885. }
  4886. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4887. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4888. }
  4889. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4890. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4891. }
  4892. if _, ok := outentry["Fifth shift Ratio(%)"]; ok {
  4893. dataexcel["5"] = outentry["Fifth shift Ratio(%)"]
  4894. }
  4895. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4896. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4897. }
  4898. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4899. if err != nil {
  4900. logs.Error(err)
  4901. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4902. return
  4903. }
  4904. if !existbar {
  4905. continue
  4906. }
  4907. _, 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()
  4908. if err != nil {
  4909. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4910. return
  4911. }
  4912. _, 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()
  4913. if err != nil {
  4914. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4915. return
  4916. }
  4917. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4918. if err != nil {
  4919. logs.Error(err)
  4920. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4921. return
  4922. }
  4923. if !existft {
  4924. continue
  4925. }
  4926. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4927. if err != nil {
  4928. logs.Error(err)
  4929. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4930. return
  4931. }
  4932. if !ftexist {
  4933. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4934. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4935. if err != nil {
  4936. logs.Error(err)
  4937. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4938. return
  4939. }
  4940. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4941. if err != nil {
  4942. logs.Error(err)
  4943. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4944. return
  4945. }
  4946. }
  4947. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4948. if err != nil {
  4949. logs.Error(err)
  4950. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4951. return
  4952. }
  4953. if !exist {
  4954. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4955. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4956. if err != nil {
  4957. logs.Error(err)
  4958. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4959. return
  4960. }
  4961. }
  4962. var feedpargs []interface{}
  4963. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4964. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4965. if _, ok := dataexcel["ftname"]; ok {
  4966. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4967. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4968. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4969. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4970. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4971. } else {
  4972. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4973. }
  4974. if _, ok := dataexcel["ptsfname"]; ok {
  4975. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4976. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4977. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4978. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4979. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4980. } else {
  4981. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4982. }
  4983. upFeedpSql += " where barname = ? and pastureid = ? "
  4984. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4985. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4986. if err != nil {
  4987. logs.Error(err)
  4988. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4989. return
  4990. }
  4991. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4992. if err != nil {
  4993. logs.Error(err)
  4994. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4995. return
  4996. }
  4997. if !exist1 {
  4998. _, 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) `,
  4999. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5000. if err != nil {
  5001. logs.Error(err)
  5002. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5003. return
  5004. }
  5005. }
  5006. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5007. if err != nil {
  5008. logs.Error(err)
  5009. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5010. return
  5011. }
  5012. if !exist2 {
  5013. _, 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) `,
  5014. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5015. if err != nil {
  5016. logs.Error(err)
  5017. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5018. return
  5019. }
  5020. }
  5021. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5022. if err != nil {
  5023. logs.Error(err)
  5024. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5025. return
  5026. }
  5027. if !exist3 {
  5028. _, 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) `,
  5029. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5030. if err != nil {
  5031. logs.Error(err)
  5032. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5033. return
  5034. }
  5035. }
  5036. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5037. if err != nil {
  5038. logs.Error(err)
  5039. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5040. return
  5041. }
  5042. if !exist4 {
  5043. _, 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) `,
  5044. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5045. if err != nil {
  5046. logs.Error(err)
  5047. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5048. return
  5049. }
  5050. }
  5051. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5052. if err != nil {
  5053. logs.Error(err)
  5054. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5055. return
  5056. }
  5057. if !exist5 {
  5058. _, 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) `,
  5059. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5060. if err != nil {
  5061. logs.Error(err)
  5062. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5063. return
  5064. }
  5065. }
  5066. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5067. if err != nil {
  5068. logs.Error(err)
  5069. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5070. return
  5071. }
  5072. if !exist6 {
  5073. _, 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) `,
  5074. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5075. if err != nil {
  5076. logs.Error(err)
  5077. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5078. return
  5079. }
  5080. }
  5081. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5082. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5083. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5084. and pastureid = ? and times = ?`
  5085. var fpdargs1 []interface{}
  5086. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5087. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5088. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5089. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5090. if err != nil {
  5091. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5092. return
  5093. }
  5094. var fpdargs2 []interface{}
  5095. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5096. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5097. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5098. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5099. if err != nil {
  5100. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5101. return
  5102. }
  5103. var fpdargs3 []interface{}
  5104. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5105. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5106. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5107. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5108. if err != nil {
  5109. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5110. return
  5111. }
  5112. var fpdargs4 []interface{}
  5113. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5114. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5115. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5116. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5117. if err != nil {
  5118. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5119. return
  5120. }
  5121. var fpdargs5 []interface{}
  5122. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5123. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5124. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5125. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5126. if err != nil {
  5127. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5128. return
  5129. }
  5130. var fpdargs6 []interface{}
  5131. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5132. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5133. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5134. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5135. if err != nil {
  5136. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5137. return
  5138. }
  5139. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5140. 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()
  5141. if err != nil {
  5142. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5143. return
  5144. }
  5145. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5146. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5147. upFpdetailList := make([]*upFpdetail, 0)
  5148. for _, newfpd := range newList {
  5149. for _, oldfpd := range oldFpdList {
  5150. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5151. var oldweight, newweight float64
  5152. if oldfpd["weight"] != nil {
  5153. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5154. }
  5155. if newfpd["weight"] != nil {
  5156. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5157. }
  5158. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5159. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5160. Old: oldweight,
  5161. New: newweight,
  5162. Times: newfpd["times"].(int64),
  5163. Ptid: newfpd["ptid"].(int64),
  5164. Fweight: fweight,
  5165. Id: oldfpd["id"].(int64),
  5166. })
  5167. break
  5168. }
  5169. }
  5170. }
  5171. // fmt.Println(dataexcel["barname"])
  5172. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5173. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5174. }
  5175. }
  5176. if !isdone {
  5177. ok++
  5178. isdone = true
  5179. }
  5180. }
  5181. for barname, v := range dataList {
  5182. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5183. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5184. if err != nil {
  5185. logs.Error(err)
  5186. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5187. return
  5188. }
  5189. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5190. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5191. if err != nil {
  5192. logs.Error(err)
  5193. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5194. return
  5195. }
  5196. updateFpdetailByBar(pastureid, barname, v)
  5197. }
  5198. }
  5199. data := make(map[string]interface{})
  5200. data["result"] = queryData
  5201. data["success"] = ok
  5202. data["err_count"] = error
  5203. appG.Response(http.StatusOK, e.SUCCESS, data)
  5204. }
  5205. type upFpdetail struct {
  5206. Old float64
  5207. New float64
  5208. Times int64
  5209. Ptid int64
  5210. Fweight float64
  5211. Id int64
  5212. // Ptsid string
  5213. }
  5214. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5215. tx := restful.Engine.NewSession()
  5216. defer tx.Close()
  5217. tx.Begin()
  5218. 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 `,
  5219. pastureid, barname).Query().List()
  5220. if err != nil {
  5221. logs.Error(err)
  5222. }
  5223. for _, fpd := range fpdList {
  5224. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5225. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5226. pastureid, fpd["id"], fpd["times"]).Query().List()
  5227. if err != nil {
  5228. tx.Rollback()
  5229. logs.Error(err)
  5230. return err
  5231. }
  5232. var lweight float64
  5233. for _, lppland := range lpplandList {
  5234. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5235. lweight += lweight1
  5236. }
  5237. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5238. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5239. if fpdweight >= ptuse && lweight == ptuse {
  5240. continue
  5241. } else {
  5242. if lweight <= fpdweight {
  5243. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5244. if err != nil {
  5245. tx.Rollback()
  5246. logs.Error(err)
  5247. return err
  5248. }
  5249. } else {
  5250. weight := lweight - fpdweight
  5251. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5252. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5253. if err != nil {
  5254. tx.Rollback()
  5255. logs.Error(err)
  5256. return err
  5257. }
  5258. for _, lppland := range lpplandList {
  5259. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5260. if weight >= lpplandlweight {
  5261. weight = weight - lpplandlweight
  5262. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5263. if err != nil {
  5264. tx.Rollback()
  5265. logs.Error(err)
  5266. return err
  5267. }
  5268. } else {
  5269. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5270. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5271. if err != nil {
  5272. tx.Rollback()
  5273. logs.Error(err)
  5274. return err
  5275. }
  5276. weight = 0
  5277. break
  5278. }
  5279. }
  5280. }
  5281. }
  5282. }
  5283. for _, list := range dataList {
  5284. ftmap := make(map[string]interface{})
  5285. ftmap["old"] = list.Old
  5286. ftmap["new"] = list.New
  5287. ftmap["times"] = list.Times
  5288. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5289. ftmap["ptsid"] = ""
  5290. // fmt.Println(ftmap)
  5291. // 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 ,
  5292. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5293. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5294. // UNION
  5295. fpdDataList, err := tx.SQL(`
  5296. 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 ,
  5297. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5298. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5299. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5300. if err != nil {
  5301. tx.Rollback()
  5302. logs.Error(err)
  5303. }
  5304. for _, fpd := range fpdDataList {
  5305. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5306. // fttype := -1
  5307. // if fpd["fttype"].(string) == "1" {
  5308. fttype := 1
  5309. // }
  5310. var fweight float64
  5311. var lweight float64
  5312. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5313. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  5314. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5315. join tmr t on t.id = lpp.tmrid
  5316. where lppland.fpdid =?
  5317. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5318. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5319. if err != nil {
  5320. tx.Rollback()
  5321. logs.Error(err)
  5322. }
  5323. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5324. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5325. // 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
  5326. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5327. var w float64
  5328. var status int
  5329. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5330. if weight >= 0 {
  5331. continue
  5332. }
  5333. w = weight
  5334. status = 0
  5335. } else {
  5336. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5337. // continue
  5338. // }
  5339. w = weight
  5340. status = 1
  5341. }
  5342. // for _, lppland := range lpplandtl1List {
  5343. // lweight += lppland.Lweight
  5344. // }
  5345. for _, lppland := range lpplandtl1List {
  5346. lpplandInfo := new(lpplandtlInfo)
  5347. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5348. lweight = lpplandInfo.Lweight
  5349. if status == 1 {
  5350. // if w <= lppland.Lweight {
  5351. if lppland.Maxweight <= lweight {
  5352. continue
  5353. }
  5354. if w+lweight <= lppland.Maxweight {
  5355. lppland.Lweight += w
  5356. lweight += w
  5357. fweight += w
  5358. w = 0
  5359. } else {
  5360. w = w - (lppland.Maxweight - lweight)
  5361. n := (lppland.Maxweight - lweight)
  5362. lppland.Lweight = lppland.Lweight + n
  5363. lweight += n
  5364. fweight += n
  5365. }
  5366. } else {
  5367. if lppland.Lweight == 0 {
  5368. continue
  5369. }
  5370. if w+lppland.Lweight >= 0 {
  5371. lppland.Lweight = lppland.Lweight + w
  5372. lweight = lweight + w
  5373. fweight = fweight + w
  5374. w = 0
  5375. } else {
  5376. w = w + lppland.Lweight
  5377. lweight = lweight - lppland.Lweight
  5378. fweight = fweight - lppland.Lweight
  5379. lppland.Lweight = 0
  5380. }
  5381. }
  5382. if lppland.Lweight > 0 {
  5383. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5384. if err != nil {
  5385. tx.Rollback()
  5386. logs.Error(err)
  5387. return err
  5388. }
  5389. } else {
  5390. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5391. if err != nil {
  5392. tx.Rollback()
  5393. logs.Error(err)
  5394. return err
  5395. }
  5396. }
  5397. if w == 0 {
  5398. break
  5399. }
  5400. }
  5401. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5402. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5403. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5404. if err != nil {
  5405. tx.Rollback()
  5406. logs.Error(err)
  5407. }
  5408. if w == 0 {
  5409. break
  5410. }
  5411. }
  5412. }
  5413. }
  5414. err = tx.Commit()
  5415. if err != nil {
  5416. logs.Error(err)
  5417. tx.Rollback()
  5418. return err
  5419. }
  5420. now := time.Now()
  5421. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5422. if err != nil {
  5423. logs.Error(err)
  5424. return nil
  5425. }
  5426. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5427. if err != nil {
  5428. logs.Error(err)
  5429. return nil
  5430. }
  5431. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5432. if err != nil {
  5433. logs.Error(err)
  5434. return nil
  5435. }
  5436. for _, newLpplandtl1 := range newLpplandtl1List {
  5437. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5438. background,cowcount,ccountradio,lweighthis,createdate)
  5439. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5440. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5441. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5442. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5443. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5444. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5445. if err != nil {
  5446. logs.Error(err)
  5447. // appG.Response(http.StatusOK, e.ERROR, false)
  5448. return err
  5449. }
  5450. }
  5451. for _, newFpd := range newFpdDataList {
  5452. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5453. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5454. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5455. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5456. if err != nil {
  5457. logs.Error(err)
  5458. // appG.Response(http.StatusOK, e.ERROR, false)
  5459. return err
  5460. }
  5461. }
  5462. for _, newFeedp := range newFeedpList {
  5463. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5464. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5465. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5466. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5467. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5468. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5469. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5470. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5471. if err != nil {
  5472. logs.Error(err)
  5473. // appG.Response(http.StatusOK, e.ERROR, false)
  5474. return err
  5475. }
  5476. }
  5477. return nil
  5478. }
  5479. func DeleteFTdetail(c *gin.Context) {
  5480. appG := app.Gin{C: c}
  5481. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5482. fsion := gofasion.NewFasion(string(dataByte))
  5483. parammaps := fsion.Get("parammaps")
  5484. pastureid := parammaps.Get("pastureid").ValueStr()
  5485. ftid := parammaps.Get("ftid").ValueStr()
  5486. tx := restful.Engine.NewSession()
  5487. defer tx.Close()
  5488. tx.Begin()
  5489. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5490. if err != nil {
  5491. tx.Rollback()
  5492. logs.Error(err)
  5493. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5494. return
  5495. }
  5496. if parammaps.Get("type").ValueStr() == "1" {
  5497. _, err := tx.SQL(`UPDATE feedp fp
  5498. set
  5499. fp.ftweight= IFNULL(IF(
  5500. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5501. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5502. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5503. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5504. ),0),fp.feedweight = IFNULL(IF(
  5505. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5506. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5507. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5508. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5509. ),0) +ifnull(fp.supplyweight,0)
  5510. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5511. if err != nil {
  5512. tx.Rollback()
  5513. logs.Error(err)
  5514. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5515. return
  5516. }
  5517. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5518. _, err = tx.SQL(`
  5519. UPDATE fpdetail fpd
  5520. INNER JOIN feedp fp
  5521. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5522. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5523. ptuse= 0
  5524. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5525. if err != nil {
  5526. tx.Rollback()
  5527. logs.Error(err)
  5528. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5529. return
  5530. }
  5531. } else {
  5532. _, err := tx.SQL(`UPDATE feedp fp
  5533. SET
  5534. fp.supplyweight= IFNULL(IF(
  5535. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5536. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5537. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5538. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5539. ),0),fp.feedweight = IFNULL(IF(
  5540. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5541. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5542. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5543. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5544. ),0) + ifnull(fp.supplyweight,0)
  5545. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5546. if err != nil {
  5547. tx.Rollback()
  5548. logs.Error(err)
  5549. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5550. return
  5551. }
  5552. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5553. _, err = tx.SQL(`
  5554. UPDATE fpdetail fpd
  5555. INNER JOIN feedp fp
  5556. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5557. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5558. ptsrate = 0
  5559. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5560. if err != nil {
  5561. tx.Rollback()
  5562. logs.Error(err)
  5563. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5564. return
  5565. }
  5566. }
  5567. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5568. if err != nil {
  5569. tx.Rollback()
  5570. logs.Error(err)
  5571. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5572. return
  5573. }
  5574. err = tx.Commit()
  5575. if err != nil {
  5576. tx.Rollback()
  5577. logs.Error(err)
  5578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5579. return
  5580. }
  5581. appG.Response(http.StatusOK, e.SUCCESS, true)
  5582. }
  5583. func DeleteSpillageAll(c *gin.Context) {
  5584. appG := app.Gin{C: c}
  5585. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5586. fsion := gofasion.NewFasion(string(dataByte))
  5587. parammaps := fsion.Get("parammaps")
  5588. pastureid := parammaps.Get("pastureid").ValueStr()
  5589. times := parammaps.Get("times").ValueStr()
  5590. barid := parammaps.Get("barid").ValueStr()
  5591. tx := restful.Engine.NewSession()
  5592. defer tx.Close()
  5593. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5594. if err != nil {
  5595. logs.Error(err)
  5596. appG.Response(http.StatusOK, e.ERROR, false)
  5597. return
  5598. }
  5599. now := time.Now()
  5600. for _, item := range lpplandtl1List {
  5601. go func(item map[string]interface{}) {
  5602. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5603. background,cowcount,ccountradio,lweighthis,createdate)
  5604. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5605. item["pastureid"], item["lppid"], item["barid"],
  5606. item["barname"], item["fpdid"], item["fttype"],
  5607. item["lweight"], item["sort"], item["tmrid"],
  5608. item["tmrname"], item["background"], item["cowcount"],
  5609. item["ccountradio"], item["lweighthis"], now).Execute()
  5610. if err != nil {
  5611. logs.Error(err)
  5612. appG.Response(http.StatusOK, e.ERROR, false)
  5613. return
  5614. }
  5615. }(item)
  5616. }
  5617. tx.Begin()
  5618. _, 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()
  5619. if err != nil {
  5620. tx.Rollback()
  5621. logs.Error(err)
  5622. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5623. return
  5624. }
  5625. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5626. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5627. if err != nil {
  5628. tx.Rollback()
  5629. logs.Error(err)
  5630. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5631. return
  5632. }
  5633. err = tx.Commit()
  5634. if err != nil {
  5635. tx.Rollback()
  5636. logs.Error(err)
  5637. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5638. return
  5639. }
  5640. appG.Response(http.StatusOK, e.SUCCESS, true)
  5641. }
  5642. func GetTMRListEnableTypeAll(c *gin.Context) {
  5643. appG := app.Gin{C: c}
  5644. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5645. fsion := gofasion.NewFasion(string(dataByte))
  5646. parammaps := fsion.Get("parammaps")
  5647. pastureid := parammaps.Get("pastureid").ValueStr()
  5648. tx := restful.Engine.NewSession()
  5649. defer tx.Close()
  5650. dataList, err := tx.SQL(`SELECT
  5651. eqcode,
  5652. tname,
  5653. datacaptureno,
  5654. trim(tclassid) tclassid,
  5655. concat(tname,' / ',eqcode) tmrmix,
  5656. d.label tclassname,
  5657. maxstirfeed,
  5658. remark,
  5659. tmr.enable,
  5660. TRIM(tmr.id) id,
  5661. TRIM(tmr.pastureid)pastureid
  5662. FROM
  5663. tmr
  5664. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5665. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5666. ORDER BY id DESC`, pastureid).Query().List()
  5667. if err != nil {
  5668. logs.Error(err)
  5669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5670. return
  5671. }
  5672. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5673. if err != nil {
  5674. logs.Error(err)
  5675. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5676. return
  5677. }
  5678. var carNum int64
  5679. for _, sysopt := range sysoptData {
  5680. if sysopt["inforvalue"] == nil {
  5681. carNum = 1
  5682. } else {
  5683. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5684. }
  5685. }
  5686. id := 200
  5687. n := 0
  5688. for i := carNum; i > 0; i-- {
  5689. id++
  5690. n++
  5691. data := make(map[string]interface{}, 0)
  5692. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5693. data["tname"] = fmt.Sprintf("任意车%d", n)
  5694. data["datacaptureno"] = -2
  5695. data["tclassid"] = -2
  5696. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5697. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5698. data["maxstirfeed"] = 100000
  5699. data["remark"] = fmt.Sprintf("任意车%d", n)
  5700. data["enable"] = 1
  5701. data["id"] = fmt.Sprintf("%d", id)
  5702. data["pastureid"] = pastureid
  5703. dataList = append(dataList, data)
  5704. }
  5705. // UNION ALL
  5706. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5707. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5708. }
  5709. func GetFeedpHistory(c *gin.Context) {
  5710. appG := app.Gin{C: c}
  5711. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5712. fsion := gofasion.NewFasion(string(dataByte))
  5713. // parammaps := fsion.Get("parammaps")
  5714. bar := fsion.Get("barname").ValueStr()
  5715. startDate := fsion.Get("startDate").ValueStr()
  5716. endDate := fsion.Get("endDate").ValueStr()
  5717. tx := restful.Engine.NewSession()
  5718. defer tx.Close()
  5719. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5720. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5721. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5722. if err != nil {
  5723. logs.Error(err)
  5724. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5725. return
  5726. }
  5727. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5728. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5729. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5730. if err != nil {
  5731. logs.Error(err)
  5732. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5733. return
  5734. }
  5735. for _, feedp := range feedpList {
  5736. // LastftList, err := tx.SQL(` select tname ,id
  5737. // from feedtemplethistory where id = ?
  5738. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5739. // if err != nil {
  5740. // logs.Error(err)
  5741. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5742. // return
  5743. // }
  5744. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5745. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5746. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5747. if err != nil {
  5748. logs.Error(err)
  5749. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5750. return
  5751. }
  5752. var ftname interface{}
  5753. ftnamestatus := 0
  5754. ftname = feedp["ftname"]
  5755. var lastftid int64
  5756. if len(nextfeedpList) > 0 {
  5757. for _, ft := range nextfeedpList {
  5758. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5759. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5760. lastftid = ft["ftid"].(int64)
  5761. ftnamestatus = 1
  5762. break
  5763. }
  5764. }
  5765. }
  5766. for i, fpd := range fpdList {
  5767. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5768. fpd["weightstatus"] = 0
  5769. fpd["tratiostatus"] = 0
  5770. fpd["ftnamestatus"] = ftnamestatus
  5771. for k, fpd2 := range fpdList {
  5772. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5773. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5774. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5775. fpd["weightstatus"] = 1
  5776. }
  5777. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5778. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5779. fpd["tratiostatus"] = 1
  5780. }
  5781. break
  5782. }
  5783. }
  5784. fpd["barid"] = feedp["barid"]
  5785. fpd["barname"] = feedp["barname"]
  5786. fpd["ccount"] = feedp["ccount"]
  5787. fpd["ratio"] = feedp["ratio"]
  5788. fpd["ccountratio"] = feedp["ccountratio"]
  5789. fpd["ftid"] = feedp["ftid"]
  5790. fpd["ftname"] = ftname
  5791. fpd["ccountstatus"] = 0
  5792. fpd["ccountratiostatus"] = 0
  5793. fpd["ratiostatus"] = 0
  5794. fpd["ftnamestatus"] = 0
  5795. fpd["lastftid"] = lastftid
  5796. for _, next := range nextfeedpList {
  5797. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5798. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5799. fpd["ccountstatus"] = 1
  5800. }
  5801. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5802. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5803. fpd["ccountratiostatus"] = 1
  5804. }
  5805. if next["ratio"].(string) != fpd["ratio"].(string) {
  5806. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5807. fpd["ratiostatus"] = 1
  5808. }
  5809. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5810. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5811. // fpd["ftnamestatus"] = 1
  5812. // }
  5813. }
  5814. }
  5815. }
  5816. }
  5817. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5818. }
  5819. // func GetLpplandtl1History(c *gin.Context) {
  5820. // appG := app.Gin{C: c}
  5821. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5822. // fsion := gofasion.NewFasion(string(dataByte))
  5823. // // parammaps := fsion.Get("parammaps")
  5824. // barid := fsion.Get("barid").ValueStr()
  5825. // startDate := fsion.Get("startDate").ValueStr()
  5826. // endDate := fsion.Get("endDate").ValueStr()
  5827. // tx := restful.Engine.NewSession()
  5828. // defer tx.Close()
  5829. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5830. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5831. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5832. // // if err != nil {
  5833. // // logs.Error(err)
  5834. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5835. // // return
  5836. // // }
  5837. // // for _, feedp := range feedpList {
  5838. // // fmt.Println(feedp)
  5839. // // for i, fpd := range fpdList {
  5840. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5841. // // for k, fpd2 := range fpdList {
  5842. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5843. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5844. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5845. // // }
  5846. // // break
  5847. // // }
  5848. // // }
  5849. // // fpd["barid"] = feedp["barid"]
  5850. // // fpd["barname"] = feedp["barname"]
  5851. // // fpd["ccount"] = feedp["ccount"]
  5852. // // fpd["ratio"] = feedp["ratio"]
  5853. // // fpd["ccountratio"] = feedp["ccountratio"]
  5854. // // fpd["ftid"] = feedp["ftid"]
  5855. // // fpd["ftname"] = feedp["ftname"]
  5856. // // }
  5857. // // }
  5858. // // }
  5859. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5860. // }
  5861. func GetRemind(c *gin.Context) {
  5862. appG := app.Gin{C: c}
  5863. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5864. fsion := gofasion.NewFasion(string(dataByte))
  5865. parammaps := fsion.Get("parammaps")
  5866. pastureid := parammaps.Get("pastureid").ValueStr()
  5867. tx := restful.Engine.NewSession()
  5868. defer tx.Close()
  5869. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5870. if err != nil {
  5871. logs.Error(err)
  5872. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5873. return
  5874. }
  5875. // pastureid = "3"
  5876. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5877. if err != nil {
  5878. logs.Error(err)
  5879. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5880. return
  5881. }
  5882. defer resp.Body.Close()
  5883. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5884. buf.ReadFrom(resp.Body)
  5885. fmt.Println(string(buf.Bytes()))
  5886. respMap := make(map[string]interface{}, 0)
  5887. err = json.Unmarshal(buf.Bytes(), &respMap)
  5888. if err != nil {
  5889. logs.Error(err)
  5890. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5891. return
  5892. }
  5893. for _, data := range dataList {
  5894. r := make(map[string]interface{}, 0)
  5895. r["sys_name"] = ""
  5896. r["service_id"] = ""
  5897. r["pasture_id"] = ""
  5898. r["type_name"] = ""
  5899. r["remind_type_id"] = ""
  5900. r["remind_type"] = ""
  5901. r["push_date"] = ""
  5902. r["push_time"] = ""
  5903. r["interval_time"] = ""
  5904. r["push_limit"] = ""
  5905. r["template_id"] = ""
  5906. r["roles_id"] = ""
  5907. r["users_id"] = ""
  5908. r["date_type"] = ""
  5909. r["cycle_type"] = ""
  5910. data["data"] = r
  5911. for _, resp := range respMap["data"].([]interface{}) {
  5912. resp1 := resp.(map[string]interface{})
  5913. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5914. if resp1["push_time"] == nil {
  5915. resp1["push_time"] = ""
  5916. }
  5917. data["data"] = resp1
  5918. break
  5919. }
  5920. }
  5921. }
  5922. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5923. }
  5924. type NoticeMsgtype struct {
  5925. SysName string `json:"sys_name"`
  5926. PastureId int64 `json:"pasture_id"`
  5927. ServiceId int64 `json:"service_id"`
  5928. TypeName string `json:"type_name"`
  5929. RemindType int64 `json:"remind_type"`
  5930. PushDate int64 `json:"push_date"`
  5931. PushTime string `json:"push_time"`
  5932. IntervalTime int64 `json:"interval_time"`
  5933. PushLimit int64 `json:"push_limit"`
  5934. TemplateId string `json:"template_id"`
  5935. UsersId string `json:"users_id"`
  5936. DateType int64 `json:"date_type"`
  5937. CycleType int64 `json:"cycle_type"`
  5938. DelayTime int64 `json:"delay_time"`
  5939. Status int64 `json:"status"`
  5940. }
  5941. func UpdateRemind(c *gin.Context) {
  5942. appG := app.Gin{C: c}
  5943. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5944. parammaps := gofasion.NewFasion(string(dataByte))
  5945. // parammaps := fsion.Get("parammaps")
  5946. // user := parammaps.Get("user").ValueStr()
  5947. id := parammaps.Get("id").ValueInt64()
  5948. noticeMsgtype := new(NoticeMsgtype)
  5949. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5950. noticeMsgtype.ServiceId = id
  5951. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5952. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5953. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5954. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5955. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5956. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5957. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5958. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5959. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5960. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5961. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5962. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5963. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5964. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5965. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5966. //TODO
  5967. noticeMsgtype.SysName = "tmrWatch"
  5968. userList := parammaps.Get("user").Array()
  5969. var userstr []string
  5970. for _, user := range userList {
  5971. userstr = append(userstr, user.ValueStr())
  5972. }
  5973. tx := restful.Engine.NewSession()
  5974. defer tx.Close()
  5975. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5976. if err != nil {
  5977. logs.Error(err)
  5978. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5979. return
  5980. }
  5981. // var jsonStr = []byte(noticeMsgtype
  5982. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5983. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5984. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5985. req.Header.Set("Content-Type", "application/json")
  5986. client := &http.Client{}
  5987. resp, err := client.Do(req)
  5988. if err != nil {
  5989. logs.Error(err)
  5990. }
  5991. defer resp.Body.Close()
  5992. body, _ := ioutil.ReadAll(resp.Body)
  5993. fmt.Println("response Body:", string(body))
  5994. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5995. if err != nil {
  5996. logs.Error(err)
  5997. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5998. return
  5999. }
  6000. defer getresp.Body.Close()
  6001. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6002. buf.ReadFrom(getresp.Body)
  6003. // fmt.Println(string(buf.Bytes()))
  6004. respMap := make(map[string]interface{}, 0)
  6005. err = json.Unmarshal(buf.Bytes(), &respMap)
  6006. if err != nil {
  6007. logs.Error(err)
  6008. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6009. return
  6010. }
  6011. for _, resp := range respMap["data"].([]interface{}) {
  6012. resp1 := resp.(map[string]interface{})
  6013. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6014. if err != nil {
  6015. logs.Error(err)
  6016. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6017. return
  6018. }
  6019. }
  6020. appG.Response(http.StatusOK, e.SUCCESS, true)
  6021. }
  6022. func GetSpillageallHistory(c *gin.Context) {
  6023. appG := app.Gin{C: c}
  6024. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6025. parammaps := gofasion.NewFasion(string(dataByte))
  6026. barname := parammaps.Get("barname").ValueStr()
  6027. pastureid := parammaps.Get("pastureid").ValueStr()
  6028. startdate := parammaps.Get("startDate").ValueStr()
  6029. enddate := parammaps.Get("endDate").ValueStr()
  6030. tx := restful.Engine.NewSession()
  6031. defer tx.Close()
  6032. 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
  6033. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6034. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6035. if err != nil {
  6036. logs.Error(err)
  6037. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6038. return
  6039. }
  6040. respMap := make([]map[string]interface{}, 0)
  6041. data := make(map[interface{}]interface{})
  6042. for _, history := range historyList {
  6043. data[history["createdate"]] = history["createdate"]
  6044. }
  6045. createList := []string{}
  6046. for _, v := range data {
  6047. createList = append(createList, v.(string))
  6048. }
  6049. // sort.Sort()
  6050. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6051. sort.Slice(createList, func(i, j int) bool {
  6052. return createList[i] > createList[j]
  6053. })
  6054. for _, v := range createList {
  6055. a := make(map[string]interface{})
  6056. a["createdate"] = data[v]
  6057. // createList = append(createList, v.(string))
  6058. respMap = append(respMap, a)
  6059. }
  6060. number := 0
  6061. dataMap := make([]interface{}, 0)
  6062. for k, resp := range respMap {
  6063. createdate := resp["createdate"].(string)
  6064. var nextcreatedate string
  6065. if len(respMap) > k+1 {
  6066. nextcreatedate = respMap[k+1]["createdate"].(string)
  6067. }
  6068. // dataList := make(map[string][]interface{})
  6069. // list := make(map[string]interface{})
  6070. times := make(map[interface{}]int)
  6071. for _, history := range historyList {
  6072. // List := make(map[interface{}][]interface{})
  6073. i := 0
  6074. if history["createdate"].(string) == createdate {
  6075. times[history["times"]]++
  6076. data := make(map[string]interface{})
  6077. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6078. // exist := false
  6079. if nextcreatedate != "" {
  6080. for _, history1 := range historyList {
  6081. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6082. history1["times"].(int64) == history["times"].(int64) {
  6083. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6084. break
  6085. // exist = true
  6086. }
  6087. }
  6088. }
  6089. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6090. i++
  6091. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6092. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6093. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6094. // resp["times"] = history["times"]
  6095. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6096. data1 := make(map[string]interface{})
  6097. data1["times"] = history["times"]
  6098. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6099. data1["createdate"] = resp["createdate"]
  6100. // fmt.Println(dataList)
  6101. dataMap = append(dataMap, data1)
  6102. }
  6103. if i > number {
  6104. number = i
  6105. }
  6106. // respMap = append(respMap, dataList)
  6107. }
  6108. // for k, data := range dataList {
  6109. // resp[k] = data
  6110. // }
  6111. // resp["data"] = dataList
  6112. }
  6113. // resp := make(map[string]interface{})
  6114. // sort.Strings(createList)
  6115. //
  6116. // for _, create := range createList {
  6117. // for _, r := range respMap {
  6118. // if create == r["createdate"].(string) {
  6119. // resp[create] = r
  6120. // break
  6121. // }
  6122. // }
  6123. // }
  6124. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6125. var trainsList []interface{}
  6126. for i := 0; i < number; i++ {
  6127. trains := make(map[string]interface{})
  6128. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6129. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6130. trainsList = append(trainsList, trains)
  6131. }
  6132. respdata := make(map[string]interface{})
  6133. respdata["data"] = dataMap
  6134. respdata["trains"] = trainsList
  6135. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6136. }
  6137. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6138. appG := app.Gin{C: c}
  6139. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6140. parammaps := gofasion.NewFasion(string(dataByte))
  6141. ftid := parammaps.Get("ftid").ValueInt64()
  6142. lastftid := parammaps.Get("lastftid").ValueInt64()
  6143. pastureid := parammaps.Get("pastureid").ValueInt64()
  6144. // createdate := parammaps.Get("createdate").ValueStr()
  6145. tx := restful.Engine.NewSession()
  6146. defer tx.Close()
  6147. data := make(map[string]interface{})
  6148. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6149. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6150. if err != nil {
  6151. logs.Error(err)
  6152. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6153. return
  6154. }
  6155. feedtemplet := make(map[string]interface{})
  6156. for _, f := range feedtempletList {
  6157. feedtemplet = f
  6158. }
  6159. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6160. if err != nil {
  6161. logs.Error(err)
  6162. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6163. return
  6164. }
  6165. feedtemplet["fit"] = fitList
  6166. data["current"] = feedtemplet
  6167. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6168. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6169. if err != nil {
  6170. logs.Error(err)
  6171. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6172. return
  6173. }
  6174. lastfeedtemplet := make(map[string]interface{})
  6175. for _, f := range lastfeedtempletList {
  6176. lastfeedtemplet = f
  6177. }
  6178. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6179. if err != nil {
  6180. logs.Error(err)
  6181. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6182. return
  6183. }
  6184. lastfeedtemplet["fit"] = lastfitList
  6185. data["last"] = lastfeedtemplet
  6186. appG.Response(http.StatusOK, e.SUCCESS, data)
  6187. }
  6188. func GetFeedtempletHistory(c *gin.Context) {
  6189. appG := app.Gin{C: c}
  6190. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6191. parammaps := gofasion.NewFasion(string(dataByte))
  6192. ftid := parammaps.Get("ftid").ValueStr()
  6193. pastureid := parammaps.Get("pastureid").ValueInt64()
  6194. start := parammaps.Get("startdate").ValueStr()
  6195. end := parammaps.Get("enddate").ValueStr()
  6196. tx := restful.Engine.NewSession()
  6197. defer tx.Close()
  6198. 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 ?
  6199. and id = ? and pastureid = ? order by createdate desc `,
  6200. start, end, ftid, pastureid).Query().List()
  6201. if err != nil {
  6202. logs.Error(err)
  6203. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6204. return
  6205. }
  6206. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6207. ftid, pastureid).Query().List()
  6208. if err != nil {
  6209. logs.Error(err)
  6210. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6211. return
  6212. }
  6213. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6214. for i, ft := range ftList {
  6215. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6216. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6217. (select empname from user where id = fit.userId) empname,
  6218. 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
  6219. where fit.fitid = ?
  6220. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6221. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6222. if err != nil {
  6223. logs.Error(err)
  6224. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6225. return
  6226. }
  6227. ft["createdate"] = ft["createdate1"]
  6228. // data["tname"] = ft["tname"]
  6229. // data["tcode"] = ft["tcode"]
  6230. // data["tcolor"] = ft["tcolor"]
  6231. // data["fttype"] = ft["fttype"]
  6232. // data["ccname"] = ft["ccname"]
  6233. // data["source"] = ft["source"]
  6234. // data["version"] = ft["version"]
  6235. // data["remark"] = ft["remark"]
  6236. for n, ft2 := range ftList {
  6237. if i < n {
  6238. if ft["tname"].(string) != ft2["tname"].(string) {
  6239. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6240. }
  6241. if _, ok := ft["tcode"]; ok {
  6242. if _, ok := ft2["tcode"]; ok {
  6243. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6244. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6245. }
  6246. }
  6247. }
  6248. if _, ok := ft["tcolor"]; ok {
  6249. if _, ok := ft2["tcolor"]; ok {
  6250. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6251. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6252. }
  6253. }
  6254. }
  6255. if _, ok := ft["fttype"]; ok {
  6256. if _, ok := ft2["fttype"]; ok {
  6257. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6258. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6259. }
  6260. }
  6261. }
  6262. if _, ok := ft["ccname"]; ok {
  6263. if _, ok := ft2["ccname"]; ok {
  6264. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6265. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6266. }
  6267. }
  6268. }
  6269. if _, ok := ft["source"]; ok {
  6270. if _, ok := ft2["source"]; ok {
  6271. if ft["source"].(string) != ft2["source"].(string) {
  6272. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6273. }
  6274. }
  6275. }
  6276. if _, ok := ft["version"]; ok {
  6277. if _, ok := ft2["version"]; ok {
  6278. if ft["version"].(int64) != ft2["version"].(int64) {
  6279. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6280. }
  6281. }
  6282. }
  6283. if _, ok := ft["remark"]; ok {
  6284. if _, ok := ft2["remark"]; ok {
  6285. if ft["remark"].(string) != ft2["remark"].(string) {
  6286. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6287. }
  6288. }
  6289. }
  6290. break
  6291. }
  6292. }
  6293. dataList := make([]map[string]interface{}, 0)
  6294. if len(fithisList) > 0 {
  6295. for _, fit := range fithisList {
  6296. data := make(map[string]interface{})
  6297. data["feedgroup"] = fit["feedgroup"]
  6298. data["fname"] = fit["fname"]
  6299. data["empname"] = fit["empname"]
  6300. if fit["Eweight"] != nil {
  6301. if fit["Eweight"].(string) != fit["weight"].(string) {
  6302. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6303. } else {
  6304. data["fweight"] = fit["Eweight"]
  6305. }
  6306. data["fweightstatus"] = 1
  6307. } else {
  6308. data["fweight"] = fit["weight"]
  6309. data["fweightstatus"] = 0
  6310. }
  6311. data["autosecond"] = fit["autosecond"]
  6312. // data["tname"] = ft["tname"]
  6313. // data["tcode"] = ft["tcode"]
  6314. // data["tcolor"] = ft["tcolor"]
  6315. // data["fttype"] = ft["fttype"]
  6316. // data["ccname"] = ft["ccname"]
  6317. // data["source"] = ft["source"]
  6318. // data["version"] = ft["version"]
  6319. // data["remark"] = ft["remark"]
  6320. // data["createdate"] = ft["createdate1"]
  6321. // ft["fit"] = data
  6322. dataList = append(dataList, data)
  6323. }
  6324. } else {
  6325. for _, fit := range ftdetailList {
  6326. data := make(map[string]interface{})
  6327. data["feedgroup"] = fit["feedgroup"]
  6328. data["fname"] = fit["fname"]
  6329. // if fit["Eweight"] != nil {
  6330. // data["weight"] = fit["Eweight"]
  6331. // } else {
  6332. data["fweight"] = fit["fweight"]
  6333. // }
  6334. data["autosecond"] = fit["autosecond"]
  6335. // ft["fit"] = data
  6336. dataList = append(dataList, data)
  6337. }
  6338. }
  6339. ft["fit"] = dataList
  6340. }
  6341. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6342. }
  6343. func UpdateMaterialTMR(c *gin.Context) {
  6344. appG := app.Gin{C: c}
  6345. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6346. parammaps := gofasion.NewFasion(string(dataByte))
  6347. tmrid := parammaps.Get("tmrid").ValueStr()
  6348. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6349. lppid := parammaps.Get("lppid").ValueStr()
  6350. times := parammaps.Get("times").ValueStr()
  6351. pastureid := parammaps.Get("pastureid").ValueStr()
  6352. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6353. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6354. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6355. tx := restful.Engine.NewSession()
  6356. defer tx.Close()
  6357. tx.Begin()
  6358. if tmrid != "1000" {
  6359. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6360. if err != nil {
  6361. logs.Error(err)
  6362. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6363. return
  6364. }
  6365. var maxstirfeed float64
  6366. for _, tmr := range tmrList {
  6367. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6368. }
  6369. if status == 0 {
  6370. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6371. if err != nil {
  6372. tx.Rollback()
  6373. logs.Error(err)
  6374. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6375. return
  6376. }
  6377. var lweight float64
  6378. for _, item := range lpplandtl1List {
  6379. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6380. lweight += fl
  6381. }
  6382. if lweight > maxstirfeed {
  6383. lweight = lweight - maxstirfeed
  6384. } else {
  6385. lweight = 0
  6386. }
  6387. if lweight > 0 {
  6388. lweight1 := lweight / float64(len(lpplandtl1List))
  6389. number := 0
  6390. for _, item := range lpplandtl1List {
  6391. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6392. if lweight1 >= fl {
  6393. number++
  6394. }
  6395. }
  6396. lweight := lweight / float64((len(lpplandtl1List) - number))
  6397. for _, item := range lpplandtl1List {
  6398. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6399. if lweight1 >= fl {
  6400. continue
  6401. }
  6402. if tmrtype == "1" {
  6403. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6404. if err != nil {
  6405. tx.Rollback()
  6406. logs.Error(err)
  6407. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6408. return
  6409. }
  6410. } else if tmrtype == "2" {
  6411. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6412. if err != nil {
  6413. tx.Rollback()
  6414. logs.Error(err)
  6415. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6416. return
  6417. }
  6418. }
  6419. if item["fttype"].(int64) == 0 {
  6420. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6421. if err != nil {
  6422. tx.Rollback()
  6423. logs.Error(err)
  6424. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6425. return
  6426. }
  6427. } else {
  6428. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6429. if err != nil {
  6430. tx.Rollback()
  6431. logs.Error(err)
  6432. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6433. return
  6434. }
  6435. }
  6436. }
  6437. } else {
  6438. for _, item := range lpplandtl1List {
  6439. // 自走式
  6440. if tmrtype == "1" {
  6441. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6442. if err != nil {
  6443. logs.Error(err)
  6444. tx.Rollback()
  6445. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6446. return
  6447. }
  6448. } else if tmrtype == "2" {
  6449. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6450. if err != nil {
  6451. logs.Error(err)
  6452. tx.Rollback()
  6453. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6454. return
  6455. }
  6456. }
  6457. }
  6458. }
  6459. } else if status == 1 {
  6460. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6461. if err != nil {
  6462. logs.Error(err)
  6463. tx.Rollback()
  6464. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6465. return
  6466. }
  6467. var lweight float64
  6468. for _, item := range lpplandtl1List {
  6469. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6470. lweight += fl
  6471. }
  6472. if lweight > maxstirfeed {
  6473. lweight = lweight - maxstirfeed
  6474. } else {
  6475. lweight = 0
  6476. }
  6477. for _, item := range lpplandtl1List {
  6478. if lweight > 0 {
  6479. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6480. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6481. if fl >= lweight {
  6482. item["lweight"] = fl - lweight
  6483. lweight = 0
  6484. if tmrtype == "1" {
  6485. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6486. if err != nil {
  6487. logs.Error(err)
  6488. tx.Rollback()
  6489. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6490. return
  6491. }
  6492. } else if tmrtype == "2" {
  6493. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6494. if err != nil {
  6495. logs.Error(err)
  6496. tx.Rollback()
  6497. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6498. return
  6499. }
  6500. }
  6501. if item["fttype"].(int64) == 0 {
  6502. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6503. if err != nil {
  6504. logs.Error(err)
  6505. tx.Rollback()
  6506. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6507. return
  6508. }
  6509. } else {
  6510. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6511. if err != nil {
  6512. logs.Error(err)
  6513. tx.Rollback()
  6514. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6515. return
  6516. }
  6517. }
  6518. } else {
  6519. lweight = lweight - fl
  6520. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6521. if err != nil {
  6522. logs.Error(err)
  6523. tx.Rollback()
  6524. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6525. return
  6526. }
  6527. if item["fttype"].(int64) == 0 {
  6528. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6529. if err != nil {
  6530. logs.Error(err)
  6531. tx.Rollback()
  6532. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6533. return
  6534. }
  6535. } else {
  6536. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6537. if err != nil {
  6538. logs.Error(err)
  6539. tx.Rollback()
  6540. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6541. return
  6542. }
  6543. }
  6544. }
  6545. } else {
  6546. // 自走式
  6547. if tmrtype == "1" {
  6548. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6549. if err != nil {
  6550. logs.Error(err)
  6551. tx.Rollback()
  6552. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6553. return
  6554. }
  6555. } else if tmrtype == "2" {
  6556. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6557. if err != nil {
  6558. logs.Error(err)
  6559. tx.Rollback()
  6560. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6561. return
  6562. }
  6563. }
  6564. }
  6565. }
  6566. } else {
  6567. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6568. if err != nil {
  6569. logs.Error(err)
  6570. tx.Rollback()
  6571. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6572. return
  6573. }
  6574. for _, item := range lpplandtl1List {
  6575. if item["fttype"].(int64) == 0 {
  6576. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6577. if err != nil {
  6578. logs.Error(err)
  6579. tx.Rollback()
  6580. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6581. return
  6582. }
  6583. } else {
  6584. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6585. if err != nil {
  6586. logs.Error(err)
  6587. tx.Rollback()
  6588. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6589. return
  6590. }
  6591. }
  6592. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6593. if err != nil {
  6594. logs.Error(err)
  6595. tx.Rollback()
  6596. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6597. return
  6598. }
  6599. }
  6600. }
  6601. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6602. if err != nil {
  6603. logs.Error(err)
  6604. tx.Rollback()
  6605. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6606. return
  6607. }
  6608. } else {
  6609. if status == 2 {
  6610. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6611. if err != nil {
  6612. logs.Error(err)
  6613. tx.Rollback()
  6614. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6615. return
  6616. }
  6617. for _, item := range lpplandtl1List {
  6618. if item["fttype"].(int64) == 0 {
  6619. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6620. if err != nil {
  6621. logs.Error(err)
  6622. tx.Rollback()
  6623. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6624. return
  6625. }
  6626. } else {
  6627. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6628. if err != nil {
  6629. logs.Error(err)
  6630. tx.Rollback()
  6631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6632. return
  6633. }
  6634. }
  6635. }
  6636. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6637. if err != nil {
  6638. logs.Error(err)
  6639. tx.Rollback()
  6640. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6641. return
  6642. }
  6643. } else {
  6644. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6645. if err != nil {
  6646. logs.Error(err)
  6647. tx.Rollback()
  6648. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6649. return
  6650. }
  6651. }
  6652. }
  6653. err := tx.Commit()
  6654. if err != nil {
  6655. logs.Error(err)
  6656. tx.Rollback()
  6657. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6658. return
  6659. }
  6660. appG.Response(http.StatusOK, e.SUCCESS, true)
  6661. }
  6662. func UpdateMaterialTMRDate(c *gin.Context) {
  6663. appG := app.Gin{C: c}
  6664. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6665. parammaps := gofasion.NewFasion(string(dataByte))
  6666. tmrid := parammaps.Get("tmrid").ValueStr()
  6667. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6668. lppid := parammaps.Get("lppid").ValueStr()
  6669. times := parammaps.Get("times").ValueStr()
  6670. pastureid := parammaps.Get("pastureid").ValueStr()
  6671. date := parammaps.Get("date").ValueStr()
  6672. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6673. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6674. tx := restful.Engine.NewSession()
  6675. defer tx.Close()
  6676. tx.Begin()
  6677. if tmrid != "1000" {
  6678. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6679. if err != nil {
  6680. logs.Error(err)
  6681. tx.Rollback()
  6682. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6683. return
  6684. }
  6685. var maxstirfeed float64
  6686. for _, tmr := range tmrList {
  6687. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6688. }
  6689. if status == 0 {
  6690. 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()
  6691. if err != nil {
  6692. logs.Error(err)
  6693. tx.Rollback()
  6694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6695. return
  6696. }
  6697. var lweight float64
  6698. for _, item := range lpplandtl1List {
  6699. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6700. lweight += fl
  6701. }
  6702. if lweight > maxstirfeed {
  6703. lweight = lweight - maxstirfeed
  6704. } else {
  6705. lweight = 0
  6706. }
  6707. if lweight > 0 {
  6708. lweight1 := lweight / float64(len(lpplandtl1List))
  6709. number := 0
  6710. for _, item := range lpplandtl1List {
  6711. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6712. if lweight1 >= fl {
  6713. number++
  6714. }
  6715. }
  6716. lweight := lweight / float64((len(lpplandtl1List) - number))
  6717. for _, item := range lpplandtl1List {
  6718. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6719. if lweight1 >= fl {
  6720. continue
  6721. }
  6722. if tmrtype == "1" {
  6723. _, 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()
  6724. if err != nil {
  6725. logs.Error(err)
  6726. tx.Rollback()
  6727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6728. return
  6729. }
  6730. } else if tmrtype == "2" {
  6731. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6732. if err != nil {
  6733. logs.Error(err)
  6734. tx.Rollback()
  6735. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6736. return
  6737. }
  6738. }
  6739. if item["fttype"].(int64) == 0 {
  6740. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6741. if err != nil {
  6742. logs.Error(err)
  6743. tx.Rollback()
  6744. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6745. return
  6746. }
  6747. } else {
  6748. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6749. if err != nil {
  6750. logs.Error(err)
  6751. tx.Rollback()
  6752. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6753. return
  6754. }
  6755. }
  6756. }
  6757. } else {
  6758. for _, item := range lpplandtl1List {
  6759. // 自走式
  6760. if tmrtype == "1" {
  6761. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6762. if err != nil {
  6763. logs.Error(err)
  6764. tx.Rollback()
  6765. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6766. return
  6767. }
  6768. } else if tmrtype == "2" {
  6769. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6770. if err != nil {
  6771. logs.Error(err)
  6772. tx.Rollback()
  6773. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6774. return
  6775. }
  6776. }
  6777. }
  6778. }
  6779. } else if status == 1 {
  6780. 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()
  6781. if err != nil {
  6782. logs.Error(err)
  6783. tx.Rollback()
  6784. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6785. return
  6786. }
  6787. var lweight float64
  6788. for _, item := range lpplandtl1List {
  6789. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6790. lweight += fl
  6791. }
  6792. if lweight > maxstirfeed {
  6793. lweight = lweight - maxstirfeed
  6794. } else {
  6795. lweight = 0
  6796. }
  6797. for _, item := range lpplandtl1List {
  6798. if lweight > 0 {
  6799. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6800. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6801. if fl >= lweight {
  6802. item["lweight"] = fl - lweight
  6803. lweight = 0
  6804. if tmrtype == "1" {
  6805. _, 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()
  6806. if err != nil {
  6807. logs.Error(err)
  6808. tx.Rollback()
  6809. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6810. return
  6811. }
  6812. } else if tmrtype == "2" {
  6813. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6814. if err != nil {
  6815. logs.Error(err)
  6816. tx.Rollback()
  6817. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6818. return
  6819. }
  6820. }
  6821. if item["fttype"].(int64) == 0 {
  6822. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6823. if err != nil {
  6824. logs.Error(err)
  6825. tx.Rollback()
  6826. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6827. return
  6828. }
  6829. } else {
  6830. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6831. if err != nil {
  6832. logs.Error(err)
  6833. tx.Rollback()
  6834. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6835. return
  6836. }
  6837. }
  6838. } else {
  6839. lweight = lweight - fl
  6840. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6841. if err != nil {
  6842. logs.Error(err)
  6843. tx.Rollback()
  6844. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6845. return
  6846. }
  6847. if item["fttype"].(int64) == 0 {
  6848. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6849. if err != nil {
  6850. logs.Error(err)
  6851. tx.Rollback()
  6852. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6853. return
  6854. }
  6855. } else {
  6856. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6857. if err != nil {
  6858. logs.Error(err)
  6859. tx.Rollback()
  6860. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6861. return
  6862. }
  6863. }
  6864. }
  6865. } else {
  6866. // 自走式
  6867. if tmrtype == "1" {
  6868. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6869. if err != nil {
  6870. logs.Error(err)
  6871. tx.Rollback()
  6872. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6873. return
  6874. }
  6875. } else if tmrtype == "2" {
  6876. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6877. if err != nil {
  6878. logs.Error(err)
  6879. tx.Rollback()
  6880. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6881. return
  6882. }
  6883. }
  6884. }
  6885. }
  6886. } else {
  6887. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6888. if err != nil {
  6889. logs.Error(err)
  6890. tx.Rollback()
  6891. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6892. return
  6893. }
  6894. for _, item := range lpplandtl1List {
  6895. if item["fttype"].(int64) == 0 {
  6896. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6897. if err != nil {
  6898. logs.Error(err)
  6899. tx.Rollback()
  6900. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6901. return
  6902. }
  6903. } else {
  6904. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6905. if err != nil {
  6906. logs.Error(err)
  6907. tx.Rollback()
  6908. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6909. return
  6910. }
  6911. }
  6912. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6913. if err != nil {
  6914. logs.Error(err)
  6915. tx.Rollback()
  6916. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6917. return
  6918. }
  6919. }
  6920. }
  6921. _, 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()
  6922. if err != nil {
  6923. logs.Error(err)
  6924. tx.Rollback()
  6925. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6926. return
  6927. }
  6928. } else {
  6929. if status == 2 {
  6930. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6931. if err != nil {
  6932. logs.Error(err)
  6933. tx.Rollback()
  6934. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6935. return
  6936. }
  6937. for _, item := range lpplandtl1List {
  6938. if item["fttype"].(int64) == 0 {
  6939. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6940. if err != nil {
  6941. logs.Error(err)
  6942. tx.Rollback()
  6943. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6944. return
  6945. }
  6946. } else {
  6947. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6948. if err != nil {
  6949. logs.Error(err)
  6950. tx.Rollback()
  6951. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6952. return
  6953. }
  6954. }
  6955. }
  6956. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6957. if err != nil {
  6958. logs.Error(err)
  6959. tx.Rollback()
  6960. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6961. return
  6962. }
  6963. } else {
  6964. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6965. if err != nil {
  6966. logs.Error(err)
  6967. tx.Rollback()
  6968. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6969. return
  6970. }
  6971. }
  6972. }
  6973. err := tx.Commit()
  6974. if err != nil {
  6975. logs.Error(err)
  6976. tx.Rollback()
  6977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6978. return
  6979. }
  6980. appG.Response(http.StatusOK, e.SUCCESS, true)
  6981. }
  6982. func Decimal(value float64) float64 {
  6983. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6984. return value
  6985. }
  6986. func UpdateDailyData(c *gin.Context) {
  6987. appG := app.Gin{C: c}
  6988. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6989. parammaps := gofasion.NewFasion(string(dataByte))
  6990. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6991. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6992. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6993. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6994. date := parammaps.Get("date").ValueStr()
  6995. tx := restful.Engine.NewSession()
  6996. defer tx.Close()
  6997. 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()
  6998. if err != nil {
  6999. logs.Error("UpdateDailyData-error-0:", err)
  7000. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7001. return
  7002. }
  7003. if count > 0 {
  7004. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7005. return
  7006. }
  7007. tx.Begin()
  7008. if location == 0 {
  7009. fid := parammaps.Get("fid").ValueStr()
  7010. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7011. if err != nil {
  7012. logs.Error("UpdateDailyData-error-1:", err)
  7013. tx.Rollback()
  7014. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7015. return
  7016. }
  7017. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7018. if err != nil {
  7019. logs.Error("UpdateDailyData-error-1:", err)
  7020. tx.Rollback()
  7021. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7022. return
  7023. }
  7024. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7025. if err != nil {
  7026. fmt.Println("Error:", err)
  7027. return
  7028. }
  7029. actualWeight := weight - num
  7030. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7031. if err != nil {
  7032. logs.Error("UpdateDailyData-error-2:", err)
  7033. tx.Rollback()
  7034. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7035. return
  7036. }
  7037. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7038. if err != nil {
  7039. logs.Error("UpdateDailyData-error-3:", err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7042. return
  7043. }
  7044. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7045. if err != nil {
  7046. logs.Error("UpdateDailyData-error-4:", err)
  7047. tx.Rollback()
  7048. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7049. return
  7050. }
  7051. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7052. if err != nil {
  7053. logs.Error("UpdateDailyData-error-5:", err)
  7054. tx.Rollback()
  7055. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7056. return
  7057. }
  7058. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7059. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7060. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7061. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7062. if err != nil {
  7063. fmt.Println("Error:", err)
  7064. return
  7065. }
  7066. // actual := actualWeight / float64(len(downloadedplanList))
  7067. for _, item := range downloadedplanList {
  7068. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7069. if err != nil {
  7070. fmt.Println("Error:", err)
  7071. return
  7072. }
  7073. actual := itemLweight / lweight * actualWeight
  7074. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7075. if err != nil {
  7076. logs.Error("UpdateDailyData-error-6:", err)
  7077. tx.Rollback()
  7078. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7079. return
  7080. }
  7081. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7082. if err != nil {
  7083. logs.Error("UpdateDailyData-error-7:", err)
  7084. tx.Rollback()
  7085. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7086. return
  7087. }
  7088. _, 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()
  7089. if err != nil {
  7090. logs.Error("UpdateDailyData-error-8:", err)
  7091. tx.Rollback()
  7092. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7093. return
  7094. }
  7095. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7096. if err != nil {
  7097. logs.Error("UpdateDailyData-error-9:", err)
  7098. tx.Rollback()
  7099. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7100. return
  7101. }
  7102. }
  7103. } else {
  7104. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7105. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7106. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7107. // if err != nil {
  7108. // fmt.Println("Error:", err)
  7109. // return
  7110. // }
  7111. for _, item := range downloadedplanList {
  7112. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7113. if err != nil {
  7114. logs.Error("UpdateDailyData-error-6:", err)
  7115. tx.Rollback()
  7116. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7117. return
  7118. }
  7119. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7120. item["lweight"], actualWeight, item["id"]).Execute()
  7121. if err != nil {
  7122. logs.Error("UpdateDailyData-error-7:", err)
  7123. tx.Rollback()
  7124. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7125. return
  7126. }
  7127. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7128. where pid = ?`, item["id"]).Execute()
  7129. if err != nil {
  7130. logs.Error("UpdateDailyData-error-8:", err)
  7131. tx.Rollback()
  7132. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7133. return
  7134. }
  7135. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7136. if err != nil {
  7137. logs.Error("UpdateDailyData-error-9:", err)
  7138. tx.Rollback()
  7139. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7140. return
  7141. }
  7142. }
  7143. }
  7144. } else {
  7145. fbarid := parammaps.Get("fbarid").ValueStr()
  7146. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7147. if err != nil {
  7148. logs.Error("UpdateDailyData-error-10:", err)
  7149. tx.Rollback()
  7150. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7151. return
  7152. }
  7153. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7154. if err != nil {
  7155. logs.Error("UpdateDailyData-error-1:", err)
  7156. tx.Rollback()
  7157. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7158. return
  7159. }
  7160. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7161. if err != nil {
  7162. fmt.Println("Error:", err)
  7163. return
  7164. }
  7165. actualWeight := weight - num
  7166. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7167. if err != nil {
  7168. logs.Error("UpdateDailyData-error-11:", err)
  7169. tx.Rollback()
  7170. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7171. return
  7172. }
  7173. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7174. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7175. if err != nil {
  7176. logs.Error("UpdateDailyData-error-12:", err)
  7177. tx.Rollback()
  7178. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7179. return
  7180. }
  7181. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7182. where pid = ? `, pid).Execute()
  7183. if err != nil {
  7184. logs.Error("UpdateDailyData-error-13:", err)
  7185. tx.Rollback()
  7186. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7187. return
  7188. }
  7189. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7190. if err != nil {
  7191. logs.Error("UpdateDailyData-error-14:", err)
  7192. tx.Rollback()
  7193. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7194. return
  7195. }
  7196. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7197. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7198. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7199. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7200. if err != nil {
  7201. fmt.Println("Error:", err)
  7202. return
  7203. }
  7204. for _, item := range downloadedplanList {
  7205. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7206. if err != nil {
  7207. fmt.Println("Error:", err)
  7208. return
  7209. }
  7210. actual := itemLweight / lweight * actualWeight
  7211. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7212. if err != nil {
  7213. logs.Error("UpdateDailyData-error-6:", err)
  7214. tx.Rollback()
  7215. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7216. return
  7217. }
  7218. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7219. if err != nil {
  7220. logs.Error("UpdateDailyData-error-7:", err)
  7221. tx.Rollback()
  7222. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7223. return
  7224. }
  7225. _, 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()
  7226. if err != nil {
  7227. logs.Error("UpdateDailyData-error-8:", err)
  7228. tx.Rollback()
  7229. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7230. return
  7231. }
  7232. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7233. if err != nil {
  7234. logs.Error("UpdateDailyData-error-9:", err)
  7235. tx.Rollback()
  7236. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7237. return
  7238. }
  7239. }
  7240. } else {
  7241. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7242. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7243. for _, item := range downloadedplanList {
  7244. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7245. // if err != nil {
  7246. // fmt.Println("Error:", err)
  7247. // return
  7248. // }
  7249. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7250. if err != nil {
  7251. logs.Error("UpdateDailyData-error-6:", err)
  7252. tx.Rollback()
  7253. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7254. return
  7255. }
  7256. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7257. item["lweight"], actualWeight, item["id"]).Execute()
  7258. if err != nil {
  7259. logs.Error("UpdateDailyData-error-7:", err)
  7260. tx.Rollback()
  7261. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7262. return
  7263. }
  7264. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7265. where pid = ?`, item["id"]).Execute()
  7266. if err != nil {
  7267. logs.Error("UpdateDailyData-error-8:", err)
  7268. tx.Rollback()
  7269. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7270. return
  7271. }
  7272. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7273. if err != nil {
  7274. logs.Error("UpdateDailyData-error-9:", err)
  7275. tx.Rollback()
  7276. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7277. return
  7278. }
  7279. }
  7280. }
  7281. }
  7282. err = tx.Commit()
  7283. if err != nil {
  7284. logs.Error("UpdateDailyData-error-20:", err)
  7285. tx.Rollback()
  7286. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7287. return
  7288. }
  7289. appG.Response(http.StatusOK, e.SUCCESS, true)
  7290. }
  7291. func GetFormulaStatistics(c *gin.Context) {
  7292. appG := app.Gin{C: c}
  7293. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7294. parammaps := gofasion.NewFasion(string(dataByte))
  7295. startTime := parammaps.Get("startTime").ValueStr()
  7296. endTime := parammaps.Get("endTime").ValueStr()
  7297. pastureId := parammaps.Get("pastureId").ValueStr()
  7298. tx := restful.Engine.NewSession()
  7299. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7300. if err != nil {
  7301. logs.Error("GetFormulaStatistics-error-1:", err)
  7302. tx.Rollback()
  7303. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7304. return
  7305. }
  7306. var feedtemplet, dateList []string
  7307. for _, f := range feedtempletList {
  7308. feedtemplet = append(feedtemplet, f["tname"].(string))
  7309. }
  7310. layout := "2006-01-02"
  7311. // s := "2023-05-01"
  7312. // e := "2023-05-23"
  7313. start, err := time.Parse(layout, startTime)
  7314. if err != nil {
  7315. fmt.Println(err)
  7316. return
  7317. }
  7318. end, err := time.Parse(layout, endTime)
  7319. if err != nil {
  7320. fmt.Println(err)
  7321. return
  7322. }
  7323. end = end.AddDate(0, 0, 1)
  7324. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7325. dateList = append(dateList, d.Format("2006-01-02"))
  7326. }
  7327. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7328. join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate join feedtemplet ftd on ftd.id = ft.id where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  7329. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7330. if err != nil {
  7331. logs.Error("GetFormulaStatistics-error-2:", err)
  7332. tx.Rollback()
  7333. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7334. return
  7335. }
  7336. var data2 [][]interface{}
  7337. for _, f := range feedtemplet {
  7338. var data1 []interface{}
  7339. for _, date := range dateList {
  7340. exist := false
  7341. for _, item := range downloadedplanList {
  7342. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7343. data1 = append(data1, item["total"])
  7344. exist = true
  7345. break
  7346. }
  7347. }
  7348. if !exist {
  7349. data1 = append(data1, 0)
  7350. }
  7351. }
  7352. data2 = append(data2, data1)
  7353. }
  7354. //前端让加的
  7355. feedtemplet = append(feedtemplet, "")
  7356. {
  7357. var data1 []interface{}
  7358. for _, f := range dateList {
  7359. // f = f + "\n"
  7360. fmt.Println(f)
  7361. data1 = append(data1, 0)
  7362. }
  7363. data2 = append(data2, data1)
  7364. }
  7365. resp := make(map[string]interface{}, 0)
  7366. resp["xdata"] = dateList
  7367. resp["data1"] = feedtemplet
  7368. resp["data2"] = data2
  7369. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7370. }
  7371. func GetPlanData(c *gin.Context) {
  7372. appG := app.Gin{C: c}
  7373. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7374. fsion := gofasion.NewFasion(string(dataByte))
  7375. sqlnamestr := fsion.Get("name").ValueStr()
  7376. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7377. offset := fsion.Get("offset").ValueDefaultInt(0)
  7378. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7379. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7380. month := fsion.Get("month").ValueDefaultStr("map")
  7381. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7382. tx := restful.Engine.NewSession()
  7383. err := tx.Begin()
  7384. defer func() {
  7385. switch {
  7386. case err != nil:
  7387. if tx != nil {
  7388. tx.Rollback()
  7389. }
  7390. default:
  7391. if tx != nil {
  7392. err = tx.Commit()
  7393. }
  7394. }
  7395. if tx != nil {
  7396. tx.Close()
  7397. }
  7398. }()
  7399. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7400. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7401. if sql != "" {
  7402. s_params := make([]interface{}, 0)
  7403. if fsion.HasKey("parammaps") {
  7404. parammaps := fsion.Get("parammaps")
  7405. paramslist := strings.Split(p, ",")
  7406. if len(paramslist) > 0 && p != "" {
  7407. for _, value := range paramslist {
  7408. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7409. if tempv, exists := c.Get("jwt_username"); exists {
  7410. s_params = append(s_params, tempv.(string))
  7411. } else {
  7412. s_params = append(s_params, "")
  7413. }
  7414. } else {
  7415. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7416. }
  7417. }
  7418. }
  7419. }
  7420. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7421. if err != nil {
  7422. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7423. } else {
  7424. paramslist1 := strings.Split(p1, ",")
  7425. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7426. s_params1 := make([]interface{}, 0)
  7427. if len(paramslist1) > 0 && p1 != "" {
  7428. for _, v := range paramslist1 {
  7429. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7430. }
  7431. }
  7432. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7433. for _, item := range arr {
  7434. trgaddressList := []string{}
  7435. if _, ok := item["trgaddress"]; ok {
  7436. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7437. for _, str := range trgaddressList1 {
  7438. if str != "" {
  7439. trgaddressList = append(trgaddressList, str)
  7440. }
  7441. }
  7442. }
  7443. item["trgaddressList"] = trgaddressList
  7444. }
  7445. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7446. }
  7447. // var wg sync.WaitGroup
  7448. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7449. // wg.Add(1)
  7450. // go func(value map[string]interface{}) {
  7451. // defer wg.Done()
  7452. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7453. // }(value)
  7454. // }
  7455. // wg.Wait()
  7456. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7457. }
  7458. } else {
  7459. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7460. }
  7461. }
  7462. func PostPlanData(c *gin.Context) {
  7463. appG := app.Gin{C: c}
  7464. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7465. fsion := gofasion.NewFasion(string(dataByte))
  7466. logging.Info("PostRJSBData err: ", string(dataByte))
  7467. s_params := make([]interface{}, 0)
  7468. tx := restful.Engine.NewSession()
  7469. err := tx.Begin()
  7470. defer func() {
  7471. switch {
  7472. case err != nil:
  7473. if tx != nil {
  7474. tx.Rollback()
  7475. }
  7476. default:
  7477. if tx != nil {
  7478. err = tx.Commit()
  7479. }
  7480. }
  7481. if tx != nil {
  7482. tx.Close()
  7483. }
  7484. }()
  7485. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7486. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7487. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7488. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7489. if !fsion.HasKey("parammaps") {
  7490. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7491. return
  7492. }
  7493. parammaps := fsion.Get("parammaps")
  7494. // paramslist := strings.Split(p, ",")
  7495. // if len(paramslist) > 0 && p != "" {
  7496. // for _, value := range paramslist {
  7497. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7498. // }
  7499. // }
  7500. // _, err = tx.SQL(sql, s_params...).Execute()
  7501. // if err != nil {
  7502. // logging.Error("PostRJSBData err: ", err)
  7503. // msg := geterrmsg(err.Error())
  7504. // appG.Response(http.StatusOK, e.ERROR, msg)
  7505. // return
  7506. // }
  7507. s_params = make([]interface{}, 0)
  7508. paramslist := strings.Split(p1, ",")
  7509. if len(paramslist) > 0 && p1 != "" {
  7510. for _, value := range paramslist {
  7511. // if value == "ID" {
  7512. // id := parammaps.Get("ID").ValueStr()
  7513. // pastureid := parammaps.Get("pastureid").ValueStr()
  7514. // 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
  7515. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7516. // if err != nil {
  7517. // logging.Error("PostRJSBData err: ", err)
  7518. // msg := geterrmsg(err.Error())
  7519. // appG.Response(http.StatusOK, e.ERROR, msg)
  7520. // return
  7521. // }
  7522. // for _, item := range datalist {
  7523. // id = item["id"]
  7524. // }
  7525. // s_params = append(s_params, id)
  7526. // } else {
  7527. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7528. // }
  7529. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7530. }
  7531. }
  7532. _, err = tx.SQL(sql1, s_params...).Execute()
  7533. if err != nil {
  7534. logging.Error("PostRJSBData1 err: ", err)
  7535. msg := geterrmsg(err.Error())
  7536. appG.Response(http.StatusOK, e.ERROR, msg)
  7537. return
  7538. }
  7539. s_params = make([]interface{}, 0)
  7540. paramslist = strings.Split(p2, ",")
  7541. if len(paramslist) > 0 && p2 != "" {
  7542. for _, value := range paramslist {
  7543. if value == "ID" {
  7544. id := parammaps.Get("ID").ValueStr()
  7545. pastureid := parammaps.Get("pastureid").ValueStr()
  7546. 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
  7547. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7548. if err != nil {
  7549. logging.Error("PostRJSBData err: ", err)
  7550. msg := geterrmsg(err.Error())
  7551. appG.Response(http.StatusOK, e.ERROR, msg)
  7552. return
  7553. }
  7554. for _, item := range datalist {
  7555. id = item["id"]
  7556. }
  7557. s_params = append(s_params, id)
  7558. } else {
  7559. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7560. }
  7561. }
  7562. }
  7563. _, err = tx.SQL(sql2, s_params...).Execute()
  7564. if err != nil {
  7565. logging.Error("PostRJSBData2 err: ", err)
  7566. msg := geterrmsg(err.Error())
  7567. appG.Response(http.StatusOK, e.ERROR, msg)
  7568. return
  7569. }
  7570. s_params = make([]interface{}, 0)
  7571. paramslist = strings.Split(p3, ",")
  7572. if len(paramslist) > 0 && p3 != "" {
  7573. for _, value := range paramslist {
  7574. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7575. }
  7576. }
  7577. _, err = tx.SQL(sql3, s_params...).Execute()
  7578. if err != nil {
  7579. logging.Error("PostRJSBData3 err: ", err)
  7580. msg := geterrmsg(err.Error())
  7581. appG.Response(http.StatusOK, e.ERROR, msg)
  7582. return
  7583. }
  7584. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7585. }
  7586. func CheckFeedTrgaddress(c *gin.Context) {
  7587. appG := app.Gin{C: c}
  7588. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7589. fsion := gofasion.NewFasion(string(dataByte))
  7590. fclassid := fsion.Get("fclassid").ValueStr()
  7591. feedId := fsion.Get("feedId").ValueStr()
  7592. backup1 := fsion.Get("backup1").ValueStr()
  7593. backup1List := strings.Split(backup1, ",")
  7594. tx := restful.Engine.NewSession()
  7595. defer tx.Close()
  7596. // if backup1 != "" {
  7597. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7598. for _, feed := range feedList {
  7599. if feed["backup1"] == "" {
  7600. continue
  7601. }
  7602. feedbackupList := strings.Split(feed["backup1"], ",")
  7603. for _, feedbackup := range feedbackupList {
  7604. for _, backup := range backup1List {
  7605. if feedbackup == backup {
  7606. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7607. return
  7608. }
  7609. }
  7610. }
  7611. }
  7612. // }
  7613. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7614. }
  7615. func ThiGetDataByName(c *gin.Context) {
  7616. appG := app.Gin{C: c}
  7617. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7618. fsion := gofasion.NewFasion(string(dataByte))
  7619. sqlnamestr := fsion.Get("name").ValueStr()
  7620. offset := fsion.Get("offset").ValueDefaultInt(0)
  7621. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7622. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7623. tx := restful.Engine.NewSession()
  7624. err := tx.Begin()
  7625. defer func() {
  7626. switch {
  7627. case err != nil:
  7628. logging.Error("tx.Begin 事务启动失败__error:", err)
  7629. if tx != nil {
  7630. tx.Rollback()
  7631. }
  7632. default:
  7633. if tx != nil {
  7634. err = tx.Commit()
  7635. }
  7636. }
  7637. if tx != nil {
  7638. tx.Close()
  7639. }
  7640. }()
  7641. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7642. if sql != "" {
  7643. s_params := make([]interface{}, 0)
  7644. if fsion.HasKey("parammaps") {
  7645. parammaps := fsion.Get("parammaps")
  7646. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7647. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7648. }
  7649. paramslist := strings.Split(p, ",")
  7650. if len(paramslist) > 0 && p != "" {
  7651. for _, value := range paramslist {
  7652. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7653. if tempv, exists := c.Get("jwt_username"); exists {
  7654. s_params = append(s_params, tempv.(string))
  7655. } else {
  7656. s_params = append(s_params, "")
  7657. }
  7658. } else {
  7659. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7660. }
  7661. }
  7662. }
  7663. } else if fsion.HasKey("params") {
  7664. params := fsion.Get("params").Array()
  7665. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7666. for _, v_params := range params {
  7667. s_params = append(s_params, v_params.ValueStr())
  7668. }
  7669. }
  7670. if returntype == "xlsx" {
  7671. var xlsxfile *xlsx.File
  7672. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7673. //c.File("c:/dd.xlsx")
  7674. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7675. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7676. c.Header("Content-Transfer-Encoding", "binary")
  7677. _ = xlsxfile.Write(c.Writer)
  7678. } else {
  7679. if sqlnamestr == "getHomepageStr" {
  7680. parammaps := fsion.Get("parammaps")
  7681. pastureid := parammaps.Get("pastureid").ValueStr()
  7682. var montimeList []float64
  7683. var montime float64
  7684. var wg sync.WaitGroup
  7685. now := time.Now()
  7686. for i := 0; i < 30; i++ {
  7687. wg.Add(1)
  7688. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7689. go func(nowstr string) {
  7690. defer wg.Done()
  7691. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7692. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7693. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7694. montimeList = append(montimeList, m)
  7695. }(nowstr)
  7696. }
  7697. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7698. if err != nil {
  7699. logging.Error("GetDataByName err: ", err)
  7700. msg := geterrmsg(err.Error())
  7701. appG.Response(http.StatusOK, e.ERROR, msg)
  7702. }
  7703. wg.Wait()
  7704. for _, m := range montimeList {
  7705. montime += m
  7706. }
  7707. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7708. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7709. return
  7710. }
  7711. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7712. if err != nil {
  7713. logging.Error("GetDataByName err: ", err)
  7714. msg := geterrmsg(err.Error())
  7715. appG.Response(http.StatusOK, e.ERROR, msg)
  7716. } else {
  7717. if sqlnamestr == "getFeedTrgaddressList" {
  7718. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7719. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7720. trgaddressList := []string{}
  7721. for _, str := range trgaddressList1 {
  7722. if str != "" {
  7723. trgaddressList = append(trgaddressList, str)
  7724. }
  7725. }
  7726. item["trgaddressList"] = trgaddressList
  7727. }
  7728. }
  7729. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7730. }
  7731. }
  7732. } else {
  7733. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7734. }
  7735. }
  7736. // func ToggleCcount(c *gin.Context) {
  7737. // appG := app.Gin{C: c}
  7738. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7739. // fsion := gofasion.NewFasion(string(dataByte))
  7740. // // 0 实际 1 软件
  7741. // status := fsion.Get("status").ValueDefaultInt64(0)
  7742. // pastureId := fsion.Get("pastureId").ValueStr()
  7743. // tx := restful.Engine.NewSession()
  7744. // err := tx.Begin()
  7745. // defer func() {
  7746. // switch {
  7747. // case err != nil:
  7748. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7749. // if tx != nil {
  7750. // tx.Rollback()
  7751. // }
  7752. // default:
  7753. // if tx != nil {
  7754. // err = tx.Commit()
  7755. // }
  7756. // }
  7757. // if tx != nil {
  7758. // tx.Close()
  7759. // }
  7760. // }()
  7761. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7762. // if err != nil {
  7763. // logs.Error(err)
  7764. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7765. // return
  7766. // }
  7767. // for _, bar := range barList {
  7768. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7769. // if err != nil {
  7770. // logs.Error(err)
  7771. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7772. // return
  7773. // }
  7774. // if !exist {
  7775. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7776. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7777. // if err != nil {
  7778. // logs.Error(err)
  7779. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7780. // return
  7781. // }
  7782. // }
  7783. // }
  7784. // if status == 0 {
  7785. // tx.Exec(`update feedp set ccount = actualcount `)
  7786. // }else{
  7787. // tx.Exec(`update feedp set ccount = softccount `)
  7788. // }
  7789. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7790. // if err != nil {
  7791. // logs.Error(err)
  7792. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7793. // return
  7794. // }
  7795. // for _, feedpData :=range feedpList{
  7796. // var feedpargs []interface{}
  7797. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7798. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7799. // if _, ok := feedpData["ftname"]; ok {
  7800. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7801. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7802. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7803. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7804. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7805. // } else {
  7806. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7807. // }
  7808. // if _, ok := feedpData["ptsfname"]; ok {
  7809. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7810. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7811. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7812. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7813. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7814. // } else {
  7815. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7816. // }
  7817. // upFeedpSql += " where barname = ? and pastureid = ? "
  7818. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7819. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7820. // if err != nil {
  7821. // logs.Error(err)
  7822. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7823. // return
  7824. // }
  7825. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7826. // if err != nil {
  7827. // logs.Error(err)
  7828. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7829. // return
  7830. // }
  7831. // if !exist1 {
  7832. // _, 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) `,
  7833. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7834. // if err != nil {
  7835. // logs.Error(err)
  7836. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7837. // return
  7838. // }
  7839. // }
  7840. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7841. // if err != nil {
  7842. // logs.Error(err)
  7843. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7844. // return
  7845. // }
  7846. // if !exist2 {
  7847. // _, 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) `,
  7848. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7849. // if err != nil {
  7850. // logs.Error(err)
  7851. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7852. // return
  7853. // }
  7854. // }
  7855. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7856. // if err != nil {
  7857. // logs.Error(err)
  7858. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7859. // return
  7860. // }
  7861. // if !exist3 {
  7862. // _, 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) `,
  7863. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7864. // if err != nil {
  7865. // logs.Error(err)
  7866. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7867. // return
  7868. // }
  7869. // }
  7870. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7871. // if err != nil {
  7872. // logs.Error(err)
  7873. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7874. // return
  7875. // }
  7876. // if !exist4 {
  7877. // _, 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) `,
  7878. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7879. // if err != nil {
  7880. // logs.Error(err)
  7881. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7882. // return
  7883. // }
  7884. // }
  7885. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7886. // if err != nil {
  7887. // logs.Error(err)
  7888. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7889. // return
  7890. // }
  7891. // if !exist5 {
  7892. // _, 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) `,
  7893. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7894. // if err != nil {
  7895. // logs.Error(err)
  7896. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7897. // return
  7898. // }
  7899. // }
  7900. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7901. // if err != nil {
  7902. // logs.Error(err)
  7903. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7904. // return
  7905. // }
  7906. // if !exist6 {
  7907. // _, 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) `,
  7908. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7909. // if err != nil {
  7910. // logs.Error(err)
  7911. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7912. // return
  7913. // }
  7914. // }
  7915. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7916. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7917. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7918. // and pastureid = ? and times = ?`
  7919. // var fpdargs1 []interface{}
  7920. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7921. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7922. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7923. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7924. // if err != nil {
  7925. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7926. // return
  7927. // }
  7928. // var fpdargs2 []interface{}
  7929. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7930. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7931. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7932. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7933. // if err != nil {
  7934. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7935. // return
  7936. // }
  7937. // var fpdargs3 []interface{}
  7938. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7939. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7940. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7941. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7942. // if err != nil {
  7943. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7944. // return
  7945. // }
  7946. // var fpdargs4 []interface{}
  7947. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7948. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7949. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7950. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7951. // if err != nil {
  7952. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7953. // return
  7954. // }
  7955. // var fpdargs5 []interface{}
  7956. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7957. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7958. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7959. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7960. // if err != nil {
  7961. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7962. // return
  7963. // }
  7964. // var fpdargs6 []interface{}
  7965. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7966. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7967. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7968. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7969. // if err != nil {
  7970. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7971. // return
  7972. // }
  7973. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7974. // 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()
  7975. // if err != nil {
  7976. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7977. // return
  7978. // }
  7979. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7980. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7981. // upFpdetailList := make([]*upFpdetail, 0)
  7982. // for _, newfpd := range newList {
  7983. // for _, oldfpd := range oldFpdList {
  7984. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7985. // var oldweight, newweight float64
  7986. // if oldfpd["weight"] != nil {
  7987. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7988. // }
  7989. // if newfpd["weight"] != nil {
  7990. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7991. // }
  7992. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7993. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7994. // Old: oldweight,
  7995. // New: newweight,
  7996. // Times: newfpd["times"].(int64),
  7997. // Ptid: newfpd["ptid"].(int64),
  7998. // Fweight: fweight,
  7999. // Id: oldfpd["id"].(int64),
  8000. // })
  8001. // break
  8002. // }
  8003. // }
  8004. // }
  8005. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8006. // }
  8007. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8008. // }
  8009. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8010. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8011. if err != nil {
  8012. return err
  8013. }
  8014. for _, item := range feedpList {
  8015. // if item["ftid"].(string) != data["ftid"].(string) {
  8016. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8017. if err != nil {
  8018. return err
  8019. }
  8020. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8021. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8022. if err != nil {
  8023. return err
  8024. }
  8025. // }
  8026. }
  8027. return nil
  8028. }
  8029. func PostPlanDatas(c *gin.Context) {
  8030. appG := app.Gin{C: c}
  8031. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8032. fsions := gofasion.NewFasion(string(dataByte))
  8033. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8034. tx := restful.Engine.NewSession()
  8035. err := tx.Begin()
  8036. defer func() {
  8037. switch {
  8038. case err != nil:
  8039. if tx != nil {
  8040. tx.Rollback()
  8041. }
  8042. default:
  8043. if tx != nil {
  8044. err = tx.Commit()
  8045. }
  8046. }
  8047. if tx != nil {
  8048. tx.Close()
  8049. }
  8050. }()
  8051. pastureId := fsions.Get("pastureid").ValueStr()
  8052. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8053. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8054. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8055. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8056. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8057. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8058. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8059. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8060. for _, parammaps := range fsions.Get("arrList").Array() {
  8061. fmt.Println(parammaps.Json())
  8062. if parammaps.Json() == "null" {
  8063. continue
  8064. }
  8065. // if !fsion.HasKey("arrList") {
  8066. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8067. // return
  8068. // continue
  8069. // }
  8070. // parammaps := fsion.Get("arrList")
  8071. s_params := make([]interface{}, 0)
  8072. // paramslist := strings.Split(p, ",")
  8073. // if len(paramslist) > 0 && p != "" {
  8074. // for _, value := range paramslist {
  8075. // if value == "pastureid" {
  8076. // s_params = append(s_params, pastureId)
  8077. // } else {
  8078. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8079. // }
  8080. // }
  8081. // }
  8082. // _, err = tx.SQL(sql, s_params...).Execute()
  8083. // if err != nil {
  8084. // logging.Error("PostRJSBData err: ", err)
  8085. // msg := geterrmsg(err.Error())
  8086. // appG.Response(http.StatusOK, e.ERROR, msg)
  8087. // return
  8088. // }
  8089. s_params = make([]interface{}, 0)
  8090. paramslist := strings.Split(p1, ",")
  8091. if len(paramslist) > 0 && p1 != "" {
  8092. for _, value := range paramslist {
  8093. // if value == "ID" {
  8094. // id := parammaps.Get("ID").ValueStr()
  8095. // pastureid := parammaps.Get("pastureid").ValueStr()
  8096. // 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
  8097. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8098. // if err != nil {
  8099. // logging.Error("PostRJSBData err: ", err)
  8100. // msg := geterrmsg(err.Error())
  8101. // appG.Response(http.StatusOK, e.ERROR, msg)
  8102. // return
  8103. // }
  8104. // for _, item := range datalist {
  8105. // id = item["id"]
  8106. // }
  8107. // s_params = append(s_params, id)
  8108. // } else {
  8109. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8110. // }
  8111. if value == "pastureid" {
  8112. s_params = append(s_params, pastureId)
  8113. } else {
  8114. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8115. }
  8116. }
  8117. }
  8118. _, err = tx.SQL(sql1, s_params...).Execute()
  8119. if err != nil {
  8120. logging.Error("PostRJSBData1 err: ", err)
  8121. msg := geterrmsg(err.Error())
  8122. appG.Response(http.StatusOK, e.ERROR, msg)
  8123. return
  8124. }
  8125. s_params = make([]interface{}, 0)
  8126. paramslist = strings.Split(p2, ",")
  8127. if len(paramslist) > 0 && p2 != "" {
  8128. for _, value := range paramslist {
  8129. if value == "ID" {
  8130. id := parammaps.Get("ID").ValueStr()
  8131. pastureid := parammaps.Get("pastureid").ValueStr()
  8132. 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
  8133. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8134. if err != nil {
  8135. logging.Error("PostRJSBData err: ", err)
  8136. msg := geterrmsg(err.Error())
  8137. appG.Response(http.StatusOK, e.ERROR, msg)
  8138. return
  8139. }
  8140. for _, item := range datalist {
  8141. id = item["id"]
  8142. }
  8143. s_params = append(s_params, id)
  8144. } else if value == "pastureid" {
  8145. s_params = append(s_params, pastureId)
  8146. } else {
  8147. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8148. }
  8149. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8150. }
  8151. }
  8152. _, err = tx.SQL(sql2, s_params...).Execute()
  8153. if err != nil {
  8154. logging.Error("PostRJSBData2 err: ", err)
  8155. msg := geterrmsg(err.Error())
  8156. appG.Response(http.StatusOK, e.ERROR, msg)
  8157. return
  8158. }
  8159. s_params = make([]interface{}, 0)
  8160. paramslist = strings.Split(p3, ",")
  8161. if len(paramslist) > 0 && p3 != "" {
  8162. for _, value := range paramslist {
  8163. if value == "pastureid" {
  8164. s_params = append(s_params, pastureId)
  8165. } else {
  8166. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8167. }
  8168. }
  8169. }
  8170. _, err = tx.SQL(sql3, s_params...).Execute()
  8171. if err != nil {
  8172. logging.Error("PostRJSBData3 err: ", err)
  8173. msg := geterrmsg(err.Error())
  8174. appG.Response(http.StatusOK, e.ERROR, msg)
  8175. return
  8176. }
  8177. }
  8178. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8179. }
  8180. func FpdBatchEdit(c *gin.Context) {
  8181. appG := app.Gin{C: c}
  8182. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8183. fsions := gofasion.NewFasion(string(dataByte))
  8184. barList := fsions.Get("barList").Array()
  8185. pastureid := fsions.Get("pastureId").ValueStr()
  8186. tx := restful.Engine.NewSession()
  8187. defer tx.Close()
  8188. 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
  8189. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8190. if err != nil {
  8191. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8192. return
  8193. }
  8194. for _, barFsions := range barList {
  8195. dataexcel := make(map[string]interface{}, 0)
  8196. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8197. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8198. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8199. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8200. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8201. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8202. continue
  8203. }
  8204. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8205. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8206. if err != nil {
  8207. logs.Error(err)
  8208. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8209. return
  8210. }
  8211. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8212. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8213. if err != nil {
  8214. logs.Error(err)
  8215. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8216. return
  8217. }
  8218. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8219. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8220. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8221. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8222. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8223. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8224. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8225. if err != nil {
  8226. logs.Error(err)
  8227. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8228. return
  8229. }
  8230. if !ftexist {
  8231. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8232. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8233. if err != nil {
  8234. logs.Error(err)
  8235. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8236. return
  8237. }
  8238. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8239. if err != nil {
  8240. logs.Error(err)
  8241. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8242. return
  8243. }
  8244. }
  8245. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8246. if err != nil {
  8247. logs.Error(err)
  8248. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8249. return
  8250. }
  8251. if !exist {
  8252. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8253. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8254. if err != nil {
  8255. logs.Error(err)
  8256. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8257. return
  8258. }
  8259. }
  8260. var feedpargs []interface{}
  8261. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8262. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8263. if _, ok := dataexcel["ftname"]; ok {
  8264. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8265. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8266. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8267. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8268. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8269. } else {
  8270. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8271. }
  8272. if _, ok := dataexcel["ptsfname"]; ok {
  8273. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8274. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8275. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8276. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8277. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8278. } else {
  8279. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8280. }
  8281. upFeedpSql += " where barname = ? and pastureid = ? "
  8282. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8283. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8284. if err != nil {
  8285. logs.Error(err)
  8286. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8287. return
  8288. }
  8289. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8290. if err != nil {
  8291. logs.Error(err)
  8292. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8293. return
  8294. }
  8295. if !exist1 {
  8296. _, 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) `,
  8297. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8298. if err != nil {
  8299. logs.Error(err)
  8300. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8301. return
  8302. }
  8303. }
  8304. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8305. if err != nil {
  8306. logs.Error(err)
  8307. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8308. return
  8309. }
  8310. if !exist2 {
  8311. _, 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) `,
  8312. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8313. if err != nil {
  8314. logs.Error(err)
  8315. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8316. return
  8317. }
  8318. }
  8319. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8320. if err != nil {
  8321. logs.Error(err)
  8322. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8323. return
  8324. }
  8325. if !exist3 {
  8326. _, 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) `,
  8327. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8328. if err != nil {
  8329. logs.Error(err)
  8330. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8331. return
  8332. }
  8333. }
  8334. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8335. if err != nil {
  8336. logs.Error(err)
  8337. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8338. return
  8339. }
  8340. if !exist4 {
  8341. _, 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) `,
  8342. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8343. if err != nil {
  8344. logs.Error(err)
  8345. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8346. return
  8347. }
  8348. }
  8349. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8350. if err != nil {
  8351. logs.Error(err)
  8352. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8353. return
  8354. }
  8355. if !exist5 {
  8356. _, 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) `,
  8357. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8358. if err != nil {
  8359. logs.Error(err)
  8360. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8361. return
  8362. }
  8363. }
  8364. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8365. if err != nil {
  8366. logs.Error(err)
  8367. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8368. return
  8369. }
  8370. if !exist6 {
  8371. _, 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) `,
  8372. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8373. if err != nil {
  8374. logs.Error(err)
  8375. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8376. return
  8377. }
  8378. }
  8379. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8380. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8381. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8382. and pastureid = ? and times = ?`
  8383. var fpdargs1 []interface{}
  8384. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8385. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8386. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8387. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8388. if err != nil {
  8389. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8390. return
  8391. }
  8392. var fpdargs2 []interface{}
  8393. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8394. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8395. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8396. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8397. if err != nil {
  8398. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8399. return
  8400. }
  8401. var fpdargs3 []interface{}
  8402. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8403. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8404. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8405. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8406. if err != nil {
  8407. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8408. return
  8409. }
  8410. var fpdargs4 []interface{}
  8411. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8412. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8413. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8414. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8415. if err != nil {
  8416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8417. return
  8418. }
  8419. var fpdargs5 []interface{}
  8420. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8421. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8422. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8423. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8424. if err != nil {
  8425. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8426. return
  8427. }
  8428. var fpdargs6 []interface{}
  8429. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8430. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8431. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8432. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8433. if err != nil {
  8434. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8435. return
  8436. }
  8437. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8438. 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()
  8439. if err != nil {
  8440. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8441. return
  8442. }
  8443. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8444. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8445. upFpdetailList := make([]*upFpdetail, 0)
  8446. for _, newfpd := range newList {
  8447. for _, oldfpd := range oldFpdList {
  8448. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8449. var oldweight, newweight float64
  8450. if oldfpd["weight"] != nil {
  8451. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8452. }
  8453. if newfpd["weight"] != nil {
  8454. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8455. }
  8456. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8457. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8458. Old: oldweight,
  8459. New: newweight,
  8460. Times: newfpd["times"].(int64),
  8461. Ptid: newfpd["ptid"].(int64),
  8462. Fweight: fweight,
  8463. Id: oldfpd["id"].(int64),
  8464. })
  8465. break
  8466. }
  8467. }
  8468. }
  8469. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8470. }
  8471. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8472. }
  8473. func UdBarSync(c *gin.Context) {
  8474. appG := app.Gin{C: c}
  8475. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8476. fsions := gofasion.NewFasion(string(dataByte))
  8477. pastureid := fsions.Get("pastureId").ValueStr()
  8478. tx := restful.Engine.NewSession()
  8479. defer tx.Close()
  8480. pastureinfo := new(udPastureInfo)
  8481. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8482. if err != nil {
  8483. logs.Error(err)
  8484. return
  8485. }
  8486. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8487. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8488. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8489. }
  8490. func UdFeedSync(c *gin.Context) {
  8491. appG := app.Gin{C: c}
  8492. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8493. fsions := gofasion.NewFasion(string(dataByte))
  8494. pastureid := fsions.Get("pastureId").ValueStr()
  8495. tx := restful.Engine.NewSession()
  8496. defer tx.Close()
  8497. pastureinfo := new(udPastureInfo)
  8498. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8499. if err != nil {
  8500. logs.Error(err)
  8501. return
  8502. }
  8503. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8504. // jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8505. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8506. }
  8507. func UdFeedtempletPush(c *gin.Context) {
  8508. appG := app.Gin{C: c}
  8509. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8510. fsions := gofasion.NewFasion(string(dataByte))
  8511. pastureid := fsions.Get("pastureId").ValueStr()
  8512. date := fsions.Get("date").ValueStr()
  8513. tx := restful.Engine.NewSession()
  8514. defer tx.Close()
  8515. pastureinfo := new(udPastureInfo)
  8516. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8517. if err != nil {
  8518. logs.Error(err)
  8519. return
  8520. }
  8521. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8522. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8523. }
  8524. func UdUtirPush(c *gin.Context) {
  8525. appG := app.Gin{C: c}
  8526. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8527. fsions := gofasion.NewFasion(string(dataByte))
  8528. pastureid := fsions.Get("pastureId").ValueStr()
  8529. date := fsions.Get("date").ValueStr()
  8530. tx := restful.Engine.NewSession()
  8531. defer tx.Close()
  8532. pastureinfo := new(udPastureInfo)
  8533. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8534. if err != nil {
  8535. logs.Error(err)
  8536. return
  8537. }
  8538. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8539. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8540. }
  8541. func UdBarFeedRemainPush(c *gin.Context) {
  8542. appG := app.Gin{C: c}
  8543. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8544. fsions := gofasion.NewFasion(string(dataByte))
  8545. pastureid := fsions.Get("pastureId").ValueStr()
  8546. date := fsions.Get("date").ValueStr()
  8547. tx := restful.Engine.NewSession()
  8548. defer tx.Close()
  8549. pastureinfo := new(udPastureInfo)
  8550. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8551. if err != nil {
  8552. logs.Error(err)
  8553. return
  8554. }
  8555. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8556. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8557. }
  8558. func UdMaterialIssuePush(c *gin.Context) {
  8559. appG := app.Gin{C: c}
  8560. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8561. fsions := gofasion.NewFasion(string(dataByte))
  8562. pastureid := fsions.Get("pastureId").ValueStr()
  8563. date := fsions.Get("date").ValueStr()
  8564. tx := restful.Engine.NewSession()
  8565. defer tx.Close()
  8566. pastureinfo := new(udPastureInfo)
  8567. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8568. if err != nil {
  8569. logs.Error(err)
  8570. return
  8571. }
  8572. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8573. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8574. }
  8575. func DelFeedTemplet(c *gin.Context) {
  8576. appG := app.Gin{C: c}
  8577. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8578. fsions := gofasion.NewFasion(string(dataByte))
  8579. ftId := fsions.Get("ftId").ValueStr()
  8580. // userId := fsions.Get("userId").ValueStr()
  8581. tx := restful.Engine.NewSession()
  8582. defer tx.Close()
  8583. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8584. if err != nil {
  8585. logs.Error(err)
  8586. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8587. return
  8588. }
  8589. /*
  8590. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8591. if err != nil {
  8592. logs.Error(err)
  8593. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8594. return
  8595. }
  8596. */
  8597. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8598. if err != nil {
  8599. logs.Error(err)
  8600. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8601. return
  8602. }
  8603. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8604. if err != nil {
  8605. logs.Error(err)
  8606. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8607. return
  8608. }
  8609. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8610. if count > 0 {
  8611. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8612. if err != nil {
  8613. logs.Error(err)
  8614. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8615. return
  8616. }
  8617. }
  8618. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8619. if err != nil {
  8620. logs.Error(err)
  8621. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8622. return
  8623. }
  8624. // var barIdStr []string
  8625. // for _, bar := range barIdList {
  8626. // barIdStr = append(barIdStr, bar["barid"])
  8627. // }
  8628. // if len(barIdStr) > 0 {
  8629. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8630. // if err != nil {
  8631. // logs.Error(err)
  8632. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8633. // return
  8634. // }
  8635. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8636. // if err != nil {
  8637. // logs.Error(err)
  8638. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8639. // return
  8640. // }
  8641. // now := time.Now()
  8642. // for _, newFpd := range newFpdDataList {
  8643. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8644. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8645. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8646. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8647. // if err != nil {
  8648. // logs.Error(err)
  8649. // appG.Response(http.StatusOK, e.ERROR, false)
  8650. // return
  8651. // }
  8652. // }
  8653. // for _, newFeedp := range newFeedpList {
  8654. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8655. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8656. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8657. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8658. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8659. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8660. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8661. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8662. // if err != nil {
  8663. // logs.Error(err)
  8664. // appG.Response(http.StatusOK, e.ERROR, false)
  8665. // return
  8666. // }
  8667. // }
  8668. // }
  8669. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8670. }
  8671. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8672. data := fasion["parammaps"].(map[string]interface{})
  8673. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8674. fmt.Println(err)
  8675. plancount1, err := tx.SQL(`SELECT
  8676. count( 1 )
  8677. FROM
  8678. (
  8679. SELECT
  8680. d.id
  8681. FROM
  8682. downloadedplan d
  8683. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8684. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8685. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8686. WHERE
  8687. d.mydate = ?
  8688. AND d.havebutton = 0
  8689. AND lpplantype IN ( 0, 1, 2 )
  8690. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8691. ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 and dd2.fname = d2.fname )
  8692. GROUP BY
  8693. d.id
  8694. ) d
  8695. `,
  8696. data["startTime"]).Count()
  8697. fmt.Println(err)
  8698. if plancount != plancount1 && number < 10 {
  8699. number++
  8700. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8701. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8702. }
  8703. }
  8704. func EditPlanSort(c *gin.Context) {
  8705. appG := app.Gin{C: c}
  8706. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8707. fsions := gofasion.NewFasion(string(dataByte))
  8708. planIdStr := fsions.Get("planId").ValueStr()
  8709. mydate := fsions.Get("mydate").ValueStr()
  8710. sort := fsions.Get("sort").ValueStr()
  8711. tx := restful.Engine.NewSession()
  8712. defer tx.Close()
  8713. tx.Begin()
  8714. type downloadedplan struct {
  8715. Id int64 `xorm:"id"`
  8716. Sort int `xorm:"sort"`
  8717. Pid int64 `xorm:"pid"`
  8718. }
  8719. planInfo := new(downloadedplan)
  8720. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8721. if err != nil {
  8722. logs.Error(err)
  8723. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8724. tx.Rollback()
  8725. return
  8726. }
  8727. sort1, _ := strconv.Atoi(sort)
  8728. if sort1 == planInfo.Sort {
  8729. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8730. tx.Rollback()
  8731. return
  8732. }
  8733. 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()
  8734. if err != nil {
  8735. logs.Error(err)
  8736. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8737. tx.Rollback()
  8738. return
  8739. }
  8740. if count1 == 0 {
  8741. tx.Rollback()
  8742. logs.Error(err)
  8743. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8744. return
  8745. }
  8746. 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()
  8747. if err != nil {
  8748. logs.Error(err)
  8749. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8750. tx.Rollback()
  8751. return
  8752. }
  8753. if count > 0 {
  8754. tx.Rollback()
  8755. logs.Error(err)
  8756. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8757. return
  8758. }
  8759. if planInfo.Sort > sort1 {
  8760. 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()
  8761. if err != nil {
  8762. logs.Error(err)
  8763. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8764. tx.Rollback()
  8765. return
  8766. }
  8767. var minSort, pidCount int
  8768. for _, sort := range minSortList {
  8769. minSort, _ = strconv.Atoi(sort["sort"])
  8770. }
  8771. planList := make([]*downloadedplan, 0)
  8772. 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)
  8773. if err != nil {
  8774. logs.Error(err)
  8775. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8776. tx.Rollback()
  8777. return
  8778. }
  8779. planPid := planInfo.Pid
  8780. planList1 := make([]*downloadedplan, 0)
  8781. planList2 := make([]*downloadedplan, 0)
  8782. for _, plan := range planList {
  8783. if plan.Pid == planPid {
  8784. pidCount++
  8785. planList1 = append(planList1, plan)
  8786. } else {
  8787. planList2 = append(planList2, plan)
  8788. }
  8789. }
  8790. planList1 = append(planList1, planList2...)
  8791. for i, plan := range planList1 {
  8792. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8793. if err != nil {
  8794. logs.Error(err)
  8795. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8796. tx.Rollback()
  8797. return
  8798. }
  8799. }
  8800. } else {
  8801. 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()
  8802. if err != nil {
  8803. logs.Error(err)
  8804. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8805. tx.Rollback()
  8806. return
  8807. }
  8808. var maxSort int
  8809. for _, sort := range maxSortList {
  8810. maxSort, _ = strconv.Atoi(sort["sort"])
  8811. }
  8812. planList := make([]*downloadedplan, 0)
  8813. 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)
  8814. if err != nil {
  8815. logs.Error(err)
  8816. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8817. tx.Rollback()
  8818. return
  8819. }
  8820. planPid := planInfo.Pid
  8821. planList1 := make([]*downloadedplan, 0)
  8822. planList2 := make([]*downloadedplan, 0)
  8823. for _, plan := range planList {
  8824. if plan.Pid == planPid {
  8825. // pidCount++
  8826. planList1 = append(planList1, plan)
  8827. } else {
  8828. planList2 = append(planList2, plan)
  8829. }
  8830. }
  8831. planList2 = append(planList2, planList1...)
  8832. for i, plan := range planList2 {
  8833. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  8834. if err != nil {
  8835. logs.Error(err)
  8836. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8837. tx.Rollback()
  8838. return
  8839. }
  8840. }
  8841. }
  8842. err = tx.Commit()
  8843. if err != nil {
  8844. logs.Error(err)
  8845. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8846. tx.Rollback()
  8847. return
  8848. }
  8849. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8850. }
  8851. func EditDownloadedplanArtificial(c *gin.Context) {
  8852. appG := app.Gin{C: c}
  8853. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8854. fsions := gofasion.NewFasion(string(dataByte))
  8855. planIdStr := fsions.Get("planId").ValueStr()
  8856. tx := restful.Engine.NewSession()
  8857. defer tx.Close()
  8858. tx.Begin()
  8859. planIdList := strings.Split(planIdStr, ",")
  8860. for _, planId := range planIdList {
  8861. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8862. if err != nil {
  8863. logs.Error(err)
  8864. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8865. tx.Rollback()
  8866. return
  8867. }
  8868. }
  8869. err := tx.Commit()
  8870. if err != nil {
  8871. logs.Error(err)
  8872. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8873. tx.Rollback()
  8874. return
  8875. }
  8876. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8877. }
  8878. type PlanRFID struct {
  8879. RFID string `json:"RFID"`
  8880. Lweight string `json:"lweight"`
  8881. Gear string `json:"gear"`
  8882. Speed string `json:"speed"`
  8883. }
  8884. func GetPlanRFID(c *gin.Context) {
  8885. appG := app.Gin{C: c}
  8886. RFIDStr := c.Query("RFID")
  8887. planRFIDList := make([]*PlanRFID, 0)
  8888. planRFIDList = append(planRFIDList, &PlanRFID{
  8889. RFID: RFIDStr,
  8890. Lweight: "1411.1",
  8891. Gear: "1",
  8892. Speed: "10",
  8893. })
  8894. planRFIDList = append(planRFIDList, &PlanRFID{
  8895. RFID: RFIDStr,
  8896. Lweight: "1322.1",
  8897. Gear: "1",
  8898. Speed: "10",
  8899. })
  8900. planRFIDList = append(planRFIDList, &PlanRFID{
  8901. RFID: RFIDStr,
  8902. Lweight: "1904.1",
  8903. Gear: "1",
  8904. Speed: "10",
  8905. })
  8906. planRFIDList = append(planRFIDList, &PlanRFID{
  8907. RFID: RFIDStr,
  8908. Lweight: "1870.1",
  8909. Gear: "1",
  8910. Speed: "10",
  8911. })
  8912. planRFIDList = append(planRFIDList, &PlanRFID{
  8913. RFID: RFIDStr,
  8914. Lweight: "2041.1",
  8915. Gear: "1",
  8916. Speed: "10",
  8917. })
  8918. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8919. }
  8920. type tmrEquipmentMuster struct {
  8921. A string
  8922. N string
  8923. }
  8924. func GetTmrEquipmentMuster(c *gin.Context) {
  8925. appG := app.Gin{C: c}
  8926. id := c.Query("id")
  8927. tx := restful.Engine.NewSession()
  8928. defer tx.Close()
  8929. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8930. if err != nil {
  8931. logs.Error(err)
  8932. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8933. return
  8934. }
  8935. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  8936. for _, data := range dataList {
  8937. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  8938. for _, g := range tmrEquipmentMusterList {
  8939. a, _ := strconv.ParseFloat(g.A, 64)
  8940. n, _ := strconv.ParseFloat(g.N, 64)
  8941. a1, n1 := ddmmtoddd(a, n)
  8942. g.A = fmt.Sprintf("%f", n1)
  8943. g.N = fmt.Sprintf("%f", a1)
  8944. }
  8945. }
  8946. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  8947. }
  8948. func ddmmtoddd(lng, lat float64) (float64, float64) {
  8949. lngDegree := fmt.Sprintf("%f", lng/100)
  8950. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  8951. lngDegreeInt := int(lngDegreefloat * 1000000)
  8952. dd := lngDegreeInt / 100 * 100 / 60
  8953. fmt.Println(dd)
  8954. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  8955. latDegree := fmt.Sprintf("%f", lat/100)
  8956. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  8957. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  8958. latDegreeInt := int(latDegreefloat * 1000000)
  8959. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  8960. a, _ := strconv.ParseFloat(lngStr, 64)
  8961. b, _ := strconv.ParseFloat(latStr, 64)
  8962. return coordtransform.WGS84toGCJ02(b, a)
  8963. }
  8964. func EditDownloadedplanExecWeight(c *gin.Context) {
  8965. appG := app.Gin{C: c}
  8966. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8967. fsions := gofasion.NewFasion(string(dataByte))
  8968. pid := fsions.Get("pid").ValueStr()
  8969. sort := fsions.Get("sort").ValueStr()
  8970. weight := fsions.Get("weight").ValueStr()
  8971. userId := fsions.Get("userId").ValueStr()
  8972. tx := restful.Engine.NewSession()
  8973. defer tx.Close()
  8974. tx.Begin()
  8975. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  8976. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  8977. pid, sort, pid, sort, weight, userId)
  8978. if err != nil {
  8979. logs.Error(err)
  8980. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8981. tx.Rollback()
  8982. return
  8983. }
  8984. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  8985. if err != nil {
  8986. logs.Error(err)
  8987. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8988. tx.Rollback()
  8989. return
  8990. }
  8991. _, err = tx.Exec(` update downloadplandtl1 set actualweightminus = lweight / (select sum(lweight) from downloadplandtl1 where pid = ? and sort = ? ) * ? where pid = ? and sort = ? `, pid, sort, weight, pid, sort)
  8992. if err != nil {
  8993. logs.Error(err)
  8994. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8995. tx.Rollback()
  8996. return
  8997. }
  8998. err = tx.Commit()
  8999. if err != nil {
  9000. logs.Error(err)
  9001. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9002. tx.Rollback()
  9003. return
  9004. }
  9005. appG.Response(http.StatusOK, e.SUCCESS, true)
  9006. }
  9007. func EditDownloadplandtl2Weight(c *gin.Context) {
  9008. appG := app.Gin{C: c}
  9009. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9010. fsions := gofasion.NewFasion(string(dataByte))
  9011. pid := fsions.Get("pid").ValueStr()
  9012. sort := fsions.Get("sort").ValueStr()
  9013. weight := fsions.Get("weight").ValueStr()
  9014. userId := fsions.Get("userId").ValueStr()
  9015. tx := restful.Engine.NewSession()
  9016. defer tx.Close()
  9017. tx.Begin()
  9018. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9019. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9020. pid, sort, pid, sort, weight, userId)
  9021. if err != nil {
  9022. logs.Error(err)
  9023. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9024. tx.Rollback()
  9025. return
  9026. }
  9027. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9028. if err != nil {
  9029. logs.Error(err)
  9030. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9031. tx.Rollback()
  9032. return
  9033. }
  9034. err = tx.Commit()
  9035. if err != nil {
  9036. logs.Error(err)
  9037. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9038. tx.Rollback()
  9039. return
  9040. }
  9041. appG.Response(http.StatusOK, e.SUCCESS, true)
  9042. }
  9043. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9044. params := fasion.Get("parammaps")
  9045. surplus := params.Get("surplus").ValueStr()
  9046. surplusId := params.Get("surplusId").ValueStr()
  9047. tx := restful.Engine.NewSession()
  9048. defer tx.Close()
  9049. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9050. if surplusId != "0" {
  9051. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9052. if err != nil {
  9053. log.Println("PostDataByName-error-1: ", err)
  9054. return errors.New("配方修改失败!")
  9055. }
  9056. type ftdetail struct {
  9057. Id string
  9058. Fname string
  9059. Sort int64
  9060. }
  9061. ftList := make([]*ftdetail, 0)
  9062. for _, data := range dataList {
  9063. ft := new(ftdetail)
  9064. ft.Fname = data["fname"]
  9065. ft.Id = data["id"]
  9066. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9067. if err != nil {
  9068. log.Println("PostDataByName-error-2: ", err)
  9069. return err
  9070. }
  9071. ft.Sort = sort
  9072. ftList = append(ftList, ft)
  9073. }
  9074. if surplus == "日粮" {
  9075. for _, ft := range ftList {
  9076. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9077. }
  9078. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9079. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9080. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9081. fmt.Println(err)
  9082. } else {
  9083. var sort int64
  9084. for _, ft := range ftList {
  9085. if ft.Fname == surplus {
  9086. sort = ft.Sort
  9087. break
  9088. }
  9089. }
  9090. if sort == 0 {
  9091. for _, ft := range ftList {
  9092. ft.Sort = ft.Sort + 1
  9093. }
  9094. } else {
  9095. for _, ft := range ftList {
  9096. if ft.Sort >= sort {
  9097. ft.Sort = ft.Sort + 1
  9098. }
  9099. }
  9100. }
  9101. for _, ft := range ftList {
  9102. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9103. }
  9104. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9105. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9106. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9107. if err != nil {
  9108. log.Println("PostDataByName-error-1: ", err)
  9109. fmt.Println(err)
  9110. return errors.New("配方修改失败!")
  9111. }
  9112. }
  9113. }
  9114. return nil
  9115. }
  9116. func FeedSurplus(fasion *gofasion.Fasion) {
  9117. tx := restful.Engine.NewSession()
  9118. defer tx.Close()
  9119. params := fasion.Get("parammaps")
  9120. feedId := params.Get("id").ValueStr()
  9121. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9122. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9123. }
  9124. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9125. // params := fasion.Get("parammaps")
  9126. // surplus := params.Get("surplus").ValueStr()
  9127. // surplusId := params.Get("surplusId").ValueStr()
  9128. tx := restful.Engine.NewSession()
  9129. defer tx.Close()
  9130. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9131. if surplusId != "0" {
  9132. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9133. if err != nil {
  9134. log.Println("PostDataByName-error-1: ", err)
  9135. return errors.New("配方修改失败!")
  9136. }
  9137. type ftdetail struct {
  9138. Id string
  9139. Fname string
  9140. Sort int64
  9141. }
  9142. ftList := make([]*ftdetail, 0)
  9143. for _, data := range dataList {
  9144. ft := new(ftdetail)
  9145. ft.Fname = data["fname"]
  9146. ft.Id = data["id"]
  9147. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9148. if err != nil {
  9149. log.Println("PostDataByName-error-2: ", err)
  9150. return err
  9151. }
  9152. ft.Sort = sort
  9153. ftList = append(ftList, ft)
  9154. }
  9155. if surplus == "日粮" {
  9156. for _, ft := range ftList {
  9157. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9158. }
  9159. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9160. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9161. pastureId, id, surplusId, surplusId, surplusId)
  9162. fmt.Println(err)
  9163. } else {
  9164. var sort int64
  9165. for _, ft := range ftList {
  9166. if ft.Fname == surplus {
  9167. sort = ft.Sort
  9168. break
  9169. }
  9170. }
  9171. if sort == 0 {
  9172. for _, ft := range ftList {
  9173. ft.Sort = ft.Sort + 1
  9174. }
  9175. } else {
  9176. for _, ft := range ftList {
  9177. if ft.Sort >= sort {
  9178. ft.Sort = ft.Sort + 1
  9179. }
  9180. }
  9181. }
  9182. for _, ft := range ftList {
  9183. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9184. }
  9185. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9186. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9187. id, surplusId, surplusId, sort, surplusId, pastureId)
  9188. if err != nil {
  9189. log.Println("PostDataByName-error-1: ", err)
  9190. fmt.Println(err)
  9191. return errors.New("配方修改失败!")
  9192. }
  9193. }
  9194. }
  9195. return nil
  9196. }
  9197. func GetLanguageStatus() string {
  9198. tx := restful.Engine.NewSession()
  9199. defer tx.Close()
  9200. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9201. if err != nil {
  9202. log.Println(err)
  9203. return "0"
  9204. }
  9205. return dataList[0]["inforvalue"]
  9206. }
  9207. func EditLanguage(c *gin.Context) {
  9208. appG := app.Gin{C: c}
  9209. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9210. fsions := gofasion.NewFasion(string(dataByte))
  9211. language := fsions.Get("language").ValueStr()
  9212. tx := restful.Engine.NewSession()
  9213. defer tx.Close()
  9214. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9215. if err != nil {
  9216. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9217. return
  9218. }
  9219. if language == "0" {
  9220. _, err := tx.Exec(`delete from dictlist `)
  9221. if err != nil {
  9222. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9223. return
  9224. }
  9225. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9226. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9227. if err != nil {
  9228. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9229. return
  9230. }
  9231. } else {
  9232. _, err := tx.Exec(`delete from dictlist `)
  9233. if err != nil {
  9234. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9235. return
  9236. }
  9237. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9238. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9239. if err != nil {
  9240. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9241. return
  9242. }
  9243. }
  9244. appG.Response(http.StatusOK, e.SUCCESS, true)
  9245. }
  9246. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9247. tx := restful.Engine.NewSession()
  9248. defer tx.Close()
  9249. oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,ifnull(fpd.weight,0)weight ,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9250. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9251. if err != nil {
  9252. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9253. return
  9254. }
  9255. for _, dataexcel := range barList {
  9256. // dataexcel := make(map[string]interface{}, 0)
  9257. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9258. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9259. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9260. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9261. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9262. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9263. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9264. // if err != nil {
  9265. // logs.Error(err)
  9266. // return
  9267. // }
  9268. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9269. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9270. // if err != nil {
  9271. // logs.Error(err)
  9272. // return
  9273. // }
  9274. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9275. continue
  9276. }
  9277. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9278. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9279. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9280. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9281. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9282. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9283. // /*
  9284. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9285. if err != nil {
  9286. logs.Error(err)
  9287. return
  9288. }
  9289. if !ftexist {
  9290. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9291. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9292. if err != nil {
  9293. logs.Error(err)
  9294. return
  9295. }
  9296. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9297. if err != nil {
  9298. logs.Error(err)
  9299. return
  9300. }
  9301. }
  9302. // */
  9303. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9304. if err != nil {
  9305. logs.Error(err)
  9306. return
  9307. }
  9308. if !exist {
  9309. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9310. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9311. if err != nil {
  9312. logs.Error(err)
  9313. return
  9314. }
  9315. }
  9316. var feedpargs []interface{}
  9317. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9318. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9319. if _, ok := dataexcel["ftname"]; ok {
  9320. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9321. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9322. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9323. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9324. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9325. } else {
  9326. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9327. }
  9328. if _, ok := dataexcel["ptsfname"]; ok {
  9329. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9330. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9331. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9332. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9333. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9334. } else {
  9335. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9336. }
  9337. upFeedpSql += " where barname = ? and pastureid = ? "
  9338. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9339. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9340. if err != nil {
  9341. logs.Error(err)
  9342. return
  9343. }
  9344. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9345. if err != nil {
  9346. logs.Error(err)
  9347. return
  9348. }
  9349. if !exist1 {
  9350. _, 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) `,
  9351. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9352. if err != nil {
  9353. logs.Error(err)
  9354. return
  9355. }
  9356. }
  9357. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9358. if err != nil {
  9359. logs.Error(err)
  9360. return
  9361. }
  9362. if !exist2 {
  9363. _, 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) `,
  9364. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9365. if err != nil {
  9366. logs.Error(err)
  9367. return
  9368. }
  9369. }
  9370. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9371. if err != nil {
  9372. logs.Error(err)
  9373. return
  9374. }
  9375. if !exist3 {
  9376. _, 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) `,
  9377. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9378. if err != nil {
  9379. logs.Error(err)
  9380. return
  9381. }
  9382. }
  9383. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9384. if err != nil {
  9385. logs.Error(err)
  9386. return
  9387. }
  9388. if !exist4 {
  9389. _, 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) `,
  9390. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9391. if err != nil {
  9392. logs.Error(err)
  9393. return
  9394. }
  9395. }
  9396. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9397. if err != nil {
  9398. logs.Error(err)
  9399. return
  9400. }
  9401. if !exist5 {
  9402. _, 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) `,
  9403. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9404. if err != nil {
  9405. logs.Error(err)
  9406. return
  9407. }
  9408. }
  9409. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9410. if err != nil {
  9411. logs.Error(err)
  9412. return
  9413. }
  9414. if !exist6 {
  9415. _, 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) `,
  9416. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9417. if err != nil {
  9418. logs.Error(err)
  9419. return
  9420. }
  9421. }
  9422. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9423. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9424. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9425. and pastureid = ? and times = ?`
  9426. var fpdargs1 []interface{}
  9427. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9428. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9429. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9430. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9431. if err != nil {
  9432. fmt.Println(err)
  9433. return
  9434. }
  9435. var fpdargs2 []interface{}
  9436. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9437. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9438. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9439. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9440. if err != nil {
  9441. fmt.Println(err)
  9442. return
  9443. }
  9444. var fpdargs3 []interface{}
  9445. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9446. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9447. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9448. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9449. if err != nil {
  9450. fmt.Println(err)
  9451. return
  9452. }
  9453. var fpdargs4 []interface{}
  9454. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9455. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9456. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9457. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9458. if err != nil {
  9459. fmt.Println(err)
  9460. return
  9461. }
  9462. var fpdargs5 []interface{}
  9463. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9464. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9465. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9466. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9467. if err != nil {
  9468. fmt.Println(err)
  9469. return
  9470. }
  9471. var fpdargs6 []interface{}
  9472. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9473. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9474. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9475. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9476. if err != nil {
  9477. fmt.Println(err)
  9478. return
  9479. }
  9480. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9481. newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,ifnull(weight,0)weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  9482. if err != nil {
  9483. return
  9484. }
  9485. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9486. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9487. upFpdetailList := make([]*upFpdetail, 0)
  9488. for _, newfpd := range newList {
  9489. for _, oldfpd := range oldFpdList {
  9490. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9491. var oldweight, newweight float64
  9492. if oldfpd["weight"] != nil {
  9493. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9494. }
  9495. if newfpd["weight"] != nil {
  9496. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9497. }
  9498. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9499. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9500. Old: oldweight,
  9501. New: newweight,
  9502. Times: newfpd["times"].(int64),
  9503. Ptid: newfpd["ptid"].(int64),
  9504. Fweight: fweight,
  9505. Id: oldfpd["id"].(int64),
  9506. })
  9507. break
  9508. }
  9509. }
  9510. }
  9511. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9512. }
  9513. }
  9514. func AddXxwFtdetail(c *gin.Context) {
  9515. appG := app.Gin{C: c}
  9516. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  9517. c.Bind(&xxwFtdetailList)
  9518. tx := restful.Engine.NewSession()
  9519. defer tx.Close()
  9520. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  9521. if err != nil {
  9522. logs.Error(err)
  9523. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9524. }
  9525. _, err = tx.Insert(xxwFtdetailList)
  9526. if err != nil {
  9527. logs.Error(err)
  9528. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9529. }
  9530. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  9531. appG.Response(http.StatusOK, e.SUCCESS, true)
  9532. }
  9533. func AddXxwFeedtemplet(c *gin.Context) {
  9534. appG := app.Gin{C: c}
  9535. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  9536. c.Bind(&xxwFeedtempletList)
  9537. tx := restful.Engine.NewSession()
  9538. defer tx.Close()
  9539. pastureinfo := new(udPastureInfo)
  9540. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  9541. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  9542. if err != nil {
  9543. logs.Error(err)
  9544. return
  9545. }
  9546. for _, ft := range xxwFeedtempletList {
  9547. ids, err := setting.SnowIds.NextId()
  9548. if err != nil {
  9549. ids = time.Now().UnixNano()
  9550. logging.Info("create SnowIds err", err)
  9551. }
  9552. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  9553. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  9554. ft.RecipeobjName, ft.RecipeobjName)
  9555. if err != nil {
  9556. logs.Error(err)
  9557. return
  9558. }
  9559. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  9560. _, err = tx.Exec(` insert into feedtemplet(pastureid,tcode,tname,xxwTempletCode,ccid,ccname,owner,fttype,fttypeid,source,sort,xxwTempletCode)values(?,(concat(DATE_FORMAT(now(),'%Y%m%d'),'640247041')),
  9561. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  9562. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  9563. if err != nil {
  9564. logs.Error(err)
  9565. return
  9566. }
  9567. }
  9568. appG.Response(http.StatusOK, e.SUCCESS, true)
  9569. }
  9570. func ProcessExcel(c *gin.Context) {
  9571. appG := app.Gin{C: c}
  9572. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9573. fasion := gofasion.NewFasion(string(dataByte))
  9574. params := fasion.Get("parammaps")
  9575. pastureid := params.Get("pastureid").ValueStr()
  9576. startTime := params.Get("startTime").ValueStr()
  9577. stopTime := params.Get("stopTime").ValueStr()
  9578. iscompleted := params.Get("iscompleted").ValueStr()
  9579. lpplantype := params.Get("lpplantype").ValueStr()
  9580. error := params.Get("error").ValueStr()
  9581. hlwc1 := params.Get("hlwc1").ValueStr()
  9582. hlwc2 := params.Get("hlwc2").ValueStr()
  9583. slwc1 := params.Get("slwc1").ValueStr()
  9584. slwc2 := params.Get("slwc2").ValueStr()
  9585. hlzq1 := params.Get("hlzq1").ValueStr()
  9586. hlzq2 := params.Get("hlzq2").ValueStr()
  9587. slzq1 := params.Get("slzq1").ValueStr()
  9588. slzq2 := params.Get("slzq2").ValueStr()
  9589. fclassid := params.Get("fclassid").ValueStr()
  9590. minproesstime := params.Get("minproesstime").ValueStr()
  9591. maxproesstime := params.Get("maxproesstime").ValueStr()
  9592. tx := restful.Engine.NewSession()
  9593. defer tx.Close()
  9594. planList, err := tx.SQL(`SELECT
  9595. d.id,d.tmrtname,d.projname,date_format(d.mydate ,'%Y-%m-%d') mydate ,date_format(d.intime ,'%Y-%m-%d') intime,p.pasture_name pastureName
  9596. FROM downloadedplan d
  9597. join pasture p on p.pastureid = d.pastureid
  9598. WHERE d.pastureid= ? and d.intime IS NOT NULL
  9599. AND mydate >= ? AND mydate <= ?
  9600. AND (iscompleted=? or ?='')
  9601. AND (lpplantype = ? or ? = '')
  9602. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  9603. and ABS(d1.lweight- d1.actualweightminus) > d1.feedallowratio and d1.feedallowratio != 0 ) >0,"有误差","无误差") = ? or if((select count(1) from downloadplandtl2 d1 where d1.pid = d.id
  9604. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  9605. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9606. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  9607. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9608. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  9609. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9610. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  9611. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9612. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  9613. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  9614. join feed f on f.feedcode = d1.feedcode and f.pastureid = d1.pastureid where f.fclassid = ? and d1.pid = d.id) > 0) and (round(TIMESTAMPDIFF(SECOND,
  9615. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  9616. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  9617. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  9618. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9619. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  9620. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  9621. or (?= '' and ? = '' ))
  9622. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  9623. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  9624. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  9625. maxproesstime, minproesstime, maxproesstime).QueryString()
  9626. if err != nil {
  9627. logs.Error(err)
  9628. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9629. return
  9630. }
  9631. planExecList, err := tx.SQL(`SELECT
  9632. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9633. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9634. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  9635. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9636. ) proesstime,
  9637. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9638. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  9639. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9640. sumproesstime, d1.pid,
  9641. d1.sort,
  9642. d1.fname,
  9643. d1.lweight,
  9644. d1.actualweightminus,
  9645. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  9646. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  9647. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  9648. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  9649. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  9650. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  9651. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9652. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9653. d1.begintime stoptime,
  9654. d1.lastactualweight,
  9655. d1.actualweight,
  9656. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  9657. case d1.buttontype
  9658. when 1 then '自动'
  9659. when 2 then '手动'
  9660. when 3 then '手动'
  9661. end,
  9662. case d1.buttontype
  9663. when 1 then 'Automatic'
  9664. when 2 then 'Manual'
  9665. when 3 then 'Manual'
  9666. end
  9667. ) buttontype
  9668. FROM
  9669. downloadplandtl1_exec d1
  9670. WHERE d1.date between ? and ?
  9671. ORDER BY sort
  9672. `, startTime, stopTime).QueryString()
  9673. if err != nil {
  9674. logs.Error(err)
  9675. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9676. return
  9677. }
  9678. planExec2, err := tx.SQL(`SELECT
  9679. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  9680. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9681. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9682. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  9683. ) proesstime,
  9684. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  9685. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9686. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  9687. d1.sort,
  9688. d1.fname,
  9689. d1.lweight,
  9690. d1.actualweightminus,
  9691. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  9692. ABS(d1.lweight- d1.actualweightminus) diff,
  9693. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,if(abs(d1.actualweightminus - d1.lweight) <=d1.allowratio , 100,if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - d1.allowratio)/d1.actualweightminus , 1-(abs(d1.actualweightminus - d1.lweight) - d1.allowratio)/d1.lweight )* 100) ,if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9694. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9695. d1.begintime stoptime,
  9696. d1.lastactualweight,
  9697. d1.actualweight,d1.pid
  9698. FROM
  9699. downloadplandtl2 d1
  9700. WHERE d1.date between ? and ?
  9701. ORDER BY sort`, startTime, stopTime).QueryString()
  9702. if err != nil {
  9703. logs.Error(err)
  9704. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9705. return
  9706. }
  9707. // 创建一个新的 Excel 文件
  9708. f := excelizexuri.NewFile()
  9709. // 创建工作表名称
  9710. sheetName := "Sheet1"
  9711. border := []excelizexuri.Border{
  9712. {Type: "left", Color: "000000", Style: 1},
  9713. {Type: "right", Color: "000000", Style: 1},
  9714. {Type: "top", Color: "000000", Style: 1},
  9715. {Type: "bottom", Color: "000000", Style: 1},
  9716. }
  9717. // 创建新的样式
  9718. style := &excelizexuri.Style{
  9719. // Border: border,
  9720. Alignment: &excelizexuri.Alignment{
  9721. Vertical: "center",
  9722. Horizontal: "center",
  9723. ShrinkToFit: true,
  9724. WrapText: true,
  9725. },
  9726. }
  9727. styleTitle := &excelizexuri.Style{
  9728. // Border: border,
  9729. Font: &excelizexuri.Font{
  9730. Bold: true, // 加粗
  9731. Size: 24, // 字体大小
  9732. // Name: "宋体", // 字体名称
  9733. // WrapText :true,
  9734. Color: "000000", // 字体颜色(黑色)
  9735. },
  9736. Alignment: &excelizexuri.Alignment{
  9737. Vertical: "center", // 垂直居中
  9738. Horizontal: "center", // 水平居中
  9739. ShrinkToFit: true,
  9740. WrapText: true,
  9741. },
  9742. }
  9743. // 创建样式 ID
  9744. styleTitleId, err := f.NewStyle(styleTitle)
  9745. if err != nil {
  9746. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9747. return
  9748. }
  9749. // 创建样式 ID
  9750. styleID, err := f.NewStyle(style)
  9751. if err != nil {
  9752. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9753. return
  9754. }
  9755. // 合并单元格并设置内容
  9756. f.MergeCell(sheetName, "A1", "K1")
  9757. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  9758. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  9759. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  9760. planExecMap := make(map[string][]map[string]string, 0)
  9761. for _, planExec := range planExecList {
  9762. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  9763. }
  9764. plan2Map := make(map[string][]map[string]string, 0)
  9765. for _, plan2 := range planExec2 {
  9766. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  9767. }
  9768. num := 2
  9769. var notBorder []int
  9770. for _, plan := range planList {
  9771. fmt.Println(plan)
  9772. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  9773. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9774. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9775. for i, header := range headers {
  9776. // 从 A2 开始
  9777. if header == "开始日期" {
  9778. cell := "%" + fmt.Sprintf("c%d", num)
  9779. cell = fmt.Sprintf(cell, 'A'+i+1)
  9780. f.SetCellValue(sheetName, cell, header)
  9781. f.SetCellStyle(sheetName, cell, cell, styleID)
  9782. continue
  9783. }
  9784. cell := "%" + fmt.Sprintf("c%d", num)
  9785. cell = fmt.Sprintf(cell, 'A'+i)
  9786. f.SetCellValue(sheetName, cell, header)
  9787. f.SetCellStyle(sheetName, cell, cell, styleID)
  9788. }
  9789. num += 1
  9790. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  9791. cell := "%" + fmt.Sprintf("c%d", num)
  9792. cell = fmt.Sprintf(cell, 'A'+0)
  9793. f.SetCellValue(sheetName, cell, plan["pastureName"])
  9794. f.SetCellStyle(sheetName, cell, cell, styleID)
  9795. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  9796. cell = "%" + fmt.Sprintf("c%d", num)
  9797. cell = fmt.Sprintf(cell, 'A'+1)
  9798. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  9799. f.SetCellStyle(sheetName, cell, cell, styleID)
  9800. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  9801. cell = "%" + fmt.Sprintf("c%d", num)
  9802. cell = fmt.Sprintf(cell, 'A'+2)
  9803. f.SetCellValue(sheetName, cell, plan["projname"])
  9804. f.SetCellStyle(sheetName, cell, cell, styleID)
  9805. cell = "%" + fmt.Sprintf("c%d", num)
  9806. cell = fmt.Sprintf(cell, 'A'+3)
  9807. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9808. f.SetCellValue(sheetName, cell, plan["mydate"])
  9809. f.SetCellStyle(sheetName, cell, cell, styleID)
  9810. cell = "%" + fmt.Sprintf("c%d", num)
  9811. cell = fmt.Sprintf(cell, 'A'+6)
  9812. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9813. f.SetCellValue(sheetName, cell, plan["intime"])
  9814. f.SetCellStyle(sheetName, cell, cell, styleID)
  9815. num += 1
  9816. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9817. for i, header := range headers1 {
  9818. cell = "%" + fmt.Sprintf("c%d", num)
  9819. cell = fmt.Sprintf(cell, 'C'+i)
  9820. f.SetCellValue(sheetName, cell, header)
  9821. f.SetCellStyle(sheetName, cell, cell, styleID)
  9822. // maxWidth := len(header)
  9823. // colName := string('C' + i)
  9824. // f.SetColWidth(sheetName, colName, colName, 20)
  9825. f.SetColWidth(sheetName, header, header, 40)
  9826. }
  9827. num += 1
  9828. for _, planExec := range planExecMap[plan["id"]] {
  9829. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9830. sort, _ := strconv.Atoi(planExec["sort"])
  9831. f.SetCellValue(sheetName, cell, sort)
  9832. f.SetCellStyle(sheetName, cell, cell, styleID)
  9833. cell = fmt.Sprintf("D%d", num)
  9834. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  9835. f.SetCellValue(sheetName, cell, lweight)
  9836. f.SetCellStyle(sheetName, cell, cell, styleID)
  9837. cell = fmt.Sprintf("E%d", num)
  9838. if _, ok := planExec["actualweightminus"]; ok {
  9839. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  9840. f.SetCellValue(sheetName, cell, actualweightminus)
  9841. f.SetCellStyle(sheetName, cell, cell, styleID)
  9842. } else {
  9843. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  9844. f.SetCellStyle(sheetName, cell, cell, styleID)
  9845. }
  9846. cell = fmt.Sprintf("F%d", num)
  9847. f.SetCellValue(sheetName, cell, planExec["fname"])
  9848. f.SetCellStyle(sheetName, cell, cell, styleID)
  9849. cell = fmt.Sprintf("G%d", num)
  9850. if _, ok := planExec["diff"]; ok {
  9851. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  9852. f.SetCellValue(sheetName, cell, diff)
  9853. f.SetCellStyle(sheetName, cell, cell, styleID)
  9854. } else {
  9855. f.SetCellValue(sheetName, cell, planExec["diff"])
  9856. f.SetCellStyle(sheetName, cell, cell, styleID)
  9857. }
  9858. cell = fmt.Sprintf("H%d", num)
  9859. if _, ok := planExec["diffRate"]; ok {
  9860. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  9861. f.SetCellValue(sheetName, cell, diffRate)
  9862. f.SetCellStyle(sheetName, cell, cell, styleID)
  9863. } else {
  9864. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  9865. f.SetCellStyle(sheetName, cell, cell, styleID)
  9866. }
  9867. cell = fmt.Sprintf("I%d", num)
  9868. f.SetCellValue(sheetName, cell, planExec["intime"])
  9869. f.SetCellStyle(sheetName, cell, cell, styleID)
  9870. cell = fmt.Sprintf("J%d", num)
  9871. if _, ok := planExec["lastactualweight"]; ok {
  9872. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  9873. f.SetCellValue(sheetName, cell, lastactualweight)
  9874. f.SetCellStyle(sheetName, cell, cell, styleID)
  9875. } else {
  9876. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  9877. f.SetCellStyle(sheetName, cell, cell, styleID)
  9878. }
  9879. cell = fmt.Sprintf("K%d", num)
  9880. if _, ok := planExec["actualweight"]; ok {
  9881. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  9882. f.SetCellValue(sheetName, cell, actualweight)
  9883. f.SetCellStyle(sheetName, cell, cell, styleID)
  9884. } else {
  9885. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  9886. f.SetCellStyle(sheetName, cell, cell, styleID)
  9887. }
  9888. num += 1
  9889. }
  9890. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9891. for i, header := range headers2 {
  9892. cell := "%" + fmt.Sprintf("c%d", num)
  9893. cell = fmt.Sprintf(cell, 'C'+i)
  9894. f.SetCellValue(sheetName, cell, header)
  9895. f.SetCellStyle(sheetName, cell, cell, styleID)
  9896. maxWidth := len(header)
  9897. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  9898. }
  9899. num += 1
  9900. for _, plan2 := range plan2Map[plan["id"]] {
  9901. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9902. sort, _ := strconv.Atoi(plan2["sort"])
  9903. f.SetCellValue(sheetName, cell, sort)
  9904. f.SetCellStyle(sheetName, cell, cell, styleID)
  9905. cell = fmt.Sprintf("D%d", num)
  9906. f.SetCellValue(sheetName, cell, plan2["fname"])
  9907. f.SetCellStyle(sheetName, cell, cell, styleID)
  9908. cell = fmt.Sprintf("E%d", num)
  9909. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  9910. f.SetCellValue(sheetName, cell, lweight)
  9911. f.SetCellStyle(sheetName, cell, cell, styleID)
  9912. cell = fmt.Sprintf("F%d", num)
  9913. if _, ok := plan2["actualweightminus"]; ok {
  9914. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  9915. f.SetCellValue(sheetName, cell, actualweightminus)
  9916. f.SetCellStyle(sheetName, cell, cell, styleID)
  9917. } else {
  9918. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  9919. f.SetCellStyle(sheetName, cell, cell, styleID)
  9920. }
  9921. cell = fmt.Sprintf("G%d", num)
  9922. if _, ok := plan2["diff"]; ok {
  9923. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  9924. f.SetCellValue(sheetName, cell, diff)
  9925. f.SetCellStyle(sheetName, cell, cell, styleID)
  9926. } else {
  9927. f.SetCellValue(sheetName, cell, plan2["diff"])
  9928. f.SetCellStyle(sheetName, cell, cell, styleID)
  9929. }
  9930. cell = fmt.Sprintf("H%d", num)
  9931. if _, ok := plan2["diffRate"]; ok {
  9932. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  9933. f.SetCellValue(sheetName, cell, diffRate)
  9934. f.SetCellStyle(sheetName, cell, cell, styleID)
  9935. } else {
  9936. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  9937. f.SetCellStyle(sheetName, cell, cell, styleID)
  9938. }
  9939. cell = fmt.Sprintf("I%d", num)
  9940. f.SetCellValue(sheetName, cell, plan2["intime"])
  9941. f.SetCellStyle(sheetName, cell, cell, styleID)
  9942. cell = fmt.Sprintf("J%d", num)
  9943. if _, ok := plan2["lastactualweight"]; ok {
  9944. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  9945. f.SetCellValue(sheetName, cell, lastactualweight)
  9946. f.SetCellStyle(sheetName, cell, cell, styleID)
  9947. } else {
  9948. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  9949. f.SetCellStyle(sheetName, cell, cell, styleID)
  9950. }
  9951. cell = fmt.Sprintf("K%d", num)
  9952. if _, ok := plan2["lastactualweight"]; ok {
  9953. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  9954. f.SetCellValue(sheetName, cell, actualweight)
  9955. f.SetCellStyle(sheetName, cell, cell, styleID)
  9956. } else {
  9957. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  9958. f.SetCellStyle(sheetName, cell, cell, styleID)
  9959. }
  9960. num += 1
  9961. }
  9962. num += 1
  9963. notBorder = append(notBorder, num)
  9964. }
  9965. for i := 2; i < num; i++ {
  9966. exist := false
  9967. for _, n := range notBorder {
  9968. if i+1 == n {
  9969. exist = true
  9970. break
  9971. }
  9972. }
  9973. if !exist {
  9974. // 为 A-K 列设置边框
  9975. for col := 'A'; col <= 'K'; col++ {
  9976. cellName := fmt.Sprintf("%c%d", col, i)
  9977. style, _ := f.NewStyle(&excelizexuri.Style{
  9978. Border: border, Alignment: &excelizexuri.Alignment{
  9979. Vertical: "center",
  9980. Horizontal: "center",
  9981. ShrinkToFit: true,
  9982. WrapText: true,
  9983. },
  9984. })
  9985. f.SetCellStyle(sheetName, cellName, cellName, style)
  9986. }
  9987. }
  9988. }
  9989. for col := 'A'; col <= 'K'; col++ {
  9990. colName := string(col)
  9991. switch colName {
  9992. case "A", "B": // 牧场名称、TMR列
  9993. f.SetColWidth(sheetName, colName, colName, 10)
  9994. case "C": // 操作编号列
  9995. f.SetColWidth(sheetName, colName, colName, 10)
  9996. case "D", "E": // 计划重量、实际重量列
  9997. f.SetColWidth(sheetName, colName, colName, 12)
  9998. case "F": // 代表成分/投料位置列
  9999. f.SetColWidth(sheetName, colName, colName, 20)
  10000. case "G", "H": // 误差数、准确率列
  10001. f.SetColWidth(sheetName, colName, colName, 12)
  10002. case "I": // 完成时间列
  10003. f.SetColWidth(sheetName, colName, colName, 15)
  10004. case "J", "K": // 起始读数重量、完成读数重量列
  10005. f.SetColWidth(sheetName, colName, colName, 15)
  10006. }
  10007. }
  10008. // 设置响应头
  10009. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10010. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10011. c.Header("Content-Transfer-Encoding", "binary")
  10012. // 写入 Excel 文件到响应
  10013. if err := f.Write(c.Writer); err != nil {
  10014. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10015. return
  10016. }
  10017. }
  10018. func RestartMqtt(c *gin.Context) {
  10019. appG := app.Gin{C: c}
  10020. // 发送 GET 请求到 MQTT 重启接口
  10021. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10022. if err != nil {
  10023. logging.Error("RestartMqtt request failed:", err)
  10024. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10025. return
  10026. }
  10027. defer resp.Body.Close()
  10028. // 读取响应内容f
  10029. body, err := ioutil.ReadAll(resp.Body)
  10030. if err != nil {
  10031. logging.Error("RestartMqtt read response failed:", err)
  10032. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10033. return
  10034. }
  10035. // 检查响应状态码
  10036. if resp.StatusCode != http.StatusOK {
  10037. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10038. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10039. return
  10040. }
  10041. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10042. }
  10043. func FpdBatchEditByWeight(c *gin.Context) {
  10044. appG := app.Gin{C: c}
  10045. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10046. fsions := gofasion.NewFasion(string(dataByte))
  10047. barList := fsions.Get("barList").Array()
  10048. pastureid := fsions.Get("pastureId").ValueStr()
  10049. tx := restful.Engine.NewSession()
  10050. defer tx.Close()
  10051. 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
  10052. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10053. if err != nil {
  10054. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10055. return
  10056. }
  10057. for _, barFsions := range barList {
  10058. dataexcel := make(map[string]interface{}, 0)
  10059. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10060. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10061. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10062. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10063. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10064. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10065. continue
  10066. }
  10067. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10068. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10069. // if err != nil {
  10070. // logs.Error(err)
  10071. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10072. // return
  10073. // }
  10074. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10075. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10076. // if err != nil {
  10077. // logs.Error(err)
  10078. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10079. // return
  10080. // }
  10081. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10082. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10083. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10084. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10085. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10086. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10087. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10088. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10089. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10090. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10091. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10092. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10093. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10094. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10095. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10096. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10097. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10098. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10099. if err != nil {
  10100. logs.Error(err)
  10101. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10102. return
  10103. }
  10104. if !ftexist {
  10105. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10106. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10107. if err != nil {
  10108. logs.Error(err)
  10109. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10110. return
  10111. }
  10112. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10113. if err != nil {
  10114. logs.Error(err)
  10115. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10116. return
  10117. }
  10118. }
  10119. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10120. if err != nil {
  10121. logs.Error(err)
  10122. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10123. return
  10124. }
  10125. if !exist {
  10126. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10127. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10128. if err != nil {
  10129. logs.Error(err)
  10130. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10131. return
  10132. }
  10133. }
  10134. var feedpargs []interface{}
  10135. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10136. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10137. if _, ok := dataexcel["ftname"]; ok {
  10138. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10139. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10140. // upFeedpSql += `,ftweight = ? `
  10141. // feedpargs = append(feedpargs, weight)
  10142. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10143. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10144. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10145. } else {
  10146. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10147. }
  10148. // if _, ok := dataexcel["ptsfname"]; ok {
  10149. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10150. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10151. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10152. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10153. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10154. // } else {
  10155. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10156. // }
  10157. upFeedpSql += " where barname = ? and pastureid = ? "
  10158. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10159. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10160. if err != nil {
  10161. logs.Error(err)
  10162. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10163. return
  10164. }
  10165. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10166. if err != nil {
  10167. logs.Error(err)
  10168. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10169. return
  10170. }
  10171. if !exist1 {
  10172. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10173. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10174. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10175. if err != nil {
  10176. logs.Error(err)
  10177. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10178. return
  10179. }
  10180. }
  10181. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10182. if err != nil {
  10183. logs.Error(err)
  10184. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10185. return
  10186. }
  10187. if !exist2 {
  10188. _, 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) `,
  10189. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10190. if err != nil {
  10191. logs.Error(err)
  10192. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10193. return
  10194. }
  10195. }
  10196. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10197. if err != nil {
  10198. logs.Error(err)
  10199. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10200. return
  10201. }
  10202. if !exist3 {
  10203. _, 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) `,
  10204. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10205. if err != nil {
  10206. logs.Error(err)
  10207. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10208. return
  10209. }
  10210. }
  10211. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10212. if err != nil {
  10213. logs.Error(err)
  10214. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10215. return
  10216. }
  10217. if !exist4 {
  10218. _, 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) `,
  10219. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10220. if err != nil {
  10221. logs.Error(err)
  10222. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10223. return
  10224. }
  10225. }
  10226. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10227. if err != nil {
  10228. logs.Error(err)
  10229. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10230. return
  10231. }
  10232. if !exist5 {
  10233. _, 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) `,
  10234. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10235. if err != nil {
  10236. logs.Error(err)
  10237. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10238. return
  10239. }
  10240. }
  10241. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10242. if err != nil {
  10243. logs.Error(err)
  10244. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10245. return
  10246. }
  10247. if !exist6 {
  10248. _, 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) `,
  10249. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10250. if err != nil {
  10251. logs.Error(err)
  10252. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10253. return
  10254. }
  10255. }
  10256. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10257. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10258. and pastureid = ? and times = ?`
  10259. var fpdargs1 []interface{}
  10260. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10261. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10262. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10263. if err != nil {
  10264. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10265. return
  10266. }
  10267. var fpdargs2 []interface{}
  10268. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10269. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10270. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10271. if err != nil {
  10272. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10273. return
  10274. }
  10275. var fpdargs3 []interface{}
  10276. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10277. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10278. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10279. if err != nil {
  10280. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10281. return
  10282. }
  10283. var fpdargs4 []interface{}
  10284. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10285. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10286. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10287. if err != nil {
  10288. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10289. return
  10290. }
  10291. var fpdargs5 []interface{}
  10292. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10293. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10294. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10295. if err != nil {
  10296. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10297. return
  10298. }
  10299. var fpdargs6 []interface{}
  10300. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10301. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10302. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10303. if err != nil {
  10304. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10305. return
  10306. }
  10307. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10308. 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()
  10309. if err != nil {
  10310. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10311. return
  10312. }
  10313. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10314. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10315. upFpdetailList := make([]*upFpdetail, 0)
  10316. for _, newfpd := range newList {
  10317. for _, oldfpd := range oldFpdList {
  10318. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10319. var oldweight, newweight float64
  10320. if oldfpd["weight"] != nil {
  10321. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10322. }
  10323. if newfpd["weight"] != nil {
  10324. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10325. }
  10326. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10327. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10328. Old: oldweight,
  10329. New: newweight,
  10330. Times: newfpd["times"].(int64),
  10331. Ptid: newfpd["ptid"].(int64),
  10332. Fweight: fweight,
  10333. Id: oldfpd["id"].(int64),
  10334. })
  10335. break
  10336. }
  10337. }
  10338. }
  10339. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10340. }
  10341. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10342. }
  10343. func FtImportExcel(c *gin.Context) {
  10344. appG := app.Gin{C: c}
  10345. inputdata := ""
  10346. c.Request.ParseForm()
  10347. params := c.Request.Form
  10348. file, _, err := c.Request.FormFile("file")
  10349. if err != nil {
  10350. appG.Response(http.StatusOK, e.ERROR, err)
  10351. return
  10352. }
  10353. sqlnamestrs := params.Get("name")
  10354. sheetname := params.Get("sheetname")
  10355. pastureid := params.Get("pastureid")
  10356. //importParams := params.Get("importParams")
  10357. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10358. // 必输项参数 (字符串格式 "field1,field2,field3")
  10359. requiredParams := params.Get("requiredParams")
  10360. // 日期参数
  10361. dateParams := params.Get("dateParams")
  10362. // 数字参数
  10363. numParams := params.Get("numParams")
  10364. //将字符串分割开
  10365. dateParamslist := strings.Split(dateParams, ",")
  10366. requiredParamslist := strings.Split(requiredParams, ",")
  10367. numParamslist := strings.Split(numParams, ",")
  10368. queryData := make([]interface{}, 0)
  10369. sqlslist := strings.Split(sqlnamestrs, ",")
  10370. xlsx1, err := excelize.OpenReader(file)
  10371. if err != nil {
  10372. fmt.Println(err)
  10373. return
  10374. }
  10375. ok := 0
  10376. error := 0
  10377. isdone := true
  10378. rows := xlsx1.GetRows(sheetname)
  10379. // 限制10000条,多余的截取掉
  10380. if len(rows) > 10000 {
  10381. rows = rows[:10000]
  10382. }
  10383. tx := restful.Engine.NewSession()
  10384. ftNameList := make(map[string]interface{})
  10385. for i, row := range rows {
  10386. if i > 0 {
  10387. entry := make(map[string]interface{})
  10388. outentry := make(map[string]interface{})
  10389. for j, colCell := range rows[0] {
  10390. for k, colCell1 := range row {
  10391. if j == k {
  10392. outentry[colCell] = colCell1
  10393. entry[colCell] = colCell1
  10394. }
  10395. }
  10396. }
  10397. inputdata = ""
  10398. a := ""
  10399. fmt.Println(outentry, entry)
  10400. //校验日期格式
  10401. for _, v := range dateParamslist {
  10402. if v == "" {
  10403. continue
  10404. }
  10405. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10406. dtime, err := TransfTime(d.(string))
  10407. if err != nil {
  10408. a = strings.Trim(v, " ")
  10409. break
  10410. }
  10411. outentry[strings.Trim(v, " ")] = dtime
  10412. }
  10413. }
  10414. if a != "" {
  10415. outentry["error_msg"] = a + " 格式错误"
  10416. error++
  10417. queryData = append(queryData, outentry)
  10418. continue
  10419. }
  10420. a = ""
  10421. //校验必填格式
  10422. for _, v := range requiredParamslist {
  10423. if v == "" {
  10424. continue
  10425. }
  10426. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10427. a = strings.Trim(v, " ")
  10428. break
  10429. }
  10430. }
  10431. if a != "" {
  10432. outentry["error_msg"] = a + " 未填或格式错误"
  10433. error++
  10434. queryData = append(queryData, outentry)
  10435. continue
  10436. }
  10437. a = ""
  10438. //校验数字格式
  10439. for _, v := range numParamslist {
  10440. if v == "" {
  10441. continue
  10442. }
  10443. d, ok := outentry[strings.Trim(v, " ")]
  10444. if !ok || d == "" {
  10445. outentry[strings.Trim(v, " ")] = 0
  10446. } else {
  10447. var fl float64
  10448. switch d.(type) {
  10449. case string:
  10450. fl, err = strconv.ParseFloat(d.(string), 64)
  10451. }
  10452. if err != nil || fl < 0 {
  10453. a = strings.Trim(v, " ")
  10454. break
  10455. }
  10456. }
  10457. }
  10458. if a != "" {
  10459. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10460. error++
  10461. queryData = append(queryData, outentry)
  10462. continue
  10463. }
  10464. err := tx.Begin()
  10465. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10466. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10467. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10468. }
  10469. for _, sqlnamestr := range sqlslist {
  10470. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  10471. paramslist := strings.Split(paramslists, ",")
  10472. if len(paramslist) > 0 {
  10473. s_params := make([]interface{}, 0)
  10474. for _, value := range paramslist {
  10475. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  10476. if tempv, exists := c.Get("jwt_username"); exists {
  10477. s_params = append(s_params, tempv.(string))
  10478. } else {
  10479. s_params = append(s_params, "")
  10480. }
  10481. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  10482. s_params = append(s_params, pastureid)
  10483. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  10484. ids, err := setting.SnowIds.NextId()
  10485. if err != nil {
  10486. ids = time.Now().UnixNano()
  10487. logging.Info("create SnowIds err", err)
  10488. }
  10489. s_params = append(s_params, ids)
  10490. } else {
  10491. if outentry[strings.Trim(value, " ")] == nil {
  10492. s_params = append(s_params, "")
  10493. } else {
  10494. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  10495. }
  10496. }
  10497. }
  10498. outentry["input"] = inputdata
  10499. fmt.Println(sql, s_params)
  10500. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  10501. if err != nil {
  10502. if tx != nil {
  10503. tx.Rollback()
  10504. }
  10505. if tx != nil {
  10506. tx.Close()
  10507. }
  10508. msg := geterrmsg(err.Error())
  10509. outentry["error_msg"] = msg
  10510. error++
  10511. queryData = append(queryData, outentry)
  10512. isdone = true
  10513. break
  10514. } else {
  10515. if len(returnmsgmap1) > 0 {
  10516. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  10517. if tx != nil {
  10518. tx.Rollback()
  10519. }
  10520. if tx != nil {
  10521. tx.Close()
  10522. }
  10523. msg := geterrmsg(va.(string))
  10524. outentry["error_msg"] = msg
  10525. error++
  10526. queryData = append(queryData, outentry)
  10527. isdone = true
  10528. break
  10529. }
  10530. }
  10531. isdone = false
  10532. }
  10533. }
  10534. }
  10535. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  10536. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  10537. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  10538. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  10539. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  10540. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  10541. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  10542. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  10543. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, outentry["配方名称"]).QueryString()
  10544. FpdBatchEditGrfd(pastureid, values1)
  10545. switch {
  10546. case err != nil:
  10547. if tx != nil {
  10548. tx.Rollback()
  10549. }
  10550. default:
  10551. if tx != nil {
  10552. err = tx.Commit()
  10553. }
  10554. }
  10555. if tx != nil {
  10556. tx.Close()
  10557. }
  10558. }
  10559. if !isdone {
  10560. ok++
  10561. isdone = true
  10562. }
  10563. }
  10564. data := make(map[string]interface{})
  10565. data["result"] = queryData
  10566. data["success"] = ok
  10567. data["err_count"] = error
  10568. appG.Response(http.StatusOK, e.SUCCESS, data)
  10569. }