ops.go 459 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "net/http"
  12. "os"
  13. "path"
  14. "regexp"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "tmr-watch/conf/setting"
  21. "tmr-watch/http/handle/jpud"
  22. "tmr-watch/http/handle/restful"
  23. "tmr-watch/http/handle/ymy"
  24. "tmr-watch/models"
  25. "tmr-watch/module"
  26. "tmr-watch/pkg/app"
  27. "tmr-watch/pkg/e"
  28. "tmr-watch/pkg/logging"
  29. "github.com/360EntSecGroup-Skylar/excelize"
  30. "github.com/Anderson-Lu/gofasion/gofasion"
  31. "github.com/astaxie/beego/logs"
  32. "github.com/gin-gonic/gin"
  33. "github.com/qichengzx/coordtransform"
  34. "github.com/tealeg/xlsx"
  35. "github.com/xormplus/xorm"
  36. excelizexuri "github.com/xuri/excelize/v2"
  37. )
  38. // @Summary 根据SQL执行得到数据集
  39. // @Tags getData
  40. // @Accept json
  41. // @Produce json
  42. // @Param sql query string true "sql"
  43. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  44. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  45. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  46. // @Router /data/getdata [POST]
  47. func GetData(c *gin.Context) {
  48. appG := app.Gin{C: c}
  49. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  50. fsion := gofasion.NewFasion(string(dataByte))
  51. sqlstr := fsion.Get("sql").ValueStr()
  52. offset := fsion.Get("offset").ValueDefaultInt(0)
  53. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  54. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  55. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  56. if err != nil {
  57. appG.Response(http.StatusOK, e.ERROR, err.Error())
  58. } else {
  59. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  60. }
  61. }
  62. func Testpartitions(c *gin.Context) {
  63. appG := app.Gin{C: c}
  64. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  65. fsion := gofasion.NewFasion(string(dataByte))
  66. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  67. user := fsion.Get("user").ValueStr() //获取新数据库用户
  68. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  69. host := fsion.Get("host").ValueStr() //获取新数据库名称
  70. port := fsion.Get("port").ValueStr() //获取新数据库名称
  71. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  72. if sqls == nil || err1 != nil {
  73. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  74. }
  75. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  76. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  77. mydb, err := sql.Open("mysql", connecting) //连接新连接
  78. if err != nil {
  79. println("err1", err.Error())
  80. }
  81. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  82. if err != nil {
  83. println("err2", err.Error())
  84. }
  85. mydb.Close()
  86. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  87. mydb, err = sql.Open("mysql", connecting)
  88. if err != nil {
  89. println("err3", err.Error())
  90. }
  91. defer mydb.Close()
  92. if err == nil {
  93. mydb.SetMaxOpenConns(10)
  94. mydb.SetMaxIdleConns(10)
  95. }
  96. errmsg := ""
  97. if err == nil {
  98. //tx ,_ :=mydb.Begin()
  99. for _, sqlstr := range sqlstrs {
  100. //println("sqlstr---",sqlstr)
  101. if sqlstr == "" {
  102. continue
  103. }
  104. _, err = mydb.Exec(sqlstr)
  105. if err != nil {
  106. println("err4", err.Error())
  107. errmsg = err.Error()
  108. //err1 :=tx.Rollback()
  109. }
  110. }
  111. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  112. //err =tx.Commit()
  113. }
  114. if errmsg == "" {
  115. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  116. } else {
  117. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  118. }
  119. }
  120. func TestData(c *gin.Context) {
  121. appG := app.Gin{C: c}
  122. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  123. fsion := gofasion.NewFasion(string(dataByte))
  124. sqlstr := fsion.Get("sql").ValueStr()
  125. token := ""
  126. if tempv, exists := c.Get("jwt_username"); exists {
  127. token = tempv.(string)
  128. }
  129. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  130. }
  131. // @Summary 根据APISQL表中SQL执行得到数据集
  132. // @Tags GetDataByName
  133. // @Accept json
  134. // @Produce json
  135. // @Param sqlname body string true "sqlname"
  136. // @Param offset body int true "offset"
  137. // @Param pagecount body int true "pagecount"
  138. // @Param returntype body string true "returntype"
  139. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  140. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  141. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  142. // @Router /data/GetDataByName [POST]
  143. func GetDataByName(c *gin.Context) {
  144. appG := app.Gin{C: c}
  145. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  146. fsion := gofasion.NewFasion(string(dataByte))
  147. sqlnamestr := fsion.Get("name").ValueStr()
  148. offset := fsion.Get("offset").ValueDefaultInt(0)
  149. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  150. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  151. tx := restful.Engine.NewSession()
  152. err := tx.Begin()
  153. defer func() {
  154. switch {
  155. case err != nil:
  156. logging.Error("tx.Begin 事务启动失败__error:", err)
  157. if tx != nil {
  158. tx.Rollback()
  159. }
  160. default:
  161. if tx != nil {
  162. err = tx.Commit()
  163. }
  164. }
  165. if tx != nil {
  166. tx.Close()
  167. }
  168. }()
  169. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  170. if sql != "" {
  171. s_params := make([]interface{}, 0)
  172. if fsion.HasKey("parammaps") {
  173. parammaps := fsion.Get("parammaps")
  174. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  175. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  176. }
  177. paramslist := strings.Split(p, ",")
  178. if len(paramslist) > 0 && p != "" {
  179. for _, value := range paramslist {
  180. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  181. if tempv, exists := c.Get("jwt_username"); exists {
  182. s_params = append(s_params, tempv.(string))
  183. } else {
  184. s_params = append(s_params, "")
  185. }
  186. } else {
  187. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  188. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  189. // tmrNameList := []string{}
  190. // for _, tmr := range tmrArray {
  191. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  192. // }
  193. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  194. // } else {
  195. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  196. // }
  197. }
  198. }
  199. }
  200. } else if fsion.HasKey("params") {
  201. params := fsion.Get("params").Array()
  202. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  203. for _, v_params := range params {
  204. s_params = append(s_params, v_params.ValueStr())
  205. }
  206. }
  207. if returntype == "xlsx" {
  208. var xlsxfile *xlsx.File
  209. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  210. //c.File("c:/dd.xlsx")
  211. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  212. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  213. c.Header("Content-Transfer-Encoding", "binary")
  214. _ = xlsxfile.Write(c.Writer)
  215. } else {
  216. if sqlnamestr == "getHomepageStr" {
  217. parammaps := fsion.Get("parammaps")
  218. pastureid := parammaps.Get("pastureid").ValueStr()
  219. var montimeList []float64
  220. var montime float64
  221. var wg sync.WaitGroup
  222. now := time.Now()
  223. for i := 0; i < 30; i++ {
  224. wg.Add(1)
  225. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  226. go func(nowstr string) {
  227. defer wg.Done()
  228. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  229. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  230. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  231. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  232. montimeList = append(montimeList, m)
  233. }
  234. }(nowstr)
  235. }
  236. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  237. if err != nil {
  238. logging.Error("GetDataByName err: ", err)
  239. msg := geterrmsg(err.Error())
  240. appG.Response(http.StatusOK, e.ERROR, msg)
  241. }
  242. wg.Wait()
  243. for _, m := range montimeList {
  244. montime += m
  245. }
  246. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  247. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  248. return
  249. }
  250. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  251. if err != nil {
  252. logging.Error("GetDataByName err: ", err)
  253. msg := geterrmsg(err.Error())
  254. appG.Response(http.StatusOK, e.ERROR, msg)
  255. } else {
  256. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  257. }
  258. }
  259. } else {
  260. appG.Response(http.StatusOK, e.SUCCESS, nil)
  261. }
  262. }
  263. // @Summary 根据APISQL表中SQL执行得到数据集
  264. // @Tags GetDataByName
  265. // @Accept json
  266. // @Produce json
  267. // @Param sqlname body string true "sqlname"
  268. // @Param offset body int true "offset"
  269. // @Param pagecount body int true "pagecount"
  270. // @Param returntype body string true "returntype"
  271. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  272. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  273. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  274. // @Router /data/GetDataByName [POST]
  275. func GetDataBySqlIN(c *gin.Context) {
  276. appG := app.Gin{C: c}
  277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  278. fsion := gofasion.NewFasion(string(dataByte))
  279. sqlnamestr := fsion.Get("name").ValueStr()
  280. offset := fsion.Get("offset").ValueDefaultInt(0)
  281. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  282. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  283. tx := restful.Engine.NewSession()
  284. err := tx.Begin()
  285. defer func() {
  286. switch {
  287. case err != nil:
  288. logging.Error("tx.Begin 事务启动失败__error:", err)
  289. if tx != nil {
  290. tx.Rollback()
  291. }
  292. default:
  293. if tx != nil {
  294. err = tx.Commit()
  295. }
  296. }
  297. if tx != nil {
  298. tx.Close()
  299. }
  300. }()
  301. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  302. if sql != "" {
  303. s_params := make([]interface{}, 0)
  304. if fsion.HasKey("parammaps") {
  305. parammaps := fsion.Get("parammaps")
  306. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  307. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  308. }
  309. paramslist := strings.Split(p, ",")
  310. if len(paramslist) > 0 && p != "" {
  311. for _, value := range paramslist {
  312. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  313. if tempv, exists := c.Get("jwt_username"); exists {
  314. s_params = append(s_params, tempv.(string))
  315. } else {
  316. s_params = append(s_params, "")
  317. }
  318. } else {
  319. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  320. }
  321. }
  322. }
  323. } else if fsion.HasKey("params") {
  324. params := fsion.Get("params").Array()
  325. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  326. for _, v_params := range params {
  327. s_params = append(s_params, v_params.ValueStr())
  328. }
  329. }
  330. if returntype == "xlsx" {
  331. var xlsxfile *xlsx.File
  332. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  333. //c.File("c:/dd.xlsx")
  334. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  335. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  336. c.Header("Content-Transfer-Encoding", "binary")
  337. _ = xlsxfile.Write(c.Writer)
  338. } else {
  339. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  340. if err != nil {
  341. logging.Error("GetDataByName err: ", err)
  342. msg := geterrmsg(err.Error())
  343. appG.Response(http.StatusOK, e.ERROR, msg)
  344. } else {
  345. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  346. }
  347. }
  348. } else {
  349. appG.Response(http.StatusOK, e.SUCCESS, nil)
  350. }
  351. }
  352. // 错误处理
  353. // 将报错信息处理成汉字
  354. func geterrmsg(errstr string) (msgstr string) {
  355. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  356. rs := []rune(errstr)
  357. if hzRegexp.MatchString(string(rs[0])) {
  358. msgstr = errstr
  359. return
  360. }
  361. if strings.Contains(errstr, "Duplicate entry") {
  362. strs := strings.Split(errstr, ` key '`)
  363. if len(strs) > 1 {
  364. if len(strs[len(strs)-1]) > 1 {
  365. errstr = "Duplicate entry :" + strs[len(strs)-1]
  366. }
  367. }
  368. }
  369. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  370. if err != nil {
  371. msgstr = errstr
  372. return
  373. }
  374. if msg == nil || len(msg) == 0 {
  375. var param []interface{}
  376. param = append(param, errstr, errstr)
  377. go func() {
  378. tx := restful.Engine.NewSession()
  379. err := tx.Begin()
  380. defer func() {
  381. switch {
  382. case err != nil:
  383. logging.Error("tx.Begin 事务启动失败__error:", err)
  384. if tx != nil {
  385. tx.Rollback()
  386. }
  387. default:
  388. if tx != nil {
  389. err = tx.Commit()
  390. }
  391. }
  392. if tx != nil {
  393. tx.Close()
  394. }
  395. }()
  396. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  397. if err != nil {
  398. logging.Error("insert into err_msg(err,msg) err", err)
  399. }
  400. }()
  401. msgstr = errstr
  402. } else {
  403. msgstr = msg[0]["msg"]
  404. }
  405. return
  406. }
  407. // @Summary 根据APISQL表中SQL执行得到数据集
  408. // @Tags GetDataByNameForm
  409. // @Accept json
  410. // @Produce json
  411. // @Param sqlname body json true "sqlname"
  412. // @Param offset query int true "offset"
  413. // @Param pagecount query int true "pagecount"
  414. // @Param returntype query string true "returntype"
  415. // @Param s formData json true "ss"
  416. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  417. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  418. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  419. // @Router /data/GetDataByNameForm [POST]
  420. func GetDataByNameForm(c *gin.Context) {
  421. appG := app.Gin{C: c}
  422. //sqlnamestr := c.PostForm("measureNumber")
  423. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  424. //fsion := gofasion.NewFasion(string(dataByte))
  425. //sqlnamestr := fsion.Get("name").ValueStr()
  426. //offset := fsion.Get("offset").ValueInt()
  427. //pagecount := fsion.Get("pagecount").ValueInt()
  428. //returntype := fsion.Get("returntype").ValueStr()
  429. //params := fsion.Get("params").Array()
  430. c.Request.ParseForm()
  431. params := c.Request.Form
  432. offset := 0
  433. pageSize_ := 0
  434. returntype := params.Get("page")
  435. if returntype == "" {
  436. returntype = "0"
  437. }
  438. if tempv, exists := c.Get("jwt_username"); exists {
  439. params.Set("JwtUserName", tempv.(string))
  440. } else {
  441. params.Set("JwtUserName", "")
  442. }
  443. sqlnamestr := params.Get("name")
  444. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  445. s_params := make([]interface{}, 0)
  446. if returntype == "1" {
  447. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  448. if error != nil {
  449. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  450. }
  451. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  452. if error != nil {
  453. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  454. }
  455. pageSize_ = pageSize
  456. offset = pageNum
  457. }
  458. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  459. paramslist := strings.Split(p, ",")
  460. if len(paramslist) > 0 && p != "" {
  461. for _, value := range paramslist {
  462. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  463. }
  464. }
  465. if sql != "" {
  466. if returntype == "xlsx" {
  467. var xlsxfile *xlsx.File
  468. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  469. c.Header("Content-Type", "application/octet-stream")
  470. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  471. c.Header("Content-Transfer-Encoding", "binary")
  472. _ = xlsxfile.Write(c.Writer)
  473. } else {
  474. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  475. if err != nil {
  476. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  477. } else {
  478. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  479. }
  480. }
  481. } else {
  482. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  483. }
  484. }
  485. // @Summary 递归获取所有
  486. // @Tags menu
  487. // @Accept json
  488. // @Produce json
  489. // @Param Ton query string true "Ton"
  490. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  491. // @Router /authdata/GetRoleMenus [GET]
  492. func GetRecuDataByName(c *gin.Context) {
  493. appG := app.Gin{C: c}
  494. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  495. fsion := gofasion.NewFasion(string(dataByte))
  496. sqlnamestr := fsion.Get("name").ValueStr()
  497. parentidname := fsion.Get("idname").ValueStr()
  498. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  499. params := make(map[string]interface{})
  500. s_params := make([]interface{}, 0)
  501. if fsion.HasKey("params") {
  502. for _, v_params := range fsion.Get("params").Array() {
  503. s_params = append(s_params, v_params.ValueStr())
  504. }
  505. params["params"] = s_params
  506. } else {
  507. jparams := fsion.Get("parammaps")
  508. paramslist := strings.Split(p, ",")
  509. if len(paramslist) > 0 && p != "" {
  510. for _, value := range paramslist {
  511. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  512. if tempv, exists := c.Get("jwt_username"); exists {
  513. params[value] = tempv.(string)
  514. } else {
  515. params[value] = ""
  516. }
  517. } else {
  518. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  519. }
  520. }
  521. }
  522. }
  523. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  524. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  525. if err != nil {
  526. appG.Response(http.StatusOK, e.ERROR, err.Error())
  527. }
  528. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  529. }
  530. // @Summary 根据APISQL表中SQL执行得到数据集
  531. // @Tags GetDataByNames
  532. // @Accept json
  533. // @Produce json
  534. // @RequestBody sqlname query string true "sqlname"
  535. // @Param offset query int true "offset"
  536. // @Param pagecount query int true "pagecount"
  537. // @Param returntype query string true "returntype"
  538. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  539. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  540. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  541. // @Router /data/GetDataByNames [POST]
  542. func GetDataByNames(c *gin.Context) {
  543. appG := app.Gin{C: c}
  544. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  545. fsion := gofasion.NewFasion(string(dataByte))
  546. sqlParams := fsion.Array()
  547. queryData := make(map[string]interface{})
  548. for _, v := range sqlParams {
  549. fsion2 := gofasion.NewFasion(v.Json())
  550. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  551. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  552. if sql == "" {
  553. errorm := make(map[string]interface{})
  554. errorm["code"] = e.ERROR
  555. errorm["message"] = "sql没找到"
  556. queryData[fsion2.Get("name").ValueStr()] = errorm
  557. continue
  558. } else if sql != "" {
  559. offset := fsion2.Get("offset").ValueInt()
  560. pagecount := fsion2.Get("pagecount").ValueInt()
  561. returntype := fsion2.Get("returntype").ValueStr()
  562. s_params := make([]interface{}, 0)
  563. if fsion2.HasKey("parammaps") {
  564. parammaps := fsion2.Get("parammaps")
  565. paramslist := strings.Split(p, ",")
  566. if len(paramslist) > 0 && p != "" {
  567. for _, value := range paramslist {
  568. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  569. if tempv, exists := c.Get("jwt_username"); exists {
  570. s_params = append(s_params, tempv.(string))
  571. } else {
  572. s_params = append(s_params, "")
  573. }
  574. } else {
  575. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  576. }
  577. }
  578. }
  579. } else if fsion2.HasKey("params") {
  580. params := fsion2.Get("params").Array()
  581. for _, v_params := range params {
  582. s_params = append(s_params, v_params.ValueStr())
  583. }
  584. }
  585. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  586. if err != nil {
  587. errorm := make(map[string]interface{})
  588. errorm["code"] = e.ERROR
  589. errorm["message"] = err.Error()
  590. queryData[fsion2.Get("name").ValueStr()] = errorm
  591. logging.Error("GetDataByNames err: ", err)
  592. continue
  593. } else {
  594. queryData[fsion2.Get("name").ValueStr()] = queryData1
  595. }
  596. }
  597. }
  598. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  599. }
  600. // @Summary 根据APISQL表中SQL执行得到数据集
  601. // @Tags PostDataByNameForm
  602. // @Accept json
  603. // @Produce json
  604. // @Param sqlname query string true "sqlname"
  605. // @Param offset query int true "offset"
  606. // @Param pagecount query int true "pagecount"
  607. // @Param returntype query string true "returntype"
  608. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  609. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  610. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  611. // @Router /data/PostDataByNameForm [POST]
  612. func PostDataByNameForm(c *gin.Context) {
  613. appG := app.Gin{C: c}
  614. c.Request.ParseForm()
  615. params := c.Request.Form
  616. sqlnamestr := params.Get("name")
  617. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  618. s_params := make([]interface{}, 0)
  619. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  620. paramslist := strings.Split(p, ",")
  621. if len(paramslist) > 0 {
  622. for _, value := range paramslist {
  623. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  624. }
  625. }
  626. if sql != "" {
  627. queryData, err := execDataBySql(sql, s_params)
  628. if err != nil {
  629. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  630. } else {
  631. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  632. }
  633. } else {
  634. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  635. }
  636. }
  637. // GetReportform 将数据集转换格式
  638. // @Tags PostDataByNameForm
  639. // @Accept json
  640. // @Produce json
  641. // @Param sqlname query string true "sqlname"
  642. // @Param offset query int true "offset"
  643. // @Param pagecount query int true "pagecount"
  644. // @Param returntype query string true "returntype"
  645. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  646. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  647. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  648. func GetReportform(c *gin.Context) {
  649. appG := app.Gin{C: c}
  650. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  651. fsion := gofasion.NewFasion(string(dataByte))
  652. sqlnamestr := fsion.Get("name").ValueStr()
  653. checked := fsion.Get("checked").ValueStr()
  654. offset := fsion.Get("offset").ValueDefaultInt(0)
  655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  656. parammaps := fsion.Get("parammaps")
  657. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  658. mode := parammaps.Get("mode").ValueDefaultInt(0)
  659. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  660. tx := restful.Engine.NewSession()
  661. err := tx.Begin()
  662. defer func() {
  663. switch {
  664. case err != nil:
  665. if tx != nil {
  666. tx.Rollback()
  667. }
  668. default:
  669. if tx != nil {
  670. err = tx.Commit()
  671. }
  672. }
  673. if tx != nil {
  674. tx.Close()
  675. }
  676. }()
  677. //fmt.Println("***************************************")
  678. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  679. if err != nil {
  680. appG.Response(http.StatusOK, e.ERROR, err.Error())
  681. } else {
  682. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  683. }
  684. }
  685. // GetUpkeepPlan 保养计划
  686. func GetUpkeepPlan(c *gin.Context) {
  687. appG := app.Gin{C: c}
  688. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  689. fsion := gofasion.NewFasion(string(dataByte))
  690. sqlnamestr := fsion.Get("name").ValueStr()
  691. offset := fsion.Get("offset").ValueDefaultInt(0)
  692. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  693. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  694. month := fsion.Get("month").ValueDefaultStr("map")
  695. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  696. tx := restful.Engine.NewSession()
  697. err := tx.Begin()
  698. defer func() {
  699. switch {
  700. case err != nil:
  701. if tx != nil {
  702. tx.Rollback()
  703. }
  704. default:
  705. if tx != nil {
  706. err = tx.Commit()
  707. }
  708. }
  709. if tx != nil {
  710. tx.Close()
  711. }
  712. }()
  713. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  714. if sql != "" {
  715. s_params := make([]interface{}, 0)
  716. if fsion.HasKey("parammaps") {
  717. parammaps := fsion.Get("parammaps")
  718. paramslist := strings.Split(p, ",")
  719. if len(paramslist) > 0 && p != "" {
  720. for _, value := range paramslist {
  721. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  722. if tempv, exists := c.Get("jwt_username"); exists {
  723. s_params = append(s_params, tempv.(string))
  724. } else {
  725. s_params = append(s_params, "")
  726. }
  727. } else {
  728. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  729. }
  730. }
  731. }
  732. } else if fsion.HasKey("params") {
  733. params := fsion.Get("params").Array()
  734. for _, v_params := range params {
  735. s_params = append(s_params, v_params.ValueStr())
  736. }
  737. }
  738. if returntype == "xlsx" {
  739. var xlsxfile *xlsx.File
  740. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  741. //c.File("c:/dd.xlsx")
  742. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  743. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  744. c.Header("Content-Transfer-Encoding", "binary")
  745. _ = xlsxfile.Write(c.Writer)
  746. } else {
  747. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  748. if err != nil {
  749. appG.Response(http.StatusOK, e.ERROR, err.Error())
  750. } else {
  751. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  752. if v, ok := value["id"]; ok {
  753. //month = "2020-03"
  754. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  755. if seviceplans != nil {
  756. for _, va := range seviceplans { //根据保养计划获取保养单
  757. //day,_ :=strconv.Atoi(va["day"])
  758. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  759. //buk := make(map[string]map[string]string)
  760. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  761. jstr := ""
  762. if bu["plantime"][8:9] == "0" {
  763. jstr = "m" + bu["plantime"][9:]
  764. } else {
  765. jstr = "m" + bu["plantime"][8:]
  766. }
  767. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  768. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  769. } else {
  770. if bu["flowCompeleted"] >= "2" {
  771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  772. } else {
  773. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  774. }
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  782. }
  783. }
  784. } else {
  785. appG.Response(http.StatusOK, e.SUCCESS, nil)
  786. }
  787. }
  788. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  789. // todo 优化性能 children统一查询
  790. // @Tags PostDataByNameForm
  791. // @Accept json
  792. // @Produce json
  793. // @Param sqlname query string true "sqlname"
  794. // @Param offset query int true "offset"
  795. // @Param pagecount query int true "pagecount"
  796. // @Param returntype query string true "returntype"
  797. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  798. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  799. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  800. func GetArrList(c *gin.Context) {
  801. appG := app.Gin{C: c}
  802. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  803. fsion := gofasion.NewFasion(string(dataByte))
  804. sqlnamestr := fsion.Get("name").ValueStr()
  805. sqlnamestr1 := fsion.Get("name1").ValueStr()
  806. offset := fsion.Get("offset").ValueDefaultInt(0)
  807. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  808. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  809. month := fsion.Get("month").ValueDefaultStr("map")
  810. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  811. tx := restful.Engine.NewSession()
  812. err := tx.Begin()
  813. defer func() {
  814. switch {
  815. case err != nil:
  816. if tx != nil {
  817. tx.Rollback()
  818. }
  819. default:
  820. if tx != nil {
  821. err = tx.Commit()
  822. }
  823. }
  824. if tx != nil {
  825. tx.Close()
  826. }
  827. }()
  828. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  829. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  830. if sql != "" {
  831. s_params := make([]interface{}, 0)
  832. if fsion.HasKey("parammaps") {
  833. parammaps := fsion.Get("parammaps")
  834. paramslist := strings.Split(p, ",")
  835. if len(paramslist) > 0 && p != "" {
  836. for _, value := range paramslist {
  837. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  838. if tempv, exists := c.Get("jwt_username"); exists {
  839. s_params = append(s_params, tempv.(string))
  840. } else {
  841. s_params = append(s_params, "")
  842. }
  843. } else {
  844. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  845. }
  846. }
  847. }
  848. }
  849. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  850. if err != nil {
  851. appG.Response(http.StatusOK, e.ERROR, err.Error())
  852. } else {
  853. paramslist1 := strings.Split(p1, ",")
  854. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  855. s_params1 := make([]interface{}, 0)
  856. if len(paramslist1) > 0 && p1 != "" {
  857. for _, v := range paramslist1 {
  858. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  859. }
  860. }
  861. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  862. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  863. }
  864. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  865. }
  866. } else {
  867. appG.Response(http.StatusOK, e.SUCCESS, nil)
  868. }
  869. }
  870. func GetAccount(c *gin.Context) {
  871. appG := app.Gin{C: c}
  872. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  873. fsion := gofasion.NewFasion(string(dataByte))
  874. sqlnamestr := fsion.Get("name").ValueStr()
  875. offset := fsion.Get("offset").ValueDefaultInt(0)
  876. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  877. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  878. tx := restful.Engine.NewSession()
  879. err := tx.Begin()
  880. defer func() {
  881. switch {
  882. case err != nil:
  883. logging.Error("tx.Begin 事务启动失败__error:", err)
  884. if tx != nil {
  885. tx.Rollback()
  886. }
  887. default:
  888. if tx != nil {
  889. err = tx.Commit()
  890. }
  891. }
  892. if tx != nil {
  893. tx.Close()
  894. }
  895. }()
  896. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  897. if sql != "" {
  898. s_params := make([]interface{}, 0)
  899. if fsion.HasKey("parammaps") {
  900. parammaps := fsion.Get("parammaps")
  901. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  902. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  903. }
  904. paramslist := strings.Split(p, ",")
  905. if len(paramslist) > 0 && p != "" {
  906. for _, value := range paramslist {
  907. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  908. if tempv, exists := c.Get("jwt_username"); exists {
  909. s_params = append(s_params, tempv.(string))
  910. } else {
  911. s_params = append(s_params, "")
  912. }
  913. } else {
  914. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  915. }
  916. }
  917. }
  918. } else if fsion.HasKey("params") {
  919. params := fsion.Get("params").Array()
  920. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  921. for _, v_params := range params {
  922. s_params = append(s_params, v_params.ValueStr())
  923. }
  924. }
  925. if returntype == "xlsx" {
  926. var xlsxfile *xlsx.File
  927. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  928. //c.File("c:/dd.xlsx")
  929. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  930. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  931. c.Header("Content-Transfer-Encoding", "binary")
  932. _ = xlsxfile.Write(c.Writer)
  933. } else {
  934. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  935. if err != nil {
  936. logging.Error("GetDataByName err: ", err)
  937. msg := geterrmsg(err.Error())
  938. appG.Response(http.StatusOK, e.ERROR, msg)
  939. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  940. } else {
  941. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  942. }
  943. }
  944. } else {
  945. appG.Response(http.StatusOK, e.SUCCESS, nil)
  946. }
  947. }
  948. // PostDataByName 根据APISQL表中SQL执行得到数据集
  949. // @Accept json
  950. // @Produce json
  951. // @Param sqlname query string true "sqlname"
  952. // @Param offset query int true "offset"
  953. // @Param pagecount query int true "pagecount"
  954. // @Param returntype query string true "returntype"
  955. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  956. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  957. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  958. // @Router /data/PostDataByName [POST]
  959. func PostDataByName(c *gin.Context) {
  960. appG := app.Gin{C: c}
  961. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  962. fsion := gofasion.NewFasion(string(dataByte))
  963. var err error
  964. queryData, err := module.PostDataByName(c, fsion)
  965. if err != nil {
  966. appG.Response(http.StatusOK, e.ERROR, err.Error())
  967. return
  968. }
  969. var (
  970. keyWord string
  971. )
  972. switch fsion.Get("name").ValueStr() {
  973. case "insertFeedclass":
  974. keyWord = "feed"
  975. err = module.GroupCategorySync(keyWord, fsion)
  976. case "deleteFeedclass":
  977. keyWord = "feed_delete"
  978. err = module.GroupCategoryDelete(keyWord, fsion)
  979. case "insertCowclass":
  980. keyWord = "cow"
  981. err = module.GroupCategorySync(keyWord, fsion)
  982. case "deleteCowclass":
  983. keyWord = "cow_delete"
  984. err = module.GroupCategoryDelete(keyWord, fsion)
  985. // case "updateFT":
  986. // FtdetailSurplus(fsion)
  987. // case "updateFeed":
  988. // FeedSurplus(fsion)
  989. default:
  990. }
  991. if err != nil {
  992. logging.Error(keyWord, err)
  993. }
  994. if queryData != nil {
  995. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  996. return
  997. }
  998. appG.Response(http.StatusOK, e.SUCCESS, nil)
  999. }
  1000. //人脸识别/格润富德接口
  1001. func GetRJSBData(c *gin.Context) {
  1002. appG := app.Gin{C: c}
  1003. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1004. fsion := gofasion.NewFasion(string(dataByte))
  1005. sqlnamestr := fsion.Get("name").ValueStr()
  1006. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1007. offset := fsion.Get("offset").ValueDefaultInt(0)
  1008. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1009. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1010. month := fsion.Get("month").ValueDefaultStr("map")
  1011. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1012. pagecount = 1
  1013. tx := restful.Engine.NewSession()
  1014. err := tx.Begin()
  1015. defer func() {
  1016. switch {
  1017. case err != nil:
  1018. if tx != nil {
  1019. tx.Rollback()
  1020. }
  1021. default:
  1022. if tx != nil {
  1023. err = tx.Commit()
  1024. }
  1025. }
  1026. if tx != nil {
  1027. tx.Close()
  1028. }
  1029. }()
  1030. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1031. _, err = tx.SQL(`update tmr set xianfeng = (select id from downloadedplan where lpplantype = 5 and mydate = date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted = 0 )
  1032. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1033. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1034. and lpplantype in(0,1)) `).Execute()
  1035. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1036. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1037. if sql != "" {
  1038. s_params := make([]interface{}, 0)
  1039. if fsion.HasKey("parammaps") {
  1040. parammaps := fsion.Get("parammaps")
  1041. paramslist := strings.Split(p, ",")
  1042. if len(paramslist) > 0 && p != "" {
  1043. for _, value := range paramslist {
  1044. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1045. if tempv, exists := c.Get("jwt_username"); exists {
  1046. s_params = append(s_params, tempv.(string))
  1047. } else {
  1048. s_params = append(s_params, "")
  1049. }
  1050. } else {
  1051. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1052. }
  1053. }
  1054. }
  1055. }
  1056. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1057. if err != nil {
  1058. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1059. } else {
  1060. paramslist1 := strings.Split(p1, ",")
  1061. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1062. s_params1 := make([]interface{}, 0)
  1063. if len(paramslist1) > 0 && p1 != "" {
  1064. for _, v := range paramslist1 {
  1065. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1066. }
  1067. }
  1068. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1069. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1070. }
  1071. var wg sync.WaitGroup
  1072. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1073. wg.Add(1)
  1074. go func(value map[string]interface{}) {
  1075. defer wg.Done()
  1076. // ,havebutton = 1
  1077. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1078. }(value)
  1079. }
  1080. wg.Wait()
  1081. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1082. }
  1083. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1084. } else {
  1085. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1086. }
  1087. }
  1088. func PostRJSBData(c *gin.Context) {
  1089. appG := app.Gin{C: c}
  1090. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1091. fsion := gofasion.NewFasion(string(dataByte))
  1092. logging.Info("PostRJSBData err: ", string(dataByte))
  1093. s_params := make([]interface{}, 0)
  1094. tx := restful.Engine.NewSession()
  1095. err := tx.Begin()
  1096. defer func() {
  1097. switch {
  1098. case err != nil:
  1099. if tx != nil {
  1100. tx.Rollback()
  1101. }
  1102. default:
  1103. if tx != nil {
  1104. err = tx.Commit()
  1105. }
  1106. }
  1107. if tx != nil {
  1108. tx.Close()
  1109. }
  1110. }()
  1111. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1112. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1113. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1114. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1115. if !fsion.HasKey("parammaps") {
  1116. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1117. return
  1118. }
  1119. parammaps := fsion.Get("parammaps")
  1120. paramslist := strings.Split(p, ",")
  1121. if len(paramslist) > 0 && p != "" {
  1122. for _, value := range paramslist {
  1123. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1124. }
  1125. }
  1126. projuctid := parammaps.Get("projuctid").ValueStr()
  1127. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1128. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1129. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1130. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1131. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1132. if err != nil {
  1133. logging.Error("PostRJSBData-0 err: ", err)
  1134. msg := geterrmsg(err.Error())
  1135. // appG.Response(http.StatusOK, e.ERROR, msg)
  1136. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1137. return
  1138. }
  1139. _, err = tx.SQL(sql, s_params...).Execute()
  1140. if err != nil {
  1141. logging.Error("PostRJSBData err: ", err)
  1142. msg := geterrmsg(err.Error())
  1143. // appG.Response(http.StatusOK, e.ERROR, msg)
  1144. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1145. return
  1146. }
  1147. s_params = make([]interface{}, 0)
  1148. paramslist = strings.Split(p1, ",")
  1149. if len(paramslist) > 0 && p1 != "" {
  1150. for _, value := range paramslist {
  1151. // if value == "ID" {
  1152. // id := parammaps.Get("ID").ValueStr()
  1153. // pastureid := parammaps.Get("pastureid").ValueStr()
  1154. // 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
  1155. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1156. // if err != nil {
  1157. // logging.Error("PostRJSBData err: ", err)
  1158. // msg := geterrmsg(err.Error())
  1159. // appG.Response(http.StatusOK, e.ERROR, msg)
  1160. // return
  1161. // }
  1162. // for _, item := range datalist {
  1163. // id = item["id"]
  1164. // }
  1165. // s_params = append(s_params, id)
  1166. // } else {
  1167. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1168. // }
  1169. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1170. }
  1171. }
  1172. _, err = tx.SQL(sql1, s_params...).Execute()
  1173. if err != nil {
  1174. logging.Error("PostRJSBData1 err: ", err)
  1175. msg := geterrmsg(err.Error())
  1176. appG.Response(http.StatusOK, e.ERROR, msg)
  1177. return
  1178. }
  1179. s_params = make([]interface{}, 0)
  1180. paramslist = strings.Split(p2, ",")
  1181. if len(paramslist) > 0 && p2 != "" {
  1182. for _, value := range paramslist {
  1183. if value == "ID" {
  1184. id := parammaps.Get("ID").ValueStr()
  1185. pastureid := parammaps.Get("pastureid").ValueStr()
  1186. 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
  1187. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1188. if err != nil {
  1189. logging.Error("PostRJSBData err: ", err)
  1190. msg := geterrmsg(err.Error())
  1191. appG.Response(http.StatusOK, e.ERROR, msg)
  1192. return
  1193. }
  1194. for _, item := range datalist {
  1195. id = item["id"]
  1196. }
  1197. s_params = append(s_params, id)
  1198. } else {
  1199. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1200. }
  1201. }
  1202. }
  1203. _, err = tx.SQL(sql2, s_params...).Execute()
  1204. if err != nil {
  1205. logging.Error("PostRJSBData2 err: ", err)
  1206. msg := geterrmsg(err.Error())
  1207. appG.Response(http.StatusOK, e.ERROR, msg)
  1208. return
  1209. }
  1210. s_params = make([]interface{}, 0)
  1211. paramslist = strings.Split(p3, ",")
  1212. if len(paramslist) > 0 && p3 != "" {
  1213. for _, value := range paramslist {
  1214. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1215. }
  1216. }
  1217. _, err = tx.SQL(sql3, s_params...).Execute()
  1218. if err != nil {
  1219. logging.Error("PostRJSBData3 err: ", err)
  1220. msg := geterrmsg(err.Error())
  1221. appG.Response(http.StatusOK, e.ERROR, msg)
  1222. return
  1223. }
  1224. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1225. }
  1226. func PostRJSBDatas(c *gin.Context) {
  1227. appG := app.Gin{C: c}
  1228. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1229. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1230. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1231. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1232. tx := restful.Engine.NewSession()
  1233. err := tx.Begin()
  1234. defer func() {
  1235. switch {
  1236. case err != nil:
  1237. if tx != nil {
  1238. tx.Rollback()
  1239. }
  1240. default:
  1241. if tx != nil {
  1242. err = tx.Commit()
  1243. }
  1244. }
  1245. if tx != nil {
  1246. tx.Close()
  1247. }
  1248. }()
  1249. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1250. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1251. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1252. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1253. for _, fsion := range fsions {
  1254. if !fsion.HasKey("parammaps") {
  1255. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1256. return
  1257. }
  1258. parammaps := fsion.Get("parammaps")
  1259. ID := parammaps.Get("ID").ValueStr()
  1260. if ID == "" {
  1261. continue
  1262. }
  1263. s_params := make([]interface{}, 0)
  1264. paramslist := strings.Split(p, ",")
  1265. if len(paramslist) > 0 && p != "" {
  1266. for _, value := range paramslist {
  1267. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1268. }
  1269. }
  1270. _, err := tx.SQL(sql, s_params...).Execute()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData 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. s_params = make([]interface{}, 0)
  1279. paramslist = strings.Split(p1, ",")
  1280. if len(paramslist) > 0 && p1 != "" {
  1281. for _, value := range paramslist {
  1282. // if value == "ID" {
  1283. // id := parammaps.Get("ID").ValueStr()
  1284. // pastureid := parammaps.Get("pastureid").ValueStr()
  1285. // 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
  1286. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1287. // if err != nil {
  1288. // logging.Error("PostRJSBData err: ", err)
  1289. // msg := geterrmsg(err.Error())
  1290. // appG.Response(http.StatusOK, e.ERROR, msg)
  1291. // return
  1292. // }
  1293. // for _, item := range datalist {
  1294. // id = item["id"]
  1295. // }
  1296. // s_params = append(s_params, id)
  1297. // } else {
  1298. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1299. // }
  1300. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1301. }
  1302. }
  1303. _, err = tx.SQL(sql1, s_params...).Execute()
  1304. if err != nil {
  1305. logging.Error("PostRJSBData1 err: ", err)
  1306. msg := geterrmsg(err.Error())
  1307. appG.Response(http.StatusOK, e.ERROR, msg)
  1308. return
  1309. }
  1310. s_params = make([]interface{}, 0)
  1311. paramslist = strings.Split(p2, ",")
  1312. if len(paramslist) > 0 && p2 != "" {
  1313. for _, value := range paramslist {
  1314. if value == "ID" {
  1315. id := parammaps.Get("ID").ValueStr()
  1316. pastureid := parammaps.Get("pastureid").ValueStr()
  1317. 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
  1318. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1319. if err != nil {
  1320. logging.Error("PostRJSBData err: ", err)
  1321. msg := geterrmsg(err.Error())
  1322. appG.Response(http.StatusOK, e.ERROR, msg)
  1323. return
  1324. }
  1325. for _, item := range datalist {
  1326. id = item["id"]
  1327. }
  1328. s_params = append(s_params, id)
  1329. } else {
  1330. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1331. }
  1332. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1333. }
  1334. }
  1335. _, err = tx.SQL(sql2, s_params...).Execute()
  1336. if err != nil {
  1337. logging.Error("PostRJSBData2 err: ", err)
  1338. msg := geterrmsg(err.Error())
  1339. appG.Response(http.StatusOK, e.ERROR, msg)
  1340. return
  1341. }
  1342. s_params = make([]interface{}, 0)
  1343. paramslist = strings.Split(p3, ",")
  1344. if len(paramslist) > 0 && p3 != "" {
  1345. for _, value := range paramslist {
  1346. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1347. }
  1348. }
  1349. _, err = tx.SQL(sql3, s_params...).Execute()
  1350. if err != nil {
  1351. logging.Error("PostRJSBData3 err: ", err)
  1352. msg := geterrmsg(err.Error())
  1353. appG.Response(http.StatusOK, e.ERROR, msg)
  1354. return
  1355. }
  1356. // ALTER TABLE `tmr`
  1357. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1358. projuctid := parammaps.Get("projuctid").ValueStr()
  1359. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1360. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1361. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1362. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1363. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1364. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1365. if err != nil {
  1366. logging.Error("PostRJSBData-0 err: ", err)
  1367. msg := geterrmsg(err.Error())
  1368. // appG.Response(http.StatusOK, e.ERROR, msg)
  1369. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1370. return
  1371. }
  1372. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1373. if count == 0 {
  1374. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1375. }
  1376. }
  1377. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1378. }
  1379. // @Summary 根据APISQL表中SQL执行得到数据集
  1380. // @Tags ExecDataByConfig
  1381. // @Accept json
  1382. // @Produce json
  1383. // @Param sqlname query string true "sqlname"
  1384. // @Param offset query int true "offset"
  1385. // @Param pagecount query int true "pagecount"
  1386. // @Param returntype query string true "returntype"
  1387. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1388. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1389. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1390. // @Router /data/PostDataByName [POST]
  1391. func ExecDataByConfig(c *gin.Context) {
  1392. appG := app.Gin{C: c}
  1393. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1394. tempval_ := make(map[string]interface{})
  1395. tempCommon := make(map[string]interface{})
  1396. tempval := make([]map[string]interface{}, 0)
  1397. err := json.Unmarshal(dataByte, &tempval_)
  1398. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1399. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1400. if err != nil {
  1401. } else {
  1402. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1403. tempCommon = v
  1404. }
  1405. if v, ok := tempval_["data"].([]interface{}); ok {
  1406. for _, Tvalue := range v {
  1407. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1408. tempval = append(tempval, v1)
  1409. }
  1410. }
  1411. }
  1412. tx := restful.Engine.NewSession()
  1413. err := tx.Begin()
  1414. if err != nil {
  1415. logging.Error("tx.Begin 事务启动失败__error:", err)
  1416. }
  1417. defer func() {
  1418. switch {
  1419. case err != nil:
  1420. if tx != nil {
  1421. tx.Rollback()
  1422. }
  1423. default:
  1424. if tx != nil {
  1425. err = tx.Commit()
  1426. }
  1427. }
  1428. if tx != nil {
  1429. tx.Close()
  1430. }
  1431. }()
  1432. if err == nil {
  1433. if tempv, exists := c.Get("jwt_username"); exists {
  1434. tempCommon["jwt_username"] = tempv.(string)
  1435. }
  1436. for _, paramvalue := range tempval {
  1437. fmt.Println(paramvalue["name"])
  1438. if paramvalue["name"].(string) == "updateBigFP" {
  1439. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1440. if err != nil {
  1441. msg := geterrmsg(err.Error())
  1442. appG.Response(http.StatusOK, e.ERROR, msg)
  1443. return
  1444. }
  1445. }
  1446. }
  1447. for _, paramvalue := range tempval {
  1448. if _, ok := paramvalue["resultname"]; !ok {
  1449. paramvalue["resultname"] = paramvalue["name"]
  1450. }
  1451. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1452. if err != nil {
  1453. logging.Error("ExecDataParam error:", err)
  1454. break
  1455. }
  1456. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1457. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1458. // }
  1459. }
  1460. if err == nil {
  1461. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1462. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1463. } else {
  1464. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1465. }
  1466. } else {
  1467. msg := geterrmsg(err.Error())
  1468. appG.Response(http.StatusOK, e.ERROR, msg)
  1469. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1470. }
  1471. }
  1472. }
  1473. if err != nil {
  1474. msg := geterrmsg(err.Error())
  1475. appG.Response(http.StatusOK, e.ERROR, msg)
  1476. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1477. }
  1478. }
  1479. func interfacetostring(val interface{}) string {
  1480. switch val.(type) {
  1481. case string:
  1482. ss := val.(string)
  1483. return ss
  1484. break
  1485. case int:
  1486. ss := val.(int)
  1487. return strconv.Itoa(ss)
  1488. break
  1489. case int64:
  1490. ss := val.(int64)
  1491. return strconv.FormatInt(ss, 10)
  1492. break
  1493. case float64:
  1494. ss := val.(float64)
  1495. return strconv.FormatFloat(ss, 'E', -1, 32)
  1496. break
  1497. }
  1498. return ""
  1499. }
  1500. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1501. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1502. tempstrb := strings.IndexAny(valuestring, "@")
  1503. tempstre := strings.IndexAny(valuestring, ".")
  1504. if tempstrb > -1 && tempstre > -1 {
  1505. for _, ParamMapList := range ParamMap {
  1506. if v, ok := ParamMapList["resultname"]; ok {
  1507. if v == valuestring[tempstrb+1:tempstre] {
  1508. if v1, ok := ParamMapList["resultmaps"]; ok {
  1509. if newA, ok := v1.([]map[string]interface{}); ok {
  1510. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1511. } else if newA, ok := v1.(map[string]interface{}); ok {
  1512. return interfacetostring(newA[valuestring[tempstre+1:]])
  1513. }
  1514. }
  1515. }
  1516. }
  1517. }
  1518. } else {
  1519. return valuestring
  1520. }
  1521. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1522. return fmt.Sprintf("%f", valuestring)
  1523. }
  1524. return ""
  1525. }
  1526. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1527. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1528. tempstrb := strings.IndexAny(valuestring, "@")
  1529. tempstre := strings.IndexAny(valuestring, ".")
  1530. if tempstrb > -1 && tempstre > -1 {
  1531. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1532. if s, ok := v.(string); ok {
  1533. return s
  1534. } else if s, ok := v.(float64); ok {
  1535. return strconv.FormatFloat(s, 'f', -1, 64)
  1536. // return strconv.FormatInt(int64(s), 10)
  1537. }
  1538. }
  1539. }
  1540. }
  1541. return ""
  1542. }
  1543. 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) {
  1544. sqlname := fasion["name"].(string)
  1545. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1546. if v, ok := fasion["type"]; ok {
  1547. sqltype = v.(string)
  1548. }
  1549. sql := ""
  1550. p := ""
  1551. s_params := make([]interface{}, 0)
  1552. if sqltype != "" {
  1553. sql, p = restful.GetSqlByName(sqlname, tx)
  1554. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1555. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1556. paramslist := strings.Split(p, ",")
  1557. if len(paramslist) > 0 && p != "" {
  1558. for _, value := range paramslist {
  1559. ss := ""
  1560. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1561. ids, err := setting.SnowIds.NextId()
  1562. if err != nil {
  1563. ids = time.Now().UnixNano()
  1564. logging.Info("create SnowIds err", err)
  1565. }
  1566. s_params = append(s_params, ids)
  1567. } else {
  1568. if ss == "" && CommonParamMap != nil {
  1569. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1570. ss = valuestring
  1571. tempstrb := strings.IndexAny(valuestring, "@")
  1572. tempstre := strings.IndexAny(valuestring, ".")
  1573. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1574. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1575. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1576. }
  1577. } else {
  1578. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1579. ss = ""
  1580. }
  1581. }
  1582. }
  1583. }
  1584. if ss == "" && ParentParamMap != nil {
  1585. ss = getParamValue_(v, value, ParentParamMap)
  1586. }
  1587. if ss == "" && sameParamMap != nil {
  1588. ss = getParamValue(v, value, sameParamMap)
  1589. }
  1590. if ss == "" && ParamMap != nil {
  1591. ss = getParamValue(v, value, ParamMap)
  1592. }
  1593. s_params = append(s_params, ss)
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. if sql == "" {
  1600. sqltype = ""
  1601. }
  1602. if sqltype == "s1" {
  1603. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1604. if v, ok := tempValParam.(map[string]interface{}); ok {
  1605. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1606. }
  1607. if err != nil {
  1608. return nil, err
  1609. }
  1610. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1611. if err != nil {
  1612. return nil, err
  1613. }
  1614. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1615. } else if sqltype == "sm" {
  1616. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1617. if v, ok := tempValParam.(map[string]interface{}); ok {
  1618. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1619. } else {
  1620. }
  1621. if err != nil {
  1622. return nil, err
  1623. }
  1624. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1625. if err != nil {
  1626. return nil, err
  1627. }
  1628. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1629. } else if sqltype == "v" {
  1630. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1631. if v, ok := tempValParam.(map[string]interface{}); ok {
  1632. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1633. } else {
  1634. }
  1635. if err != nil {
  1636. return nil, err
  1637. }
  1638. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1639. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1640. }
  1641. } else if sqltype == "e" {
  1642. tempVal_arrary := make([]map[string]interface{}, 0)
  1643. tempVal_map := make(map[string]interface{})
  1644. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1645. if err == nil {
  1646. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1647. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1648. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1649. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1650. return tempVal_arrary, err
  1651. }
  1652. return nil, err
  1653. } else {
  1654. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1655. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1656. if err != nil {
  1657. return nil, err
  1658. }
  1659. return nil, err
  1660. }
  1661. }
  1662. return nil, nil
  1663. }
  1664. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1665. var err error
  1666. subarray, ok := fasion["children"]
  1667. if ok {
  1668. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1669. tempVal_arrary := make([]map[string]interface{}, 0)
  1670. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1671. tempVal_ := make(map[string]interface{})
  1672. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1673. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1674. } else {
  1675. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1676. }
  1677. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1678. if err != nil {
  1679. return err
  1680. }
  1681. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1682. }
  1683. v.(map[string]interface{})["children"] = tempVal_arrary
  1684. }
  1685. }
  1686. return nil
  1687. }
  1688. // @Summary 删除图片
  1689. // @Tags RemovePicByName
  1690. // @Accept json
  1691. // @Produce json
  1692. // @Param sqlname query string true "sqlname"
  1693. // @Param offset query int true "offset"
  1694. // @Param pagecount query int true "pagecount"
  1695. // @Param returntype query string true "returntype"
  1696. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1697. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1698. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1699. // @Router /data/PostDataByName [POST]
  1700. func RemovePicByName(c *gin.Context) {
  1701. logging.Info("RemovePicByName ", c.Keys)
  1702. appG := app.Gin{C: c}
  1703. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1704. fsion := gofasion.NewFasion(string(dataByte))
  1705. sqlnamestr := fsion.Get("name").ValueStr()
  1706. picname := fsion.Get("picname").ValueStr()
  1707. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1708. params := fsion.Get("params").Array()
  1709. s_params := make([]interface{}, 0)
  1710. for _, v_params := range params {
  1711. s_params = append(s_params, v_params.ValueStr())
  1712. }
  1713. if sql != "" {
  1714. queryData, err := execDataBySql(sql, s_params)
  1715. if picname != "" {
  1716. // Destination
  1717. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1718. err := os.Remove(distPath) //删除文件test.txt
  1719. if err != nil {
  1720. //如果删除失败则输出 file remove Error!
  1721. fmt.Println("file remove Error!")
  1722. //输出错误详细信息
  1723. fmt.Printf("%s", err)
  1724. } else {
  1725. //如果删除成功则输出 file remove OK!
  1726. fmt.Print("file remove OK!")
  1727. }
  1728. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1729. err = os.Remove(distPath) //删除文件test.txt
  1730. if err != nil {
  1731. //如果删除失败则输出 file remove Error!
  1732. fmt.Println("file remove Error!")
  1733. //输出错误详细信息
  1734. fmt.Printf("%s", err)
  1735. } else {
  1736. //如果删除成功则输出 file remove OK!
  1737. fmt.Print("file remove OK!")
  1738. }
  1739. }
  1740. if err != nil {
  1741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1742. } else {
  1743. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1744. }
  1745. } else {
  1746. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1747. }
  1748. }
  1749. // @Summary 删除文件
  1750. // @Tags RemoveFileByName
  1751. // @Accept json
  1752. // @Produce json
  1753. // @Param sqlname query string true "sqlname"
  1754. // @Param offset query int true "offset"
  1755. // @Param pagecount query int true "pagecount"
  1756. // @Param returntype query string true "returntype"
  1757. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1758. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1759. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1760. // @Router /data/PostDataByName [POST]
  1761. func RemoveFileByName(c *gin.Context) {
  1762. appG := app.Gin{C: c}
  1763. id := c.Param("id")
  1764. logging.Info("DownloadFile ", c.Keys, id)
  1765. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1766. if eqdoc == nil {
  1767. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1768. return
  1769. }
  1770. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1771. err = os.Remove(distPath) //删除文件test.txt
  1772. if err != nil {
  1773. //如果删除失败则输出 file remove Error!
  1774. fmt.Println("file remove Error!")
  1775. //输出错误详细信息
  1776. fmt.Printf("%s", err)
  1777. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1778. return
  1779. }
  1780. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1781. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1782. }
  1783. // @Summary 根据APISQL表中SQL执行得到数据集
  1784. // @Tags PostDataByName
  1785. // @Accept json
  1786. // @Produce json
  1787. // @Param sqlname query string true "sqlname"
  1788. // @Param offset query int true "offset"
  1789. // @Param pagecount query int true "pagecount"
  1790. // @Param returntype query string true "returntype"
  1791. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1792. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1793. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1794. // @Router /data/PostDataByName [POST]
  1795. func UpdateDataRelation(c *gin.Context) {
  1796. appG := app.Gin{C: c}
  1797. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1798. fsion := gofasion.NewFasion(string(dataByte))
  1799. tablename := fsion.Get("name").ValueStr()
  1800. dataname := fsion.Get("dataname").ValueStr()
  1801. datavalue := fsion.Get("datavalue").ValueStr()
  1802. valuename := fsion.Get("valuename").ValueStr()
  1803. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1804. values := fsion.Get("values").Array()
  1805. tx := restful.Engine.NewSession()
  1806. err := tx.Begin()
  1807. defer func() {
  1808. switch {
  1809. case err != nil:
  1810. if tx != nil {
  1811. tx.Rollback()
  1812. }
  1813. default:
  1814. if tx != nil {
  1815. err = tx.Commit()
  1816. }
  1817. }
  1818. if tx != nil {
  1819. tx.Close()
  1820. }
  1821. }()
  1822. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1823. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1824. d_params := make([]interface{}, 4)
  1825. d_params[0] = datavalue
  1826. s_params := ""
  1827. for _, v_values := range values {
  1828. d_params[1] = v_values.ValueStr()
  1829. if s_params == "" {
  1830. s_params = v_values.ValueStr()
  1831. } else {
  1832. s_params = s_params + "," + v_values.ValueStr()
  1833. }
  1834. d_params[2] = d_params[1]
  1835. d_params[3] = d_params[0]
  1836. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1837. if err != nil {
  1838. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1839. break
  1840. }
  1841. }
  1842. if s_params != "" {
  1843. deleteSqlstr := "delete from " + tablename + " " +
  1844. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1845. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1846. if err != nil {
  1847. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1848. } else if err == nil {
  1849. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1850. }
  1851. } else {
  1852. deleteSqlstr := "delete from " + tablename + " " +
  1853. " where " + dataname + " = " + datavalue
  1854. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1855. if err != nil {
  1856. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1857. } else if err == nil {
  1858. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1859. }
  1860. }
  1861. }
  1862. // @Summary 根据APISQL表中SQL执行得到数据集
  1863. // @Tags PostDatasByName
  1864. // @Accept json
  1865. // @Produce json
  1866. // @Param sqlname query string true "sqlname"
  1867. // @Param offset query int true "offset"
  1868. // @Param pagecount query int true "pagecount"
  1869. // @Param returntype query string true "returntype"
  1870. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1871. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1872. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1873. // @Router /data/PostDatasByName [POST]
  1874. func PostDataByNames(c *gin.Context) {
  1875. appG := app.Gin{C: c}
  1876. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1877. fsion := gofasion.NewFasion(string(dataByte))
  1878. sqlParams := fsion.Get("array").Array()
  1879. queryData := make(map[string]interface{})
  1880. for _, v := range sqlParams {
  1881. fsion2 := gofasion.NewFasion(v.Json())
  1882. ss := fsion2.Get("name")
  1883. aa := fsion2.Get("params")
  1884. fmt.Println(ss, aa)
  1885. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1886. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1887. if sql == "" {
  1888. errorm := make(map[string]interface{})
  1889. errorm["code"] = e.ERROR
  1890. errorm["message"] = "sql没有找到"
  1891. errorm["param"] = ""
  1892. queryData[fsion2.Get("name").ValueStr()] = errorm
  1893. continue
  1894. } else if sql != "" {
  1895. s_params := make([]interface{}, 0)
  1896. if fsion2.HasKey("parammaps") {
  1897. parammaps := fsion2.Get("parammaps")
  1898. paramslist := strings.Split(p, ",")
  1899. if len(paramslist) > 0 && p != "" {
  1900. for _, value := range paramslist {
  1901. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1902. if tempv, exists := c.Get("jwt_username"); exists {
  1903. s_params = append(s_params, tempv.(string))
  1904. } else {
  1905. s_params = append(s_params, "")
  1906. }
  1907. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1908. ids, err := setting.SnowIds.NextId()
  1909. if err != nil {
  1910. ids = time.Now().UnixNano()
  1911. logging.Info("create SnowIds err", err)
  1912. }
  1913. s_params = append(s_params, ids)
  1914. } else {
  1915. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1916. }
  1917. }
  1918. }
  1919. } else if fsion2.HasKey("params") {
  1920. params := fsion2.Get("params").Array()
  1921. //ids,err := setting.SnowIds.NextId()
  1922. //if err !=nil{
  1923. // ids = time.Now().UnixNano()
  1924. // logging.Info("create SnowIds err",err)
  1925. //}
  1926. //s_params = append(s_params, ids)
  1927. for _, v_params := range params {
  1928. s_params = append(s_params, v_params.ValueStr())
  1929. }
  1930. }
  1931. _, err := execDataBySql(sql, s_params)
  1932. if err != nil {
  1933. logging.Error("PostDataByName err: ", err)
  1934. errorm := make(map[string]interface{})
  1935. errorm["code"] = e.ERROR
  1936. errorm["message"] = err.Error()
  1937. errorm["param"] = s_params
  1938. queryData[fsion2.Get("name").ValueStr()] = errorm
  1939. continue
  1940. } else {
  1941. errorm := make(map[string]interface{})
  1942. errorm["code"] = e.SUCCESS
  1943. errorm["message"] = "success"
  1944. queryData[fsion2.Get("name").ValueStr()] = errorm
  1945. continue
  1946. }
  1947. } else {
  1948. errorm := make(map[string]interface{})
  1949. errorm["code"] = e.ERROR
  1950. errorm["message"] = "NO SQL"
  1951. errorm["param"] = ""
  1952. queryData[fsion2.Get("name").ValueStr()] = errorm
  1953. }
  1954. }
  1955. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1956. }
  1957. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1958. if offset > 0 {
  1959. offset = offset - 1
  1960. }
  1961. //if pagecount == 0 {
  1962. // pagecount = setting.AppSetting.PageSize
  1963. //}else if pagecount>setting.AppSetting.PageSize{
  1964. // pagecount = setting.AppSetting.PageSize
  1965. //}
  1966. if returntype == "list" {
  1967. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1968. return queryData, err
  1969. } else if returntype == "listlist" {
  1970. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1971. return queryData, err
  1972. } else {
  1973. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1974. return queryData, err
  1975. }
  1976. }
  1977. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1978. if offset > 0 {
  1979. offset = offset - 1
  1980. }
  1981. //if pagecount == 0 {
  1982. // pagecount = setting.AppSetting.PageSize
  1983. //}else if pagecount>setting.AppSetting.PageSize{
  1984. // pagecount = setting.AppSetting.PageSize
  1985. //}
  1986. if returntype == "list" {
  1987. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1988. return queryData, err
  1989. } else if returntype == "listlist" {
  1990. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1991. return queryData, err
  1992. } else {
  1993. fmt.Println(params)
  1994. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1995. return queryData, err
  1996. }
  1997. }
  1998. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1999. paramslist := strings.Split(Params, ",")
  2000. s_params := make([]interface{}, 0)
  2001. if isList {
  2002. for _, v_params := range thisParams["params"].([]interface{}) {
  2003. s_params = append(s_params, v_params)
  2004. }
  2005. } else {
  2006. paramslist := strings.Split(Params, ",")
  2007. if len(paramslist) > 0 && Params != "" {
  2008. for _, value := range paramslist {
  2009. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2010. }
  2011. }
  2012. }
  2013. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2014. for _, queryData_ := range queryData {
  2015. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2016. if isList {
  2017. if queryData_[idname] != nil {
  2018. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2019. }
  2020. } else {
  2021. if queryData_[idname] != nil {
  2022. thisParams[idname] = queryData_[idname].(interface{})
  2023. }
  2024. if len(paramslist) > 0 && Params != "" {
  2025. s_params = make([]interface{}, 0)
  2026. for _, value := range paramslist {
  2027. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2028. }
  2029. }
  2030. }
  2031. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2032. } else {
  2033. }
  2034. }
  2035. return queryData, err
  2036. }
  2037. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2038. queryData, err := restful.ExecQuery(sqlstr, params)
  2039. return queryData, err
  2040. }
  2041. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2042. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2043. return queryData, err
  2044. }
  2045. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2046. queryData, err := restful.ExecQuery(sqlstr, params)
  2047. return queryData, err
  2048. }
  2049. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2050. // @Tags ImportExcel
  2051. // @Accept json
  2052. // @Produce json
  2053. // @Param file query string true "文件名"
  2054. // @Param name header string true "执行sql的名字"
  2055. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2056. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2057. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2058. // @Router /data/ImportExcel [POST]
  2059. func ImportExcel(c *gin.Context) {
  2060. appG := app.Gin{C: c}
  2061. inputdata := ""
  2062. c.Request.ParseForm()
  2063. params := c.Request.Form
  2064. file, _, err := c.Request.FormFile("file")
  2065. if err != nil {
  2066. appG.Response(http.StatusOK, e.ERROR, err)
  2067. return
  2068. }
  2069. sqlnamestrs := params.Get("name")
  2070. sheetname := params.Get("sheetname")
  2071. pastureid := params.Get("pastureid")
  2072. //importParams := params.Get("importParams")
  2073. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2074. // 必输项参数 (字符串格式 "field1,field2,field3")
  2075. requiredParams := params.Get("requiredParams")
  2076. // 日期参数
  2077. dateParams := params.Get("dateParams")
  2078. // 数字参数
  2079. numParams := params.Get("numParams")
  2080. //将字符串分割开
  2081. dateParamslist := strings.Split(dateParams, ",")
  2082. requiredParamslist := strings.Split(requiredParams, ",")
  2083. numParamslist := strings.Split(numParams, ",")
  2084. queryData := make([]interface{}, 0)
  2085. sqlslist := strings.Split(sqlnamestrs, ",")
  2086. xlsx1, err := excelize.OpenReader(file)
  2087. if err != nil {
  2088. fmt.Println(err)
  2089. return
  2090. }
  2091. ok := 0
  2092. error := 0
  2093. isdone := true
  2094. rows := xlsx1.GetRows(sheetname)
  2095. // 限制10000条,多余的截取掉
  2096. if len(rows) > 10000 {
  2097. rows = rows[:10000]
  2098. }
  2099. for i, row := range rows {
  2100. if i > 0 {
  2101. entry := make(map[string]interface{})
  2102. outentry := make(map[string]interface{})
  2103. for j, colCell := range rows[0] {
  2104. for k, colCell1 := range row {
  2105. if j == k {
  2106. outentry[colCell] = colCell1
  2107. entry[colCell] = colCell1
  2108. }
  2109. }
  2110. }
  2111. inputdata = ""
  2112. a := ""
  2113. fmt.Println(outentry, entry)
  2114. //校验日期格式
  2115. for _, v := range dateParamslist {
  2116. if v == "" {
  2117. continue
  2118. }
  2119. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2120. dtime, err := TransfTime(d.(string))
  2121. if err != nil {
  2122. a = strings.Trim(v, " ")
  2123. break
  2124. }
  2125. outentry[strings.Trim(v, " ")] = dtime
  2126. }
  2127. }
  2128. if a != "" {
  2129. outentry["error_msg"] = a + " 格式错误"
  2130. error++
  2131. queryData = append(queryData, outentry)
  2132. continue
  2133. }
  2134. a = ""
  2135. //校验必填格式
  2136. for _, v := range requiredParamslist {
  2137. if v == "" {
  2138. continue
  2139. }
  2140. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2141. a = strings.Trim(v, " ")
  2142. break
  2143. }
  2144. }
  2145. if a != "" {
  2146. outentry["error_msg"] = a + " 未填或格式错误"
  2147. error++
  2148. queryData = append(queryData, outentry)
  2149. continue
  2150. }
  2151. a = ""
  2152. //校验数字格式
  2153. for _, v := range numParamslist {
  2154. if v == "" {
  2155. continue
  2156. }
  2157. d, ok := outentry[strings.Trim(v, " ")]
  2158. if !ok || d == "" {
  2159. outentry[strings.Trim(v, " ")] = 0
  2160. } else {
  2161. var fl float64
  2162. switch d.(type) {
  2163. case string:
  2164. fl, err = strconv.ParseFloat(d.(string), 64)
  2165. }
  2166. if err != nil || fl < 0 {
  2167. a = strings.Trim(v, " ")
  2168. break
  2169. }
  2170. }
  2171. }
  2172. if a != "" {
  2173. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2174. error++
  2175. queryData = append(queryData, outentry)
  2176. continue
  2177. }
  2178. tx := restful.Engine.NewSession()
  2179. err := tx.Begin()
  2180. for _, sqlnamestr := range sqlslist {
  2181. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2182. paramslist := strings.Split(paramslists, ",")
  2183. if len(paramslist) > 0 {
  2184. s_params := make([]interface{}, 0)
  2185. for _, value := range paramslist {
  2186. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2187. if tempv, exists := c.Get("jwt_username"); exists {
  2188. s_params = append(s_params, tempv.(string))
  2189. } else {
  2190. s_params = append(s_params, "")
  2191. }
  2192. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2193. s_params = append(s_params, pastureid)
  2194. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2195. ids, err := setting.SnowIds.NextId()
  2196. if err != nil {
  2197. ids = time.Now().UnixNano()
  2198. logging.Info("create SnowIds err", err)
  2199. }
  2200. s_params = append(s_params, ids)
  2201. } else {
  2202. if outentry[strings.Trim(value, " ")] == nil {
  2203. s_params = append(s_params, "")
  2204. } else {
  2205. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2206. }
  2207. }
  2208. }
  2209. outentry["input"] = inputdata
  2210. fmt.Println(sql, s_params)
  2211. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2212. if err != nil {
  2213. if tx != nil {
  2214. tx.Rollback()
  2215. }
  2216. if tx != nil {
  2217. tx.Close()
  2218. }
  2219. msg := geterrmsg(err.Error())
  2220. outentry["error_msg"] = msg
  2221. error++
  2222. queryData = append(queryData, outentry)
  2223. isdone = true
  2224. break
  2225. } else {
  2226. if len(returnmsgmap1) > 0 {
  2227. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2228. if tx != nil {
  2229. tx.Rollback()
  2230. }
  2231. if tx != nil {
  2232. tx.Close()
  2233. }
  2234. msg := geterrmsg(va.(string))
  2235. outentry["error_msg"] = msg
  2236. error++
  2237. queryData = append(queryData, outentry)
  2238. isdone = true
  2239. break
  2240. }
  2241. }
  2242. isdone = false
  2243. }
  2244. }
  2245. }
  2246. switch {
  2247. case err != nil:
  2248. if tx != nil {
  2249. tx.Rollback()
  2250. }
  2251. default:
  2252. if tx != nil {
  2253. err = tx.Commit()
  2254. }
  2255. }
  2256. if tx != nil {
  2257. tx.Close()
  2258. }
  2259. }
  2260. if !isdone {
  2261. ok++
  2262. isdone = true
  2263. }
  2264. }
  2265. data := make(map[string]interface{})
  2266. data["result"] = queryData
  2267. data["success"] = ok
  2268. data["err_count"] = error
  2269. appG.Response(http.StatusOK, e.SUCCESS, data)
  2270. }
  2271. func TransfTime(timestr string) (string, error) {
  2272. if timestr == "" {
  2273. return time.Now().Format("2006-01-02"), nil
  2274. }
  2275. days, err := strconv.Atoi(timestr)
  2276. if err != nil {
  2277. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2278. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2279. }
  2280. _, err := time.Parse("2006-01-02", timestr)
  2281. if err != nil {
  2282. t, err := time.Parse("2006/01/02", timestr)
  2283. if err != nil {
  2284. t, err := time.Parse("2006.01.02", timestr)
  2285. if err != nil {
  2286. return "", err
  2287. } else {
  2288. return t.Format("2006-01-02"), nil
  2289. }
  2290. } else {
  2291. return t.Format("2006-01-02"), nil
  2292. }
  2293. } else {
  2294. return timestr, nil
  2295. }
  2296. }
  2297. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2298. times = times.AddDate(0, 0, days)
  2299. return times.Format("2006-01-02"), nil
  2300. }
  2301. func Createchart(c *gin.Context) {
  2302. appG := app.Gin{C: c}
  2303. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2304. fsion := gofasion.NewFasion(string(dataByte))
  2305. chart_name := fsion.Get("chart_name").ValueStr()
  2306. desc := fsion.Get("desc").ValueStr()
  2307. pastureid := fsion.Get("pastureid").ValueStr()
  2308. source_id := fsion.Get("source_id").ValueStr()
  2309. emp := fsion.Get("emp").ValueStr()
  2310. content := fsion.Get("content").Json()
  2311. var mapResult map[string]interface{}
  2312. err1 := json.Unmarshal([]byte(content), &mapResult)
  2313. if err1 != nil {
  2314. fmt.Println("JsonToMapDemo err: ", err1)
  2315. }
  2316. tx := restful.Engine.NewSession()
  2317. err := tx.Begin()
  2318. defer func() {
  2319. switch {
  2320. case err != nil:
  2321. logging.Error("tx.Begin 事务启动失败__error:", err)
  2322. if tx != nil {
  2323. tx.Rollback()
  2324. }
  2325. default:
  2326. if tx != nil {
  2327. err = tx.Commit()
  2328. }
  2329. }
  2330. if tx != nil {
  2331. tx.Close()
  2332. }
  2333. }()
  2334. ids, err := setting.SnowIds.NextId()
  2335. if err != nil {
  2336. ids = time.Now().UnixNano()
  2337. logging.Info("create SnowIds err", err)
  2338. }
  2339. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2340. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2341. if err != nil {
  2342. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2343. } else {
  2344. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2345. }
  2346. }
  2347. func Updatedashboard(c *gin.Context) {
  2348. appG := app.Gin{C: c}
  2349. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2350. fsion := gofasion.NewFasion(string(dataByte))
  2351. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2352. pastureid := fsion.Get("pastureid").ValueStr()
  2353. content := fsion.Get("content").Json()
  2354. var mapResult map[string]interface{}
  2355. err1 := json.Unmarshal([]byte(content), &mapResult)
  2356. if err1 != nil {
  2357. fmt.Println("JsonToMapDemo err: ", err1)
  2358. }
  2359. layout := mapResult["layout"]
  2360. tx := restful.Engine.NewSession()
  2361. err := tx.Begin()
  2362. defer func() {
  2363. switch {
  2364. case err != nil:
  2365. logging.Error("tx.Begin 事务启动失败__error:", err)
  2366. if tx != nil {
  2367. tx.Rollback()
  2368. }
  2369. default:
  2370. if tx != nil {
  2371. err = tx.Commit()
  2372. }
  2373. }
  2374. if tx != nil {
  2375. tx.Close()
  2376. }
  2377. }()
  2378. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2379. if err != nil {
  2380. println("2", err.Error())
  2381. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2382. } else {
  2383. if exec != nil {
  2384. if exec[0]["content"] == nil {
  2385. mapR := make(map[string]interface{})
  2386. mapR["layout"] = layout
  2387. mjson, _ := json.Marshal(mapR)
  2388. mString := string(mjson)
  2389. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2390. if err3 != nil {
  2391. println("3", err3.Error())
  2392. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2393. } else {
  2394. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2395. }
  2396. } else {
  2397. var mapR map[string]interface{}
  2398. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2399. if err1 != nil {
  2400. fmt.Println("JsonToMapDemo err: ", err2)
  2401. }
  2402. mapR["layout"] = layout
  2403. mjson, _ := json.Marshal(mapR)
  2404. mString := string(mjson)
  2405. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2406. if err3 != nil {
  2407. println("3", err3.Error())
  2408. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2409. } else {
  2410. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2411. }
  2412. }
  2413. } else {
  2414. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2415. }
  2416. }
  2417. }
  2418. func ExecSQL(c *gin.Context) {
  2419. appG := app.Gin{C: c}
  2420. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2421. fsion := gofasion.NewFasion(string(dataByte))
  2422. content := fsion.Get("content").Json()
  2423. pastureid := fsion.Get("pastureid").ValueStr()
  2424. var mapResult map[string]interface{}
  2425. err1 := json.Unmarshal([]byte(content), &mapResult)
  2426. if err1 != nil {
  2427. fmt.Println("JsonToMapDemo err: ", err1)
  2428. }
  2429. sqlstr := "select "
  2430. groupstr := " GROUP BY "
  2431. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2432. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2433. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2434. }
  2435. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2436. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2437. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2438. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2439. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2440. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2441. sqlstr = sqlstr + tem + ","
  2442. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2443. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2444. sqlstr = sqlstr + tem + ","
  2445. } else {
  2446. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2447. sqlstr = sqlstr + tem + ","
  2448. }
  2449. }
  2450. if _, ok := mapResult["selectedCalcul2"]; ok {
  2451. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2452. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2453. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2454. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2455. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2456. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2457. sqlstr = sqlstr + tem + ","
  2458. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2459. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2460. sqlstr = sqlstr + tem + ","
  2461. } else {
  2462. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2463. sqlstr = sqlstr + tem + ","
  2464. }
  2465. }
  2466. }
  2467. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2468. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2469. sqlstr = sqlstr + " where pastureid=" + pastureid
  2470. if len(mapResult["filters"].([]interface{})) > 0 {
  2471. sqlstr = sqlstr + " and "
  2472. }
  2473. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2474. for _, value := range mapResult["filters"].([]interface{}) {
  2475. switch value.(map[string]interface{})["filterOperator"].(string) {
  2476. case ">", "=", "<", ">=", "<=", "!=", "like":
  2477. 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 "
  2478. case "IN":
  2479. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2480. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2481. sqlstr = sqlstr + value1.(string) + ","
  2482. }
  2483. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2484. sqlstr = sqlstr + ")" + " AND "
  2485. case "BETWEEN":
  2486. 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 "
  2487. }
  2488. }
  2489. if len(mapResult["filters"].([]interface{})) > 0 {
  2490. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2491. }
  2492. //
  2493. groupstr = groupstr[0 : len(groupstr)-1]
  2494. sqlstr = sqlstr + groupstr + " "
  2495. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2496. sqlstr = sqlstr + " order by "
  2497. }
  2498. //
  2499. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2500. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2501. sqlstr = sqlstr + value.(string) + " "
  2502. } else {
  2503. sqlstr = sqlstr + value.(string) + ","
  2504. }
  2505. }
  2506. //
  2507. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2508. tx := restful.Engine.NewSession()
  2509. err := tx.Begin()
  2510. defer func() {
  2511. switch {
  2512. case err != nil:
  2513. logging.Error("tx.Begin 事务启动失败__error:", err)
  2514. if tx != nil {
  2515. tx.Rollback()
  2516. }
  2517. default:
  2518. if tx != nil {
  2519. err = tx.Commit()
  2520. }
  2521. }
  2522. if tx != nil {
  2523. tx.Close()
  2524. }
  2525. }()
  2526. exec, err := tx.SQL(sqlstr).Query().List()
  2527. if err != nil {
  2528. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2529. } else {
  2530. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2531. }
  2532. }
  2533. func Dashboards(c *gin.Context) {
  2534. appG := app.Gin{C: c}
  2535. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2536. fsion := gofasion.NewFasion(string(dataByte))
  2537. sqlnamestr := fsion.Get("name").ValueStr()
  2538. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2539. offset := fsion.Get("offset").ValueDefaultInt(0)
  2540. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2541. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2542. month := fsion.Get("month").ValueDefaultStr("map")
  2543. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2544. tx := restful.Engine.NewSession()
  2545. err := tx.Begin()
  2546. defer func() {
  2547. switch {
  2548. case err != nil:
  2549. if tx != nil {
  2550. tx.Rollback()
  2551. }
  2552. default:
  2553. if tx != nil {
  2554. err = tx.Commit()
  2555. }
  2556. }
  2557. if tx != nil {
  2558. tx.Close()
  2559. }
  2560. }()
  2561. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2562. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2563. if sql != "" {
  2564. s_params := make([]interface{}, 0)
  2565. if fsion.HasKey("parammaps") {
  2566. parammaps := fsion.Get("parammaps")
  2567. paramslist := strings.Split(p, ",")
  2568. if len(paramslist) > 0 && p != "" {
  2569. for _, value := range paramslist {
  2570. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2571. if tempv, exists := c.Get("jwt_username"); exists {
  2572. s_params = append(s_params, tempv.(string))
  2573. } else {
  2574. s_params = append(s_params, "")
  2575. }
  2576. } else {
  2577. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2578. }
  2579. }
  2580. }
  2581. }
  2582. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2583. if err != nil {
  2584. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2585. } else {
  2586. //paramslist1 := strings.Split(p1, ",")
  2587. dids := make([]interface{}, 0)
  2588. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2589. var mapResult map[string]interface{}
  2590. dids = append(dids, value["dashboard_id"])
  2591. if value["content"] != nil {
  2592. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2593. if err1 != nil {
  2594. println("JsonToMapDemo1 err: ", err1)
  2595. }
  2596. temap := make(map[string]interface{})
  2597. tem := mapResult["layout"].([]interface{})
  2598. if v, ok := value["chartids"]; ok {
  2599. chartids := strings.Split(v.(string), ",")
  2600. for _, va := range chartids {
  2601. a := false
  2602. for _, v2 := range tem {
  2603. if v2.(map[string]interface{})["id"].(string) == va {
  2604. a = true
  2605. //println("va1======",va)
  2606. }
  2607. }
  2608. if !a {
  2609. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2610. va + "\",\"id\":\"" + va +
  2611. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2612. var mapTem map[string]interface{}
  2613. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2614. if err1 != nil {
  2615. println("JsonToMapDemo err: ", err1)
  2616. }
  2617. tem = append(tem, mapTem)
  2618. }
  2619. }
  2620. temap["layout"] = tem
  2621. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2622. }
  2623. } else {
  2624. temap := make(map[string]interface{})
  2625. tem := make([]interface{}, 0)
  2626. if v, ok := value["chartids"]; ok {
  2627. chartids := strings.Split(v.(string), ",")
  2628. for _, va := range chartids {
  2629. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2630. va + "\",\"id\":\"" + va +
  2631. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2632. var mapTem map[string]interface{}
  2633. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2634. if err1 != nil {
  2635. println("JsonToMapDemo err: ", err1)
  2636. }
  2637. tem = append(tem, mapTem)
  2638. }
  2639. temap["layout"] = tem
  2640. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2641. }
  2642. }
  2643. }
  2644. queryData.(map[string]interface{})["order"] = dids
  2645. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2646. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2647. }
  2648. } else {
  2649. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2650. }
  2651. }
  2652. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2653. fsion := gofasion.NewFasion(parammaps)
  2654. sqlnamestr := fsion.Get("name").ValueStr()
  2655. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2656. offset := fsion.Get("offset").ValueDefaultInt(0)
  2657. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2658. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2659. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2660. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2661. body := []byte("")
  2662. if sql != "" {
  2663. s_params := make([]interface{}, 0)
  2664. if fsion.HasKey("parammaps") {
  2665. parammaps := fsion.Get("parammaps")
  2666. paramslist := strings.Split(p, ",")
  2667. if len(paramslist) > 0 && p != "" {
  2668. for _, value := range paramslist {
  2669. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2670. }
  2671. }
  2672. }
  2673. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2674. if err != nil {
  2675. } else {
  2676. paramslist1 := strings.Split(p1, ",")
  2677. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2678. s_params1 := make([]interface{}, 0)
  2679. if len(paramslist1) > 0 && p1 != "" {
  2680. for _, v := range paramslist1 {
  2681. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2682. }
  2683. }
  2684. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2685. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2686. body, _ = json.Marshal(queryData)
  2687. }
  2688. }
  2689. }
  2690. bs := bytes.NewBuffer(body)
  2691. client := &http.Client{}
  2692. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2693. req, err := http.NewRequest(RequestMethod,
  2694. url,
  2695. bs,
  2696. )
  2697. if err != nil {
  2698. }
  2699. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2700. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2701. if err != nil {
  2702. // handle error
  2703. }
  2704. resp, err := client.Do(req)
  2705. if err != nil {
  2706. return ""
  2707. }
  2708. defer resp.Body.Close()
  2709. result_body, err := ioutil.ReadAll(resp.Body)
  2710. if err != nil {
  2711. return ""
  2712. }
  2713. fmt.Println(string(result_body))
  2714. return ""
  2715. }
  2716. func GetSummary(c *gin.Context) {
  2717. appG := app.Gin{C: c}
  2718. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2719. fsion := gofasion.NewFasion(string(dataByte))
  2720. offset := fsion.Get("offset").ValueDefaultInt(0)
  2721. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2722. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2723. parammaps := fsion.Get("parammaps")
  2724. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2725. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2726. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2727. tx := restful.Engine.NewSession()
  2728. defer tx.Close()
  2729. sqlnamestr := ""
  2730. if genre == "0" {
  2731. if status == "0" {
  2732. sqlnamestr = "getAccuracyJSY"
  2733. } else if status == "1" {
  2734. sqlnamestr = "getAccuracyHFT"
  2735. } else if status == "2" {
  2736. sqlnamestr = "getAccuracyHNS"
  2737. } else if status == "3" {
  2738. sqlnamestr = "getAccuracyHSC"
  2739. } else if status == "4" {
  2740. sqlnamestr = "getAccuracyHCC"
  2741. } else if status == "5" {
  2742. sqlnamestr = "getAccuracyMC"
  2743. } else if status == "6" {
  2744. sqlnamestr = "getAccuracyFeedHL"
  2745. } else if status == "7" {
  2746. sqlnamestr = "getAccuracyRT"
  2747. }
  2748. } else {
  2749. if status == "0" {
  2750. sqlnamestr = "getAccuracySCCJSY"
  2751. } else if status == "1" {
  2752. sqlnamestr = "getAccuracySFT"
  2753. } else if status == "2" {
  2754. sqlnamestr = "getAccuracySNS"
  2755. } else if status == "3" {
  2756. sqlnamestr = "getAccuracySSC"
  2757. } else if status == "4" {
  2758. sqlnamestr = "getAccuracySCC"
  2759. } else if status == "5" {
  2760. sqlnamestr = "getAccuracySLCL"
  2761. } else if status == "7" {
  2762. sqlnamestr = "getAccuracySCCRT"
  2763. }
  2764. }
  2765. if isDate == "1" {
  2766. sqlnamestr += "Date"
  2767. }
  2768. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2769. // fmt.Println(sqlnamestr, sql)
  2770. if sql != "" {
  2771. s_params := make([]interface{}, 0)
  2772. // if fsion.HasKey("parammaps") {
  2773. fmt.Println(s_params, "222", p)
  2774. paramslist := strings.Split(p, ",")
  2775. if len(paramslist) > 0 && p != "" {
  2776. for _, value := range paramslist {
  2777. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2778. if tempv, exists := c.Get("jwt_username"); exists {
  2779. s_params = append(s_params, tempv.(string))
  2780. } else {
  2781. s_params = append(s_params, "")
  2782. }
  2783. } else {
  2784. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2785. }
  2786. }
  2787. }
  2788. if returntype == "xlsx" {
  2789. var xlsxfile *xlsx.File
  2790. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2791. //c.File("c:/dd.xlsx")
  2792. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2793. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2794. c.Header("Content-Transfer-Encoding", "binary")
  2795. _ = xlsxfile.Write(c.Writer)
  2796. } else {
  2797. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2798. if err != nil {
  2799. logging.Error("GetDataByName err: ", err)
  2800. msg := geterrmsg(err.Error())
  2801. appG.Response(http.StatusOK, e.ERROR, msg)
  2802. } else {
  2803. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2804. }
  2805. }
  2806. } else {
  2807. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2808. }
  2809. }
  2810. // type lpplanStruct struct {
  2811. // Id int64 `xorm:"id"`
  2812. // Tmrname string `xorm:"tmrname"`
  2813. // Tmrid int64 `xorm:"tmrid"`
  2814. // Sort int64 `xorm:"sort"`
  2815. // Sel int64 `xorm:"sel"`
  2816. // Times int64 `xorm:"times"`
  2817. // Ftname string `xorm:"ftname"`
  2818. // Ftid int64 `xorm:"ftid"`
  2819. // Maxweight float64 `xorm:"maxweight"`
  2820. // Sumweight float64 `xorm:"sumweight"`
  2821. // Sumcowcount int64 `xorm:"sumcowcount"`
  2822. // Pastureid string `xorm:"pastureid"`
  2823. // Display string `xorm:"display"`
  2824. // Issplit int64 `xorm:"issplit"`
  2825. // BeginTime string `xorm:"begintime"`
  2826. // }
  2827. func UpdateFTdetail(c *gin.Context) {
  2828. appG := app.Gin{C: c}
  2829. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2830. tempval_ := make(map[string]interface{})
  2831. tempCommon := make(map[string]interface{})
  2832. tempval := make([]map[string]interface{}, 0)
  2833. fTChange := make(map[string]interface{}, 0)
  2834. // fpdOldDataList := make([]map[string]interface{}, 0)
  2835. // fpdDataList := make([]map[string]interface{}, 0)
  2836. fsion := gofasion.NewFasion(string(dataByte))
  2837. // parammaps := fsion.Get("parammaps")
  2838. createdate := time.Now().Format("2006-01-02 15:04:05")
  2839. err := json.Unmarshal(dataByte, &tempval_)
  2840. if err != nil {
  2841. appG.Response(http.StatusOK, e.ERROR, false)
  2842. return
  2843. }
  2844. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2845. tx := restful.Engine.NewSession()
  2846. if v, ok := tempval_["data"].([]interface{}); ok {
  2847. for _, Tvalue := range v {
  2848. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2849. if v1["name"] == "updateFPbyFTChange" {
  2850. fTChange = v1
  2851. continue
  2852. }
  2853. tempval = append(tempval, v1)
  2854. }
  2855. }
  2856. }
  2857. parammaps := fTChange["parammaps"].(map[string]interface{})
  2858. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, 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. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2865. // if err != nil {
  2866. // logs.Error(err)
  2867. // appG.Response(http.StatusOK, e.ERROR, false)
  2868. // return
  2869. // }
  2870. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2871. // if err != nil {
  2872. // logs.Error(err)
  2873. // appG.Response(http.StatusOK, e.ERROR, false)
  2874. // return
  2875. // }
  2876. err = tx.Begin()
  2877. if err != nil {
  2878. logging.Error("tx.Begin 事务启动失败__error:", err)
  2879. }
  2880. defer func() {
  2881. if err != nil {
  2882. if tx != nil {
  2883. tx.Rollback()
  2884. }
  2885. }
  2886. if tx != nil {
  2887. tx.Close()
  2888. }
  2889. }()
  2890. if err != nil {
  2891. } else {
  2892. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2893. tempCommon = v
  2894. }
  2895. // 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 ,
  2896. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2897. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2898. // UNION
  2899. // 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 ,
  2900. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2901. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2902. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2903. if err == nil {
  2904. if tempv, exists := c.Get("jwt_username"); exists {
  2905. tempCommon["jwt_username"] = tempv.(string)
  2906. }
  2907. for _, paramvalue := range tempval {
  2908. if _, ok := paramvalue["resultname"]; !ok {
  2909. paramvalue["resultname"] = paramvalue["name"]
  2910. }
  2911. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2912. if err != nil {
  2913. logging.Error("ExecDataParam error:", err)
  2914. break
  2915. }
  2916. }
  2917. if err != nil {
  2918. msg := geterrmsg(err.Error())
  2919. appG.Response(http.StatusOK, e.ERROR, msg)
  2920. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2921. }
  2922. }
  2923. }
  2924. tx.Commit()
  2925. // go func() {
  2926. if fTChange != nil {
  2927. parammaps := fTChange["parammaps"].(map[string]interface{})
  2928. if parammaps["type"].(float64) == 1 {
  2929. _, err = tx.SQL(`UPDATE feedp fp
  2930. set
  2931. ccountratio = ccount *(ratio /100 ),
  2932. fp.ftweight= IFNULL(IF(
  2933. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2935. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2936. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2937. ),0),fp.feedweight = IFNULL(IF(
  2938. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2940. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2941. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2942. ),0) +ifnull(fp.supplyweight,0)
  2943. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2944. _, err = tx.SQL(`UPDATE fpdetail fpd
  2945. INNER JOIN feedp fp
  2946. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2947. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2948. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2949. } else {
  2950. _, err = tx.SQL(`UPDATE feedp fp
  2951. SET ccountratio = ccount *(ratio /100 ),
  2952. fp.supplyweight= IFNULL(IF(
  2953. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2954. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2955. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2956. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2957. ),0),fp.feedweight = IFNULL(IF(
  2958. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2959. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2960. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2961. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2962. ),0) +ifnull(fp.supplyweight,0)
  2963. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2964. _, err = tx.SQL(`UPDATE fpdetail fpd
  2965. INNER JOIN feedp fp
  2966. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2967. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2968. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2969. }
  2970. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2971. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2972. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2973. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2974. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2975. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2976. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2977. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2978. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2979. // fmt.Println(ftId)
  2980. tx.SQL(`update feedp fp set barname = (select bname from bar where id = fp.id ) where pastureid = ?`, parammaps["pastureid"]).Execute()
  2981. // fmt.Println(fsion.Get("userId").ValueStr(),"fsion.Get.ValueStr()")
  2982. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2983. // 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 ,
  2984. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2985. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2986. // UNION
  2987. // 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 ,
  2988. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2989. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2990. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2991. // lpplanList := make([]*lpplanStruct, 0)
  2992. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2993. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2994. // (select ifnull(volume,0) from feedtemplet where id = lpplan.ftid) ) maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2995. // if err != nil {
  2996. // logs.Error(err, 1)
  2997. // return
  2998. // }
  2999. // lppidlist := []string{}
  3000. // for _, lpp := range lpplanList {
  3001. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3002. // }
  3003. // if len(lppidlist) <= 0 {
  3004. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3005. // return
  3006. // }
  3007. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3008. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3009. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3010. // if err != nil {
  3011. // // tx.Rollback()
  3012. // logs.Error(err, 2, parammaps["pastureid"])
  3013. // return
  3014. // }
  3015. // for _, lpp := range lpplandtl1AllList {
  3016. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3017. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3018. // if err != nil {
  3019. // logs.Error(err)
  3020. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3021. // return
  3022. // }
  3023. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3024. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3025. // if err != nil {
  3026. // logs.Error(err)
  3027. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3028. // return
  3029. // }
  3030. // }
  3031. // var wg sync.WaitGroup
  3032. // for _, old := range fpdOldDataList {
  3033. // for _, fpd := range fpdDataList {
  3034. // wg.Add(1)
  3035. // go func(old, fpd map[string]interface{}) {
  3036. // updateLppandList := make([]*lpplandtl1, 0)
  3037. // defer wg.Done()
  3038. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3039. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3040. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3041. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3042. // // if weight > oldweight {
  3043. // // return
  3044. // // }
  3045. // var w float64
  3046. // var status int
  3047. // if weight < oldweight {
  3048. // if weight >= 0 {
  3049. // return
  3050. // }
  3051. // w = weight
  3052. // status = 0
  3053. // } else {
  3054. // if oldweight > 0 {
  3055. // return
  3056. // }
  3057. // w = weight
  3058. // status = 1
  3059. // }
  3060. // // fweight = w
  3061. // for _, lpp := range lpplanList {
  3062. // var fweight float64
  3063. // var lweight float64
  3064. // lpplandtl1List := make([]*lpplandtl1, 0)
  3065. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3066. // for _, lppland := range lpplandtl1AllList {
  3067. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3068. // lpplandtl1List = append(lpplandtl1List, lppland)
  3069. // }
  3070. // }
  3071. // if len(lpplandtl1List) == 0 {
  3072. // continue
  3073. // }
  3074. // for _, lppland := range lpplandtl1List {
  3075. // lweight += lppland.Lweight
  3076. // }
  3077. // if status == 0 {
  3078. // if lweight <= 0 {
  3079. // continue
  3080. // }
  3081. // } else {
  3082. // if lpp.Maxweight <= lweight {
  3083. // continue
  3084. // }
  3085. // }
  3086. // for _, lppland := range lpplandtl1List {
  3087. // if fpdid == lppland.Fpdid {
  3088. // if status == 1 {
  3089. // // if w <= lppland.Lweight {
  3090. // if lpp.Maxweight <= lweight {
  3091. // continue
  3092. // }
  3093. // if w+lweight <= lpp.Maxweight {
  3094. // lppland.Lweight += w
  3095. // lweight += w
  3096. // fweight += w
  3097. // w = 0
  3098. // } else {
  3099. // w = w - (lpp.Maxweight - lweight)
  3100. // n := (lpp.Maxweight - lweight)
  3101. // lppland.Lweight = lppland.Lweight + n
  3102. // lweight += n
  3103. // fweight += n
  3104. // }
  3105. // } else {
  3106. // if lppland.Lweight == 0 {
  3107. // continue
  3108. // }
  3109. // if w+lppland.Lweight >= 0 {
  3110. // lppland.Lweight = lppland.Lweight + w
  3111. // lweight = lweight + w
  3112. // fweight = fweight + w
  3113. // w = 0
  3114. // } else {
  3115. // w = w + lppland.Lweight
  3116. // lweight = lweight - lppland.Lweight
  3117. // fweight = fweight - lppland.Lweight
  3118. // lppland.Lweight = 0
  3119. // }
  3120. // }
  3121. // updateLppandList = append(updateLppandList, lppland)
  3122. // break
  3123. // }
  3124. // }
  3125. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3126. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3127. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3128. // if err != nil {
  3129. // // tx.Rollback()
  3130. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3131. // return
  3132. // }
  3133. // for _, lppland := range updateLppandList {
  3134. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3135. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3136. // if err != nil {
  3137. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3138. // // tx.Rollback()
  3139. // logs.Error(err, 3)
  3140. // return
  3141. // }
  3142. // // defer wg.Done()
  3143. // }
  3144. // updateLppandList = []*lpplandtl1{}
  3145. // if w == 0 {
  3146. // break
  3147. // }
  3148. // }
  3149. // }
  3150. // }(old, fpd)
  3151. // }
  3152. // }
  3153. // wg.Wait()
  3154. }
  3155. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3156. if err != nil {
  3157. logs.Error(err)
  3158. appG.Response(http.StatusOK, e.ERROR, false)
  3159. return
  3160. }
  3161. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3162. if err != nil {
  3163. logs.Error(err)
  3164. appG.Response(http.StatusOK, e.ERROR, false)
  3165. return
  3166. }
  3167. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3168. if err != nil {
  3169. logs.Error(err)
  3170. appG.Response(http.StatusOK, e.ERROR, false)
  3171. return
  3172. }
  3173. now := createdate
  3174. userId:= fsion.Get("userId").ValueStr()
  3175. // for _, oldFpd := range oldFpdDataList {
  3176. for _, newFpd := range newFpdDataList {
  3177. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3178. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3179. // go func() {
  3180. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3181. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3182. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3183. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  3184. if err != nil {
  3185. logs.Error(err)
  3186. appG.Response(http.StatusOK, e.ERROR, false)
  3187. return
  3188. }
  3189. // }()
  3190. }
  3191. // break
  3192. // }
  3193. // }
  3194. // }
  3195. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3196. for _, newLpplandtl1 := range newLpplandtl1List {
  3197. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3198. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3199. // go func() {
  3200. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3201. background,cowcount,ccountradio,lweighthis,userId,createdate)
  3202. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3203. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3204. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3205. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3206. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3207. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], userId,now ).Execute()
  3208. if err != nil {
  3209. logs.Error(err)
  3210. appG.Response(http.StatusOK, e.ERROR, false)
  3211. return
  3212. }
  3213. // }()
  3214. // }
  3215. // break
  3216. // }
  3217. // }
  3218. }
  3219. // for _, oldFeedp := range oldFeedpList {
  3220. for _, newFeedp := range newFeedpList {
  3221. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3222. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3223. // go func() {
  3224. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3225. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3226. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3227. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3228. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3229. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3230. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3231. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  3232. // fmt.Println(userId,"33333333333333333333333333333333333")
  3233. if err != nil {
  3234. logs.Error(err)
  3235. appG.Response(http.StatusOK, e.ERROR, false)
  3236. return
  3237. }
  3238. }
  3239. // ,,parammaps["ftid"])
  3240. // surplus, surplusId, id, pastureId string
  3241. // FtdetailSurplusFt(parammaps["ftid"].)
  3242. ftList1, err := tx.SQL(` SELECT
  3243. f.id,
  3244. f.surplus surplusId,
  3245. f.pastureid,
  3246. s.surplus
  3247. FROM
  3248. feedtemplet f
  3249. JOIN surplus s ON s.id = f.surplus
  3250. WHERE
  3251. f.id = ?`, parammaps["ftid"]).QueryString()
  3252. for _, ft := range ftList1 {
  3253. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3254. }
  3255. appG.Response(http.StatusOK, e.SUCCESS, true)
  3256. }
  3257. type lpplandtlInfo struct {
  3258. Id int64 `xorm:"id"`
  3259. Pastureid int64 `xorm:"pastureid"`
  3260. Lppid int64 `xorm:"lppid"`
  3261. Barid int64 `xorm:"barid"`
  3262. Barname string `xorm:"barname"`
  3263. Fpdid int64 `xorm:"fpdid"`
  3264. Fttype int64 `xorm:"fttype"`
  3265. Lweight float64 `xorm:"lweight"`
  3266. Sort int64 `xorm:"sort"`
  3267. Tmrid int64 `xorm:"tmrid"`
  3268. Tmrname string `xorm:"tmrname"`
  3269. Cowcount int64 `xorm:"cowcount"`
  3270. Ccountradio float64 `xorm:"ccountradio"`
  3271. Background string `xorm:"background"`
  3272. Lweighthis float64 `xorm:"lweighthis"`
  3273. Maxweight float64 `xorm:"maxweight"`
  3274. }
  3275. func UpdateFpdetailBar(c *gin.Context) {
  3276. appG := app.Gin{C: c}
  3277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3278. fsion := gofasion.NewFasion(string(dataByte))
  3279. pastureid := fsion.Get("pastureid").ValueStr()
  3280. id := fsion.Get("id").ValueStr()
  3281. tx := restful.Engine.NewSession()
  3282. tx.Begin()
  3283. 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 `,
  3284. pastureid, id).Query().List()
  3285. if err != nil {
  3286. logs.Error(err)
  3287. }
  3288. for _, fpd := range fpdList {
  3289. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3290. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3291. pastureid, fpd["id"]).Query().List()
  3292. if err != nil {
  3293. tx.Rollback()
  3294. logs.Error(err)
  3295. appG.Response(http.StatusOK, e.ERROR, false)
  3296. return
  3297. }
  3298. var lweight float64
  3299. for _, lppland := range lpplandList {
  3300. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3301. lweight += lweight1
  3302. }
  3303. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3304. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3305. if fpdweight >= ptuse && lweight == ptuse {
  3306. continue
  3307. } else {
  3308. if lweight <= fpdweight {
  3309. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3310. if err != nil {
  3311. tx.Rollback()
  3312. logs.Error(err)
  3313. appG.Response(http.StatusOK, e.ERROR, false)
  3314. return
  3315. }
  3316. } else {
  3317. weight := fpdweight - lweight
  3318. for _, lppland := range lpplandList {
  3319. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3320. if weight >= lpplandlweight {
  3321. weight = weight - lpplandlweight
  3322. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3323. if err != nil {
  3324. tx.Rollback()
  3325. logs.Error(err)
  3326. appG.Response(http.StatusOK, e.ERROR, false)
  3327. return
  3328. }
  3329. } else {
  3330. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3331. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3332. // if err != nil {
  3333. // tx.Rollback()
  3334. // logs.Error(err)
  3335. // appG.Response(http.StatusOK, e.ERROR, false)
  3336. // return
  3337. // }
  3338. weight = 0
  3339. break
  3340. }
  3341. }
  3342. }
  3343. }
  3344. }
  3345. fsionData := fsion.Get("data").Array()
  3346. for _, list := range fsionData {
  3347. ftmap := make(map[string]interface{})
  3348. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3349. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3350. ftmap["times"] = list.Get("times").ValueInt64()
  3351. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3352. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3353. // fmt.Println(ftmap)
  3354. /*
  3355. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3356. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3357. if count == 1 {
  3358. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3359. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3360. if err != nil {
  3361. tx.Rollback()
  3362. logs.Error(err)
  3363. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3364. return
  3365. }
  3366. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3367. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3368. if err != nil {
  3369. tx.Rollback()
  3370. logs.Error(err)
  3371. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3372. return
  3373. }
  3374. }
  3375. */
  3376. fpdDataList, err := tx.SQL(`
  3377. 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 ,
  3378. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3379. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3380. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3381. if err != nil {
  3382. tx.Rollback()
  3383. logs.Error(err)
  3384. }
  3385. for _, fpd := range fpdDataList {
  3386. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3387. fttype := -1
  3388. if fpd["fttype"].(string) == "1" {
  3389. fttype = 1
  3390. }
  3391. var fweight float64
  3392. var lweight float64
  3393. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3394. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3395. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3396. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3397. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3398. join tmr t on t.id = lpp.tmrid
  3399. where lppland.fpdid =?
  3400. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3401. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3402. if err != nil {
  3403. tx.Rollback()
  3404. logs.Error(err)
  3405. }
  3406. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3407. var w float64
  3408. var status int
  3409. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3410. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3411. if weight >= 0 {
  3412. continue
  3413. }
  3414. w = weight
  3415. status = 0
  3416. } else {
  3417. // continue
  3418. if weight <= 0 {
  3419. continue
  3420. }
  3421. w = weight
  3422. status = 1
  3423. }
  3424. // for _, lppland := range lpplandtl1List {
  3425. // lweight += lppland.Lweight
  3426. // }
  3427. for _, lppland := range lpplandtl1List {
  3428. lpplandInfo := new(lpplandtlInfo)
  3429. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3430. lweight = lpplandInfo.Lweight
  3431. if status == 1 {
  3432. // if w <= lppland.Lweight {
  3433. if lppland.Maxweight <= lweight {
  3434. continue
  3435. }
  3436. if w+lweight <= lppland.Maxweight {
  3437. lppland.Lweight += w
  3438. lweight += w
  3439. fweight += w
  3440. w = 0
  3441. } else {
  3442. w = w - (lppland.Maxweight - lweight)
  3443. n := (lppland.Maxweight - lweight)
  3444. lppland.Lweight = lppland.Lweight + n
  3445. lweight += n
  3446. fweight += n
  3447. }
  3448. } else {
  3449. if lppland.Lweight == 0 {
  3450. continue
  3451. }
  3452. if w+lppland.Lweight >= 0 {
  3453. lppland.Lweight = lppland.Lweight + w
  3454. lweight = lweight + w
  3455. fweight = fweight + w
  3456. w = 0
  3457. } else {
  3458. w = w + lppland.Lweight
  3459. lweight = lweight - lppland.Lweight
  3460. fweight = fweight - lppland.Lweight
  3461. lppland.Lweight = 0
  3462. }
  3463. }
  3464. if lppland.Lweight > 0 {
  3465. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3466. if err != nil {
  3467. tx.Rollback()
  3468. logs.Error(err)
  3469. return
  3470. }
  3471. } else {
  3472. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3473. if err != nil {
  3474. tx.Rollback()
  3475. logs.Error(err)
  3476. return
  3477. }
  3478. }
  3479. if w == 0 {
  3480. break
  3481. }
  3482. // break
  3483. }
  3484. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3485. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3486. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3487. if err != nil {
  3488. tx.Rollback()
  3489. logs.Error(err)
  3490. }
  3491. if w == 0 {
  3492. break
  3493. }
  3494. }
  3495. }
  3496. }
  3497. tx.Commit()
  3498. now := time.Now()
  3499. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3500. if err != nil {
  3501. logs.Error(err)
  3502. appG.Response(http.StatusOK, e.ERROR, false)
  3503. return
  3504. }
  3505. for _, newLpplandtl1 := range newLpplandtl1List {
  3506. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3507. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3508. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3509. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3510. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3511. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3512. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3513. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3514. if err != nil {
  3515. logs.Error(err)
  3516. appG.Response(http.StatusOK, e.ERROR, false)
  3517. return
  3518. }
  3519. }
  3520. appG.Response(http.StatusOK, e.SUCCESS, true)
  3521. }
  3522. func GetProcessAnalysis(c *gin.Context) {
  3523. appG := app.Gin{C: c}
  3524. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3525. fsion := gofasion.NewFasion(string(dataByte))
  3526. sqlnamestr := fsion.Get("name").ValueStr()
  3527. offset := fsion.Get("offset").ValueDefaultInt(0)
  3528. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3529. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3530. parammaps := fsion.Get("parammaps")
  3531. tx := restful.Engine.NewSession()
  3532. err := tx.Begin()
  3533. defer func() {
  3534. switch {
  3535. case err != nil:
  3536. logging.Error("tx.Begin 事务启动失败__error:", err)
  3537. if tx != nil {
  3538. tx.Rollback()
  3539. }
  3540. default:
  3541. if tx != nil {
  3542. err = tx.Commit()
  3543. }
  3544. }
  3545. if tx != nil {
  3546. tx.Close()
  3547. }
  3548. }()
  3549. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3550. s_params := make([]interface{}, 0)
  3551. paramslist := strings.Split(p, ",")
  3552. if len(paramslist) > 0 && p != "" {
  3553. for _, value := range paramslist {
  3554. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3555. if tempv, exists := c.Get("jwt_username"); exists {
  3556. s_params = append(s_params, tempv.(string))
  3557. } else {
  3558. s_params = append(s_params, "")
  3559. }
  3560. } else {
  3561. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3562. }
  3563. }
  3564. }
  3565. tmrtnameStr := ""
  3566. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3567. if len(tmrtnameStr) == 0 {
  3568. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3569. } else {
  3570. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3571. }
  3572. }
  3573. if len(tmrtnameStr) > 0 {
  3574. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3575. }
  3576. sql += " ORDER BY d.intime"
  3577. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3578. if err != nil {
  3579. logging.Error("GetDataByName err: ", err)
  3580. msg := geterrmsg(err.Error())
  3581. appG.Response(http.StatusOK, e.ERROR, msg)
  3582. } else {
  3583. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3584. }
  3585. }
  3586. func UpdateFeedtempletStatus(c *gin.Context) {
  3587. appG := app.Gin{C: c}
  3588. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3589. fsion := gofasion.NewFasion(string(dataByte))
  3590. parammaps := fsion.Get("parammaps")
  3591. tx := restful.Engine.NewSession()
  3592. tx.Begin()
  3593. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3594. if err != nil {
  3595. tx.Rollback()
  3596. logs.Error(err)
  3597. appG.Response(http.StatusOK, e.ERROR, err)
  3598. return
  3599. }
  3600. tx.Commit()
  3601. appG.Response(http.StatusOK, e.SUCCESS, true)
  3602. }
  3603. func AddFtdry(c *gin.Context) {
  3604. appG := app.Gin{C: c}
  3605. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3606. fsion := gofasion.NewFasion(string(dataByte))
  3607. sqlnamestr := fsion.Get("name").ValueStr()
  3608. s_params := make([]interface{}, 0)
  3609. tx := restful.Engine.NewSession()
  3610. err := tx.Begin()
  3611. defer func() {
  3612. switch {
  3613. case err != nil:
  3614. if tx != nil {
  3615. tx.Rollback()
  3616. }
  3617. default:
  3618. if tx != nil {
  3619. err = tx.Commit()
  3620. }
  3621. }
  3622. if tx != nil {
  3623. tx.Close()
  3624. }
  3625. }()
  3626. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3627. if sql != "" {
  3628. parammaps := fsion.Get("parammaps")
  3629. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3630. paramslist := strings.Split(p, ",")
  3631. if len(paramslist) > 0 && p != "" {
  3632. for _, value := range paramslist {
  3633. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3634. if tempv, exists := c.Get("jwt_username"); exists {
  3635. s_params = append(s_params, tempv.(string))
  3636. } else {
  3637. s_params = append(s_params, "")
  3638. }
  3639. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3640. ids, err := setting.SnowIds.NextId()
  3641. if err != nil {
  3642. ids = time.Now().UnixNano()
  3643. logging.Info("create SnowIds err", err)
  3644. }
  3645. s_params = append(s_params, ids)
  3646. } else {
  3647. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3648. }
  3649. }
  3650. }
  3651. var actweight float64
  3652. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3653. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3654. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3655. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3656. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3657. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3658. 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()
  3659. if err != nil {
  3660. logging.Error("AddFtdry err: ", err)
  3661. msg := geterrmsg(err.Error())
  3662. appG.Response(http.StatusOK, e.ERROR, msg)
  3663. }
  3664. if len(actweightList) > 0 {
  3665. for _, item := range actweightList {
  3666. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3667. if err != nil {
  3668. logging.Error("AddFtdry err: ", err)
  3669. msg := geterrmsg(err.Error())
  3670. appG.Response(http.StatusOK, e.ERROR, msg)
  3671. }
  3672. actweight = fl
  3673. }
  3674. } else {
  3675. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3676. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3677. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3678. if err != nil {
  3679. logging.Error("AddFtdry err: ", err)
  3680. msg := geterrmsg(err.Error())
  3681. appG.Response(http.StatusOK, e.ERROR, msg)
  3682. }
  3683. for _, item := range dryList {
  3684. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3685. if err != nil {
  3686. logging.Error("AddFtdry err: ", err)
  3687. msg := geterrmsg(err.Error())
  3688. appG.Response(http.StatusOK, e.ERROR, msg)
  3689. }
  3690. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3691. }
  3692. }
  3693. if sqlnamestr == "insertFtdry" {
  3694. s_params = append(s_params, actweight)
  3695. } else if sqlnamestr == "updateFtdry" {
  3696. sql = fmt.Sprintf(sql, actweight)
  3697. }
  3698. queryData, err := execDataBySqlT(sql, s_params, tx)
  3699. if err != nil {
  3700. logging.Error("AddFtdry err: ", err)
  3701. msg := geterrmsg(err.Error())
  3702. appG.Response(http.StatusOK, e.ERROR, msg)
  3703. } else {
  3704. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3705. }
  3706. } else {
  3707. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3708. }
  3709. }
  3710. func CheckDates(c *gin.Context) {
  3711. tx := restful.Engine.NewSession()
  3712. defer tx.Close()
  3713. appG := app.Gin{C: c}
  3714. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3715. tempval_ := make(map[string]interface{})
  3716. tempCommon := make(map[string]interface{})
  3717. tempval := make([]map[string]interface{}, 0)
  3718. err := json.Unmarshal(dataByte, &tempval_)
  3719. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3720. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3721. if err != nil {
  3722. } else {
  3723. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3724. tempCommon = v
  3725. }
  3726. if v, ok := tempval_["data"].([]interface{}); ok {
  3727. for _, Tvalue := range v {
  3728. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3729. tempval = append(tempval, v1)
  3730. }
  3731. }
  3732. }
  3733. if err == nil {
  3734. if tempv, exists := c.Get("jwt_username"); exists {
  3735. tempCommon["jwt_username"] = tempv.(string)
  3736. }
  3737. for _, paramvalue := range tempval {
  3738. if _, ok := paramvalue["resultname"]; !ok {
  3739. paramvalue["resultname"] = paramvalue["name"]
  3740. }
  3741. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3742. if err != nil {
  3743. logging.Error("ExecDataParam error:", err)
  3744. }
  3745. }
  3746. if err == nil {
  3747. vmsg := ""
  3748. for _, item := range tempval {
  3749. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3750. for _, childrenList := range list.([]interface{}) {
  3751. for k, children := range childrenList.(map[string]interface{}) {
  3752. if k != "children" {
  3753. continue
  3754. }
  3755. for _, v := range children.([]map[string]interface{}) {
  3756. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3757. if k1 == "list" {
  3758. for _, v2 := range v1.([]map[string]interface{}) {
  3759. if v2["vmsg"].(string) != "1" {
  3760. if len(vmsg) == 0 {
  3761. vmsg = v2["vmsg"].(string)
  3762. } else {
  3763. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. }
  3772. }
  3773. }
  3774. if len(vmsg) > 0 {
  3775. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3776. } else {
  3777. appG.Response(http.StatusOK, e.SUCCESS, true)
  3778. }
  3779. } else {
  3780. msg := geterrmsg(err.Error())
  3781. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3782. }
  3783. }
  3784. }
  3785. if err != nil {
  3786. msg := geterrmsg(err.Error())
  3787. appG.Response(http.StatusOK, e.ERROR, msg)
  3788. }
  3789. }
  3790. 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) {
  3791. sqlname := fasion["name"].(string)
  3792. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3793. if v, ok := fasion["type"]; ok {
  3794. sqltype = v.(string)
  3795. }
  3796. sql := ""
  3797. p := ""
  3798. s_params := make([]interface{}, 0)
  3799. if sqltype != "" {
  3800. sql, p = restful.GetSqlByName(sqlname, tx)
  3801. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3802. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3803. paramslist := strings.Split(p, ",")
  3804. if len(paramslist) > 0 && p != "" {
  3805. for _, value := range paramslist {
  3806. ss := ""
  3807. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3808. ids, err := setting.SnowIds.NextId()
  3809. if err != nil {
  3810. ids = time.Now().UnixNano()
  3811. logging.Info("create SnowIds err", err)
  3812. }
  3813. s_params = append(s_params, ids)
  3814. } else {
  3815. if ss == "" && CommonParamMap != nil {
  3816. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3817. ss = valuestring
  3818. tempstrb := strings.IndexAny(valuestring, "@")
  3819. tempstre := strings.IndexAny(valuestring, ".")
  3820. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3821. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3822. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3823. }
  3824. } else {
  3825. ss = ""
  3826. }
  3827. }
  3828. }
  3829. if ss == "" && ParentParamMap != nil {
  3830. ss = getParamValue_(v, value, ParentParamMap)
  3831. }
  3832. if ss == "" && sameParamMap != nil {
  3833. ss = getParamValue(v, value, sameParamMap)
  3834. }
  3835. if ss == "" && ParamMap != nil {
  3836. ss = getParamValue(v, value, ParamMap)
  3837. }
  3838. s_params = append(s_params, ss)
  3839. }
  3840. }
  3841. }
  3842. }
  3843. }
  3844. if sql == "" {
  3845. sqltype = ""
  3846. }
  3847. if sql != "" {
  3848. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3849. if err != nil {
  3850. return nil, err
  3851. }
  3852. // fmt.Println(tempValParam)
  3853. return tempValParam.(map[string]interface{}), nil
  3854. } else {
  3855. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3856. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3857. if err != nil {
  3858. return nil, err
  3859. }
  3860. return nil, err
  3861. }
  3862. }
  3863. return nil, nil
  3864. }
  3865. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3866. var err error
  3867. subarray, ok := fasion["children"]
  3868. if ok {
  3869. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3870. tempVal_arrary := make([]map[string]interface{}, 0)
  3871. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3872. tempVal_ := make(map[string]interface{})
  3873. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3874. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3875. } else {
  3876. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3877. }
  3878. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3879. if err != nil {
  3880. return err
  3881. }
  3882. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3883. }
  3884. v.(map[string]interface{})["children"] = tempVal_arrary
  3885. }
  3886. }
  3887. return nil
  3888. }
  3889. func FpdImportExcel(c *gin.Context) {
  3890. appG := app.Gin{C: c}
  3891. inputdata := ""
  3892. c.Request.ParseForm()
  3893. params := c.Request.Form
  3894. file, _, err := c.Request.FormFile("file")
  3895. if err != nil {
  3896. appG.Response(http.StatusOK, e.ERROR, err)
  3897. return
  3898. }
  3899. sqlnamestrs := params.Get("name")
  3900. sheetname := params.Get("sheetname")
  3901. pastureid := params.Get("pastureid")
  3902. // importParams := params.Get("importParams")
  3903. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3904. // 必输项参数 (字符串格式 "field1,field2,field3")
  3905. requiredParams := params.Get("requiredParams")
  3906. // 日期参数
  3907. dateParams := params.Get("dateParams")
  3908. // 数字参数
  3909. numParams := params.Get("numParams")
  3910. //将字符串分割开
  3911. dateParamslist := strings.Split(dateParams, ",")
  3912. requiredParamslist := strings.Split(requiredParams, ",")
  3913. numParamslist := strings.Split(numParams, ",")
  3914. queryData := make([]interface{}, 0)
  3915. sqlslist := strings.Split(sqlnamestrs, ",")
  3916. xlsx1, err := excelize.OpenReader(file)
  3917. if err != nil {
  3918. fmt.Println(err)
  3919. return
  3920. }
  3921. ok := 0
  3922. error := 0
  3923. isdone := true
  3924. tx := restful.Engine.NewSession()
  3925. defer tx.Close()
  3926. languageStatus := GetLanguageStatus()
  3927. if languageStatus == "0" {
  3928. 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
  3929. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3930. if err != nil {
  3931. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3932. return
  3933. }
  3934. rows := xlsx1.GetRows(sheetname)
  3935. // 限制10000条,多余的截取掉
  3936. if len(rows) > 10000 {
  3937. rows = rows[:10000]
  3938. }
  3939. dataList := make(map[string][]*upFpdetail, 0)
  3940. for i, row := range rows {
  3941. if i > 0 {
  3942. entry := make(map[string]interface{})
  3943. outentry := make(map[string]interface{})
  3944. for j, colCell := range rows[0] {
  3945. for k, colCell1 := range row {
  3946. if j == k {
  3947. outentry[colCell] = colCell1
  3948. entry[colCell] = colCell1
  3949. }
  3950. }
  3951. }
  3952. inputdata = ""
  3953. a := ""
  3954. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3955. //校验日期格式
  3956. for _, v := range dateParamslist {
  3957. if v == "" {
  3958. continue
  3959. }
  3960. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3961. dtime, err := TransfTime(d.(string))
  3962. if err != nil {
  3963. a = strings.Trim(v, " ")
  3964. break
  3965. }
  3966. outentry[strings.Trim(v, " ")] = dtime
  3967. }
  3968. }
  3969. if a != "" {
  3970. outentry["error_msg"] = a + " 格式错误"
  3971. error++
  3972. queryData = append(queryData, outentry)
  3973. continue
  3974. }
  3975. a = ""
  3976. //校验必填格式
  3977. for _, v := range requiredParamslist {
  3978. if v == "" {
  3979. continue
  3980. }
  3981. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3982. a = strings.Trim(v, " ")
  3983. break
  3984. }
  3985. }
  3986. if a != "" {
  3987. outentry["error_msg"] = a + " 未填或格式错误"
  3988. error++
  3989. queryData = append(queryData, outentry)
  3990. continue
  3991. }
  3992. a = ""
  3993. //校验数字格式
  3994. for _, v := range numParamslist {
  3995. if v == "" {
  3996. continue
  3997. }
  3998. d, ok := outentry[strings.Trim(v, " ")]
  3999. if !ok || d == "" {
  4000. outentry[strings.Trim(v, " ")] = 0
  4001. } else {
  4002. var fl float64
  4003. switch d.(type) {
  4004. case string:
  4005. fl, err = strconv.ParseFloat(d.(string), 64)
  4006. }
  4007. if err != nil || fl < 0 {
  4008. a = strings.Trim(v, " ")
  4009. break
  4010. }
  4011. }
  4012. }
  4013. if a != "" {
  4014. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4015. error++
  4016. queryData = append(queryData, outentry)
  4017. continue
  4018. }
  4019. errExist := false
  4020. for _, sqlnamestr := range sqlslist {
  4021. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4022. paramslist := strings.Split(paramslists, ",")
  4023. if len(paramslist) > 0 {
  4024. s_params := make([]interface{}, 0)
  4025. for _, value := range paramslist {
  4026. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4027. if tempv, exists := c.Get("jwt_username"); exists {
  4028. s_params = append(s_params, tempv.(string))
  4029. } else {
  4030. s_params = append(s_params, "")
  4031. }
  4032. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4033. s_params = append(s_params, pastureid)
  4034. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4035. ids, err := setting.SnowIds.NextId()
  4036. if err != nil {
  4037. ids = time.Now().UnixNano()
  4038. logging.Info("create SnowIds err", err)
  4039. }
  4040. s_params = append(s_params, ids)
  4041. } else {
  4042. if outentry[strings.Trim(value, " ")] == nil {
  4043. s_params = append(s_params, "")
  4044. } else {
  4045. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4046. }
  4047. }
  4048. }
  4049. outentry["input"] = inputdata
  4050. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4051. if err != nil {
  4052. errExist = true
  4053. // if tx != nil {
  4054. // tx.Rollback()
  4055. // }
  4056. // if tx != nil {
  4057. // tx.Close()
  4058. // }
  4059. msg := geterrmsg(err.Error())
  4060. outentry["error_msg"] = msg
  4061. error++
  4062. queryData = append(queryData, outentry)
  4063. isdone = true
  4064. break
  4065. } else {
  4066. if len(returnmsgmap1) > 0 {
  4067. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4068. // if tx != nil {
  4069. // tx.Rollback()
  4070. // }
  4071. // if tx != nil {
  4072. // tx.Close()
  4073. // }
  4074. msg := geterrmsg(va.(string))
  4075. outentry["error_msg"] = msg
  4076. error++
  4077. queryData = append(queryData, outentry)
  4078. isdone = true
  4079. break
  4080. }
  4081. }
  4082. isdone = false
  4083. }
  4084. }
  4085. }
  4086. fmt.Println(outentry["栏舍名称"])
  4087. if !errExist {
  4088. dataexcel := make(map[string]interface{}, 0)
  4089. if _, ok := outentry["栏舍名称"]; ok {
  4090. dataexcel["barname"] = outentry["栏舍名称"]
  4091. }
  4092. if _, ok := outentry["实际牛头数"]; ok {
  4093. dataexcel["ccount"] = outentry["实际牛头数"]
  4094. }
  4095. // if _, ok := outentry["实际羊只数"]; ok {
  4096. // dataexcel["ccount"] = outentry["实际羊只数"]
  4097. // }
  4098. if _, ok := outentry["系数(%)"]; ok {
  4099. dataexcel["ratio"] = outentry["系数(%)"]
  4100. }
  4101. if _, ok := outentry["配方模板"]; ok {
  4102. dataexcel["ftname"] = outentry["配方模板"]
  4103. }
  4104. if _, ok := outentry["补料配方"]; ok {
  4105. dataexcel["ptsfname"] = outentry["补料配方"]
  4106. }
  4107. if _, ok := outentry["第一班比例(%)"]; ok {
  4108. dataexcel["1"] = outentry["第一班比例(%)"]
  4109. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4110. dataexcel["1"] = 0
  4111. }
  4112. } else {
  4113. dataexcel["1"] = 0
  4114. }
  4115. if _, ok := outentry["第二班比例(%)"]; ok {
  4116. dataexcel["2"] = outentry["第二班比例(%)"]
  4117. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4118. dataexcel["2"] = 0
  4119. }
  4120. } else {
  4121. dataexcel["2"] = 0
  4122. }
  4123. if _, ok := outentry["第三班比例(%)"]; ok {
  4124. dataexcel["3"] = outentry["第三班比例(%)"]
  4125. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4126. dataexcel["3"] = 0
  4127. }
  4128. } else {
  4129. dataexcel["3"] = 0
  4130. }
  4131. if _, ok := outentry["第四班比例(%)"]; ok {
  4132. dataexcel["4"] = outentry["第四班比例(%)"]
  4133. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4134. dataexcel["4"] = 0
  4135. }
  4136. } else {
  4137. dataexcel["4"] = 0
  4138. }
  4139. if _, ok := outentry["第五班比例(%)"]; ok {
  4140. dataexcel["5"] = outentry["第五班比例(%)"]
  4141. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4142. dataexcel["5"] = 0
  4143. }
  4144. } else {
  4145. dataexcel["5"] = 0
  4146. }
  4147. if _, ok := outentry["第六班比例(%)"]; ok {
  4148. dataexcel["6"] = outentry["第六班比例(%)"]
  4149. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4150. dataexcel["6"] = 0
  4151. }
  4152. } else {
  4153. dataexcel["6"] = 0
  4154. }
  4155. dataWeight := new(models.FpdetailEdit)
  4156. // dataWeightMap := make(map[string]interface{}, 0)
  4157. if _, ok := outentry["第一班重量"]; ok {
  4158. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4159. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4160. }
  4161. if _, ok := outentry["第二班重量"]; ok {
  4162. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4163. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4164. }
  4165. if _, ok := outentry["第三班重量"]; ok {
  4166. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4167. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4168. }
  4169. if _, ok := outentry["第四班重量"]; ok {
  4170. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4171. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4172. }
  4173. if _, ok := outentry["第五班重量"]; ok {
  4174. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4175. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4176. }
  4177. if _, ok := outentry["第六班重量"]; ok {
  4178. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4179. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4180. }
  4181. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4182. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4183. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4184. // fmt.Println(err)
  4185. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4186. dataWeight.Weight1 = 0
  4187. dataWeight.Weight2 = 0
  4188. dataWeight.Weight3 = 0
  4189. dataWeight.Weight4 = 0
  4190. dataWeight.Weight5 = 0
  4191. dataWeight.Weight6 = 0
  4192. }
  4193. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4194. if weight > 0 {
  4195. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4196. if err != nil {
  4197. logs.Error(err)
  4198. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4199. return
  4200. }
  4201. if !existbar {
  4202. continue
  4203. }
  4204. _, 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()
  4205. if err != nil {
  4206. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4207. return
  4208. }
  4209. _, 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()
  4210. if err != nil {
  4211. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4212. return
  4213. }
  4214. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4215. if err != nil {
  4216. logs.Error(err)
  4217. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4218. return
  4219. }
  4220. if !existft {
  4221. continue
  4222. }
  4223. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4224. if err != nil {
  4225. logs.Error(err)
  4226. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4227. return
  4228. }
  4229. if !ftexist {
  4230. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4231. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4232. if err != nil {
  4233. logs.Error(err)
  4234. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4235. return
  4236. }
  4237. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4238. if err != nil {
  4239. logs.Error(err)
  4240. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4241. return
  4242. }
  4243. }
  4244. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4245. if err != nil {
  4246. logs.Error(err)
  4247. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4248. return
  4249. }
  4250. if !exist {
  4251. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4252. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4253. if err != nil {
  4254. logs.Error(err)
  4255. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4256. return
  4257. }
  4258. }
  4259. var feedpargs []interface{}
  4260. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4261. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4262. if _, ok := dataexcel["ftname"]; ok {
  4263. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4264. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4265. // upFeedpSql += `,ftweight = ? `
  4266. // feedpargs = append(feedpargs, weight)
  4267. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4268. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4269. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4270. } else {
  4271. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4272. }
  4273. if _, ok := dataexcel["ptsfname"]; ok {
  4274. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4275. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4276. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4277. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4278. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4279. } else {
  4280. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4281. }
  4282. upFeedpSql += " where barname = ? and pastureid = ? "
  4283. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4284. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4285. if err != nil {
  4286. logs.Error(err)
  4287. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4288. return
  4289. }
  4290. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, 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 !exist1 {
  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 = ? ),?,1,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. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4306. if err != nil {
  4307. logs.Error(err)
  4308. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4309. return
  4310. }
  4311. if !exist2 {
  4312. _, 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) `,
  4313. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4314. if err != nil {
  4315. logs.Error(err)
  4316. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4317. return
  4318. }
  4319. }
  4320. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4321. if err != nil {
  4322. logs.Error(err)
  4323. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4324. return
  4325. }
  4326. if !exist3 {
  4327. _, 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) `,
  4328. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4329. if err != nil {
  4330. logs.Error(err)
  4331. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4332. return
  4333. }
  4334. }
  4335. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4336. if err != nil {
  4337. logs.Error(err)
  4338. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4339. return
  4340. }
  4341. if !exist4 {
  4342. _, 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) `,
  4343. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4344. if err != nil {
  4345. logs.Error(err)
  4346. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4347. return
  4348. }
  4349. }
  4350. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4351. if err != nil {
  4352. logs.Error(err)
  4353. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4354. return
  4355. }
  4356. if !exist5 {
  4357. _, 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) `,
  4358. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4359. if err != nil {
  4360. logs.Error(err)
  4361. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4362. return
  4363. }
  4364. }
  4365. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4366. if err != nil {
  4367. logs.Error(err)
  4368. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4369. return
  4370. }
  4371. if !exist6 {
  4372. _, 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) `,
  4373. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4374. if err != nil {
  4375. logs.Error(err)
  4376. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4377. return
  4378. }
  4379. }
  4380. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4381. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4382. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4383. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4384. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4385. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4386. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4387. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4388. and pastureid = ? and times = ?`
  4389. var fpdargs1 []interface{}
  4390. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4391. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4392. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4393. if err != nil {
  4394. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4395. return
  4396. }
  4397. var fpdargs2 []interface{}
  4398. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4399. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4400. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4401. if err != nil {
  4402. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4403. return
  4404. }
  4405. var fpdargs3 []interface{}
  4406. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4407. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4408. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4409. if err != nil {
  4410. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4411. return
  4412. }
  4413. var fpdargs4 []interface{}
  4414. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4415. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4416. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4417. if err != nil {
  4418. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4419. return
  4420. }
  4421. var fpdargs5 []interface{}
  4422. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4423. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4424. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4425. if err != nil {
  4426. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4427. return
  4428. }
  4429. var fpdargs6 []interface{}
  4430. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4431. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4432. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4433. if err != nil {
  4434. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4435. return
  4436. }
  4437. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4438. 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()
  4439. if err != nil {
  4440. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4441. return
  4442. }
  4443. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4444. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4445. upFpdetailList := make([]*upFpdetail, 0)
  4446. for _, newfpd := range newList {
  4447. for _, oldfpd := range oldFpdList {
  4448. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4449. var oldweight, newweight float64
  4450. if oldfpd["weight"] != nil {
  4451. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4452. }
  4453. if newfpd["weight"] != nil {
  4454. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4455. }
  4456. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4457. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4458. Old: oldweight,
  4459. New: newweight,
  4460. Times: newfpd["times"].(int64),
  4461. Ptid: newfpd["ptid"].(int64),
  4462. Fweight: fweight,
  4463. Id: oldfpd["id"].(int64),
  4464. })
  4465. break
  4466. }
  4467. }
  4468. }
  4469. // fmt.Println(dataexcel["barname"])
  4470. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4471. } else {
  4472. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4473. if err != nil {
  4474. logs.Error(err)
  4475. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4476. return
  4477. }
  4478. if !existbar {
  4479. continue
  4480. }
  4481. _, 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()
  4482. if err != nil {
  4483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4484. return
  4485. }
  4486. _, 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()
  4487. if err != nil {
  4488. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4489. return
  4490. }
  4491. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4492. if err != nil {
  4493. logs.Error(err)
  4494. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4495. return
  4496. }
  4497. if !existft {
  4498. continue
  4499. }
  4500. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4501. if err != nil {
  4502. logs.Error(err)
  4503. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4504. return
  4505. }
  4506. if !ftexist {
  4507. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4508. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4509. if err != nil {
  4510. logs.Error(err)
  4511. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4512. return
  4513. }
  4514. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4515. if err != nil {
  4516. logs.Error(err)
  4517. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4518. return
  4519. }
  4520. }
  4521. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4522. if err != nil {
  4523. logs.Error(err)
  4524. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4525. return
  4526. }
  4527. if !exist {
  4528. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4529. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4530. if err != nil {
  4531. logs.Error(err)
  4532. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4533. return
  4534. }
  4535. }
  4536. var feedpargs []interface{}
  4537. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4538. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4539. if _, ok := dataexcel["ftname"]; ok {
  4540. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4541. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4542. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4543. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4544. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4545. } else {
  4546. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4547. }
  4548. if _, ok := dataexcel["ptsfname"]; ok {
  4549. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4550. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4551. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4552. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4553. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4554. } else {
  4555. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4556. }
  4557. upFeedpSql += " where barname = ? and pastureid = ? "
  4558. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4559. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4560. if err != nil {
  4561. logs.Error(err)
  4562. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4563. return
  4564. }
  4565. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, 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 !exist1 {
  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 = ? ),?,1,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. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4581. if err != nil {
  4582. logs.Error(err)
  4583. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4584. return
  4585. }
  4586. if !exist2 {
  4587. _, 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) `,
  4588. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4589. if err != nil {
  4590. logs.Error(err)
  4591. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4592. return
  4593. }
  4594. }
  4595. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4596. if err != nil {
  4597. logs.Error(err)
  4598. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4599. return
  4600. }
  4601. if !exist3 {
  4602. _, 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) `,
  4603. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4604. if err != nil {
  4605. logs.Error(err)
  4606. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4607. return
  4608. }
  4609. }
  4610. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4611. if err != nil {
  4612. logs.Error(err)
  4613. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4614. return
  4615. }
  4616. if !exist4 {
  4617. _, 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) `,
  4618. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4619. if err != nil {
  4620. logs.Error(err)
  4621. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4622. return
  4623. }
  4624. }
  4625. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4626. if err != nil {
  4627. logs.Error(err)
  4628. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4629. return
  4630. }
  4631. if !exist5 {
  4632. _, 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) `,
  4633. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4634. if err != nil {
  4635. logs.Error(err)
  4636. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4637. return
  4638. }
  4639. }
  4640. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4641. if err != nil {
  4642. logs.Error(err)
  4643. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4644. return
  4645. }
  4646. if !exist6 {
  4647. _, 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) `,
  4648. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4649. if err != nil {
  4650. logs.Error(err)
  4651. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4652. return
  4653. }
  4654. }
  4655. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4656. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4657. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4658. and pastureid = ? and times = ?`
  4659. var fpdargs1 []interface{}
  4660. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4661. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4662. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4663. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4664. if err != nil {
  4665. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4666. return
  4667. }
  4668. var fpdargs2 []interface{}
  4669. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4670. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4671. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4672. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4673. if err != nil {
  4674. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4675. return
  4676. }
  4677. var fpdargs3 []interface{}
  4678. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4679. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4680. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4681. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4682. if err != nil {
  4683. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4684. return
  4685. }
  4686. var fpdargs4 []interface{}
  4687. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4688. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4689. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4690. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4691. if err != nil {
  4692. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4693. return
  4694. }
  4695. var fpdargs5 []interface{}
  4696. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4697. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4698. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4699. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4700. if err != nil {
  4701. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4702. return
  4703. }
  4704. var fpdargs6 []interface{}
  4705. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4706. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4707. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4708. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4709. if err != nil {
  4710. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4711. return
  4712. }
  4713. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4714. 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()
  4715. if err != nil {
  4716. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4717. return
  4718. }
  4719. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4720. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4721. upFpdetailList := make([]*upFpdetail, 0)
  4722. for _, newfpd := range newList {
  4723. for _, oldfpd := range oldFpdList {
  4724. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4725. var oldweight, newweight float64
  4726. if oldfpd["weight"] != nil {
  4727. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4728. }
  4729. if newfpd["weight"] != nil {
  4730. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4731. }
  4732. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4733. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4734. Old: oldweight,
  4735. New: newweight,
  4736. Times: newfpd["times"].(int64),
  4737. Ptid: newfpd["ptid"].(int64),
  4738. Fweight: fweight,
  4739. Id: oldfpd["id"].(int64),
  4740. })
  4741. break
  4742. }
  4743. }
  4744. }
  4745. // fmt.Println(dataexcel["barname"])
  4746. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4747. }
  4748. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4749. }
  4750. }
  4751. if !isdone {
  4752. ok++
  4753. isdone = true
  4754. }
  4755. }
  4756. for barname, v := range dataList {
  4757. // for _, v1 := range v {
  4758. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4759. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4760. // if count == 1 {
  4761. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4762. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4763. // if err != nil {
  4764. // logs.Error(err)
  4765. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4766. // return
  4767. // }
  4768. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4769. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4770. // if err != nil {
  4771. // logs.Error(err)
  4772. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4773. // return
  4774. // }
  4775. // }
  4776. // }
  4777. // /*/*
  4778. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4779. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4780. if err != nil {
  4781. logs.Error(err)
  4782. return
  4783. }
  4784. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4785. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4786. if err != nil {
  4787. logs.Error(err)
  4788. return
  4789. }
  4790. // */
  4791. updateFpdetailByBar(pastureid, barname, v)
  4792. }
  4793. } else {
  4794. 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
  4795. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4796. if err != nil {
  4797. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4798. return
  4799. }
  4800. rows := xlsx1.GetRows(sheetname)
  4801. // 限制10000条,多余的截取掉
  4802. if len(rows) > 10000 {
  4803. rows = rows[:10000]
  4804. }
  4805. dataList := make(map[string][]*upFpdetail, 0)
  4806. for i, row := range rows {
  4807. if i > 0 {
  4808. entry := make(map[string]interface{})
  4809. outentry := make(map[string]interface{})
  4810. for j, colCell := range rows[0] {
  4811. for k, colCell1 := range row {
  4812. if j == k {
  4813. outentry[colCell] = colCell1
  4814. entry[colCell] = colCell1
  4815. }
  4816. }
  4817. }
  4818. inputdata = ""
  4819. a := ""
  4820. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4821. //校验日期格式
  4822. for _, v := range dateParamslist {
  4823. if v == "" {
  4824. continue
  4825. }
  4826. if d, ok := outentry[v]; ok {
  4827. dtime, err := TransfTime(d.(string))
  4828. if err != nil {
  4829. a = v
  4830. break
  4831. }
  4832. outentry[v] = dtime
  4833. }
  4834. }
  4835. if a != "" {
  4836. outentry["error_msg"] = a + " format error"
  4837. error++
  4838. queryData = append(queryData, outentry)
  4839. continue
  4840. }
  4841. a = ""
  4842. //校验必填格式
  4843. for _, v := range requiredParamslist {
  4844. if v == "" {
  4845. continue
  4846. }
  4847. if d, ok := outentry[v]; !ok || d == "" {
  4848. a = v
  4849. break
  4850. }
  4851. }
  4852. if a != "" {
  4853. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4854. error++
  4855. queryData = append(queryData, outentry)
  4856. continue
  4857. }
  4858. a = ""
  4859. //校验数字格式
  4860. for _, v := range numParamslist {
  4861. if v == "" {
  4862. continue
  4863. }
  4864. d, ok := outentry[v]
  4865. if !ok || d == "" {
  4866. outentry[v] = 0
  4867. } else {
  4868. var fl float64
  4869. switch d.(type) {
  4870. case string:
  4871. fl, err = strconv.ParseFloat(d.(string), 64)
  4872. }
  4873. if err != nil || fl < 0 {
  4874. a = v
  4875. break
  4876. }
  4877. }
  4878. }
  4879. if a != "" {
  4880. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4881. error++
  4882. queryData = append(queryData, outentry)
  4883. continue
  4884. }
  4885. errExist := false
  4886. for _, sqlnamestr := range sqlslist {
  4887. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4888. paramslist := strings.Split(paramslists, ",")
  4889. if len(paramslist) > 0 {
  4890. s_params := make([]interface{}, 0)
  4891. for _, value := range paramslist {
  4892. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4893. if tempv, exists := c.Get("jwt_username"); exists {
  4894. s_params = append(s_params, tempv.(string))
  4895. } else {
  4896. s_params = append(s_params, "")
  4897. }
  4898. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4899. s_params = append(s_params, pastureid)
  4900. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4901. ids, err := setting.SnowIds.NextId()
  4902. if err != nil {
  4903. ids = time.Now().UnixNano()
  4904. logging.Info("create SnowIds err", err)
  4905. }
  4906. s_params = append(s_params, ids)
  4907. } else {
  4908. if outentry[strings.Trim(value, " ")] == nil {
  4909. s_params = append(s_params, "")
  4910. } else {
  4911. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4912. }
  4913. }
  4914. }
  4915. outentry["input"] = inputdata
  4916. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4917. if err != nil {
  4918. errExist = true
  4919. // if tx != nil {
  4920. // tx.Rollback()
  4921. // }
  4922. // if tx != nil {
  4923. // tx.Close()
  4924. // }
  4925. msg := geterrmsg(err.Error())
  4926. outentry["error_msg"] = msg
  4927. error++
  4928. queryData = append(queryData, outentry)
  4929. isdone = true
  4930. break
  4931. } else {
  4932. if len(returnmsgmap1) > 0 {
  4933. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4934. // if tx != nil {
  4935. // tx.Rollback()
  4936. // }
  4937. // if tx != nil {
  4938. // tx.Close()
  4939. // }
  4940. msg := geterrmsg(va.(string))
  4941. outentry["error_msg"] = msg
  4942. error++
  4943. queryData = append(queryData, outentry)
  4944. isdone = true
  4945. break
  4946. }
  4947. }
  4948. isdone = false
  4949. }
  4950. }
  4951. }
  4952. if !errExist {
  4953. dataexcel := make(map[string]interface{}, 0)
  4954. if _, ok := outentry["Pen Name"]; ok {
  4955. dataexcel["barname"] = outentry["Pen Name"]
  4956. }
  4957. if _, ok := outentry["Actual Cattle Number"]; ok {
  4958. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4959. }
  4960. if _, ok := outentry["Coefficient(%)"]; ok {
  4961. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4962. }
  4963. if _, ok := outentry["Formula Template"]; ok {
  4964. dataexcel["ftname"] = outentry["Formula Template"]
  4965. }
  4966. if _, ok := outentry["Supplement Formula"]; ok {
  4967. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4968. }
  4969. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4970. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4971. }
  4972. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4973. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4974. }
  4975. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4976. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4977. }
  4978. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4979. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4980. }
  4981. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4982. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4983. }
  4984. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4985. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4986. }
  4987. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4988. if err != nil {
  4989. logs.Error(err)
  4990. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4991. return
  4992. }
  4993. if !existbar {
  4994. continue
  4995. }
  4996. _, 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()
  4997. if err != nil {
  4998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4999. return
  5000. }
  5001. _, 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()
  5002. if err != nil {
  5003. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5004. return
  5005. }
  5006. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5007. if err != nil {
  5008. logs.Error(err)
  5009. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5010. return
  5011. }
  5012. if !existft {
  5013. continue
  5014. }
  5015. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5016. if err != nil {
  5017. logs.Error(err)
  5018. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5019. return
  5020. }
  5021. if !ftexist {
  5022. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5023. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5024. if err != nil {
  5025. logs.Error(err)
  5026. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5027. return
  5028. }
  5029. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5030. if err != nil {
  5031. logs.Error(err)
  5032. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5033. return
  5034. }
  5035. }
  5036. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, 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 !exist {
  5043. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5044. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5045. if err != nil {
  5046. logs.Error(err)
  5047. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5048. return
  5049. }
  5050. }
  5051. var feedpargs []interface{}
  5052. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5053. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5054. if _, ok := dataexcel["ftname"]; ok {
  5055. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5056. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5057. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5058. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5059. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5060. } else {
  5061. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5062. }
  5063. if _, ok := dataexcel["ptsfname"]; ok {
  5064. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5065. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5066. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5067. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5068. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5069. } else {
  5070. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5071. }
  5072. upFeedpSql += " where barname = ? and pastureid = ? "
  5073. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5074. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5075. if err != nil {
  5076. logs.Error(err)
  5077. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5078. return
  5079. }
  5080. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5081. if err != nil {
  5082. logs.Error(err)
  5083. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5084. return
  5085. }
  5086. if !exist1 {
  5087. _, 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) `,
  5088. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5089. if err != nil {
  5090. logs.Error(err)
  5091. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5092. return
  5093. }
  5094. }
  5095. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5096. if err != nil {
  5097. logs.Error(err)
  5098. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5099. return
  5100. }
  5101. if !exist2 {
  5102. _, 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) `,
  5103. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5104. if err != nil {
  5105. logs.Error(err)
  5106. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5107. return
  5108. }
  5109. }
  5110. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5111. if err != nil {
  5112. logs.Error(err)
  5113. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5114. return
  5115. }
  5116. if !exist3 {
  5117. _, 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) `,
  5118. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5119. if err != nil {
  5120. logs.Error(err)
  5121. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5122. return
  5123. }
  5124. }
  5125. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5126. if err != nil {
  5127. logs.Error(err)
  5128. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5129. return
  5130. }
  5131. if !exist4 {
  5132. _, 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) `,
  5133. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5134. if err != nil {
  5135. logs.Error(err)
  5136. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5137. return
  5138. }
  5139. }
  5140. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5141. if err != nil {
  5142. logs.Error(err)
  5143. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5144. return
  5145. }
  5146. if !exist5 {
  5147. _, 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) `,
  5148. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5149. if err != nil {
  5150. logs.Error(err)
  5151. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5152. return
  5153. }
  5154. }
  5155. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5156. if err != nil {
  5157. logs.Error(err)
  5158. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5159. return
  5160. }
  5161. if !exist6 {
  5162. _, 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) `,
  5163. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5164. if err != nil {
  5165. logs.Error(err)
  5166. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5167. return
  5168. }
  5169. }
  5170. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5171. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5172. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5173. and pastureid = ? and times = ?`
  5174. var fpdargs1 []interface{}
  5175. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5176. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5177. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5178. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5179. if err != nil {
  5180. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5181. return
  5182. }
  5183. var fpdargs2 []interface{}
  5184. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5185. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5186. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5187. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5188. if err != nil {
  5189. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5190. return
  5191. }
  5192. var fpdargs3 []interface{}
  5193. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5194. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5195. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5196. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5197. if err != nil {
  5198. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5199. return
  5200. }
  5201. var fpdargs4 []interface{}
  5202. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5203. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5204. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5205. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5206. if err != nil {
  5207. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5208. return
  5209. }
  5210. var fpdargs5 []interface{}
  5211. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5212. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5213. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5214. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5215. if err != nil {
  5216. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5217. return
  5218. }
  5219. var fpdargs6 []interface{}
  5220. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5221. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5222. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5223. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5224. if err != nil {
  5225. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5226. return
  5227. }
  5228. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5229. 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()
  5230. if err != nil {
  5231. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5232. return
  5233. }
  5234. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5235. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5236. upFpdetailList := make([]*upFpdetail, 0)
  5237. for _, newfpd := range newList {
  5238. for _, oldfpd := range oldFpdList {
  5239. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5240. var oldweight, newweight float64
  5241. if oldfpd["weight"] != nil {
  5242. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5243. }
  5244. if newfpd["weight"] != nil {
  5245. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5246. }
  5247. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5248. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5249. Old: oldweight,
  5250. New: newweight,
  5251. Times: newfpd["times"].(int64),
  5252. Ptid: newfpd["ptid"].(int64),
  5253. Fweight: fweight,
  5254. Id: oldfpd["id"].(int64),
  5255. })
  5256. break
  5257. }
  5258. }
  5259. }
  5260. // fmt.Println(dataexcel["barname"])
  5261. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5262. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5263. }
  5264. }
  5265. if !isdone {
  5266. ok++
  5267. isdone = true
  5268. }
  5269. }
  5270. for barname, v := range dataList {
  5271. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5272. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5273. if err != nil {
  5274. logs.Error(err)
  5275. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5276. return
  5277. }
  5278. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5279. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5280. if err != nil {
  5281. logs.Error(err)
  5282. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5283. return
  5284. }
  5285. updateFpdetailByBar(pastureid, barname, v)
  5286. }
  5287. }
  5288. data := make(map[string]interface{})
  5289. data["result"] = queryData
  5290. data["success"] = ok
  5291. data["err_count"] = error
  5292. appG.Response(http.StatusOK, e.SUCCESS, data)
  5293. }
  5294. type upFpdetail struct {
  5295. Old float64
  5296. New float64
  5297. Times int64
  5298. Ptid int64
  5299. Fweight float64
  5300. Id int64
  5301. // Ptsid string
  5302. }
  5303. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5304. tx := restful.Engine.NewSession()
  5305. defer tx.Close()
  5306. tx.Begin()
  5307. 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 `,
  5308. pastureid, barname).Query().List()
  5309. if err != nil {
  5310. logs.Error(err)
  5311. }
  5312. for _, fpd := range fpdList {
  5313. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5314. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5315. pastureid, fpd["id"], fpd["times"]).Query().List()
  5316. if err != nil {
  5317. tx.Rollback()
  5318. logs.Error(err)
  5319. return err
  5320. }
  5321. var lweight float64
  5322. for _, lppland := range lpplandList {
  5323. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5324. lweight += lweight1
  5325. }
  5326. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5327. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5328. if fpdweight >= ptuse && lweight == ptuse {
  5329. continue
  5330. } else {
  5331. if lweight <= fpdweight {
  5332. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5333. if err != nil {
  5334. tx.Rollback()
  5335. logs.Error(err)
  5336. return err
  5337. }
  5338. } else {
  5339. weight := lweight - fpdweight
  5340. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5341. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5342. if err != nil {
  5343. tx.Rollback()
  5344. logs.Error(err)
  5345. return err
  5346. }
  5347. for _, lppland := range lpplandList {
  5348. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5349. if weight >= lpplandlweight {
  5350. weight = weight - lpplandlweight
  5351. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5352. if err != nil {
  5353. tx.Rollback()
  5354. logs.Error(err)
  5355. return err
  5356. }
  5357. } else {
  5358. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5359. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5360. if err != nil {
  5361. tx.Rollback()
  5362. logs.Error(err)
  5363. return err
  5364. }
  5365. weight = 0
  5366. break
  5367. }
  5368. }
  5369. }
  5370. }
  5371. }
  5372. for _, list := range dataList {
  5373. ftmap := make(map[string]interface{})
  5374. ftmap["old"] = list.Old
  5375. ftmap["new"] = list.New
  5376. ftmap["times"] = list.Times
  5377. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5378. ftmap["ptsid"] = ""
  5379. // fmt.Println(ftmap)
  5380. // 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 ,
  5381. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5382. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5383. // UNION
  5384. fpdDataList, err := tx.SQL(`
  5385. 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 ,
  5386. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5387. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5388. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5389. if err != nil {
  5390. tx.Rollback()
  5391. logs.Error(err)
  5392. }
  5393. for _, fpd := range fpdDataList {
  5394. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5395. // fttype := -1
  5396. // if fpd["fttype"].(string) == "1" {
  5397. fttype := 1
  5398. // }
  5399. var fweight float64
  5400. var lweight float64
  5401. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5402. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5403. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5404. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5405. join tmr t on t.id = lpp.tmrid
  5406. where lppland.fpdid =?
  5407. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5408. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5409. if err != nil {
  5410. tx.Rollback()
  5411. logs.Error(err)
  5412. }
  5413. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5414. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5415. // 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
  5416. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5417. var w float64
  5418. var status int
  5419. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5420. if weight >= 0 {
  5421. continue
  5422. }
  5423. w = weight
  5424. status = 0
  5425. } else {
  5426. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5427. // continue
  5428. // }
  5429. w = weight
  5430. status = 1
  5431. }
  5432. // for _, lppland := range lpplandtl1List {
  5433. // lweight += lppland.Lweight
  5434. // }
  5435. for _, lppland := range lpplandtl1List {
  5436. lpplandInfo := new(lpplandtlInfo)
  5437. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5438. lweight = lpplandInfo.Lweight
  5439. if status == 1 {
  5440. // if w <= lppland.Lweight {
  5441. if lppland.Maxweight <= lweight {
  5442. continue
  5443. }
  5444. if w+lweight <= lppland.Maxweight {
  5445. lppland.Lweight += w
  5446. lweight += w
  5447. fweight += w
  5448. w = 0
  5449. } else {
  5450. w = w - (lppland.Maxweight - lweight)
  5451. n := (lppland.Maxweight - lweight)
  5452. lppland.Lweight = lppland.Lweight + n
  5453. lweight += n
  5454. fweight += n
  5455. }
  5456. } else {
  5457. if lppland.Lweight == 0 {
  5458. continue
  5459. }
  5460. if w+lppland.Lweight >= 0 {
  5461. lppland.Lweight = lppland.Lweight + w
  5462. lweight = lweight + w
  5463. fweight = fweight + w
  5464. w = 0
  5465. } else {
  5466. w = w + lppland.Lweight
  5467. lweight = lweight - lppland.Lweight
  5468. fweight = fweight - lppland.Lweight
  5469. lppland.Lweight = 0
  5470. }
  5471. }
  5472. if lppland.Lweight > 0 {
  5473. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5474. if err != nil {
  5475. tx.Rollback()
  5476. logs.Error(err)
  5477. return err
  5478. }
  5479. } else {
  5480. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5481. if err != nil {
  5482. tx.Rollback()
  5483. logs.Error(err)
  5484. return err
  5485. }
  5486. }
  5487. if w == 0 {
  5488. break
  5489. }
  5490. }
  5491. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5492. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5493. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5494. if err != nil {
  5495. tx.Rollback()
  5496. logs.Error(err)
  5497. }
  5498. if w == 0 {
  5499. break
  5500. }
  5501. }
  5502. }
  5503. }
  5504. err = tx.Commit()
  5505. if err != nil {
  5506. logs.Error(err)
  5507. tx.Rollback()
  5508. return err
  5509. }
  5510. now := time.Now()
  5511. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5512. if err != nil {
  5513. logs.Error(err)
  5514. return nil
  5515. }
  5516. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5517. if err != nil {
  5518. logs.Error(err)
  5519. return nil
  5520. }
  5521. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5522. if err != nil {
  5523. logs.Error(err)
  5524. return nil
  5525. }
  5526. for _, newLpplandtl1 := range newLpplandtl1List {
  5527. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5528. background,cowcount,ccountradio,lweighthis,createdate)
  5529. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5530. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5531. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5532. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5533. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5534. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5535. if err != nil {
  5536. logs.Error(err)
  5537. // appG.Response(http.StatusOK, e.ERROR, false)
  5538. return err
  5539. }
  5540. }
  5541. for _, newFpd := range newFpdDataList {
  5542. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5543. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5544. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5545. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5546. if err != nil {
  5547. logs.Error(err)
  5548. // appG.Response(http.StatusOK, e.ERROR, false)
  5549. return err
  5550. }
  5551. }
  5552. for _, newFeedp := range newFeedpList {
  5553. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5554. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5555. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5556. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5557. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5558. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5559. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5560. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5561. if err != nil {
  5562. logs.Error(err)
  5563. // appG.Response(http.StatusOK, e.ERROR, false)
  5564. return err
  5565. }
  5566. }
  5567. return nil
  5568. }
  5569. func DeleteFTdetail(c *gin.Context) {
  5570. appG := app.Gin{C: c}
  5571. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5572. fsion := gofasion.NewFasion(string(dataByte))
  5573. parammaps := fsion.Get("parammaps")
  5574. pastureid := parammaps.Get("pastureid").ValueStr()
  5575. ftid := parammaps.Get("ftid").ValueStr()
  5576. tx := restful.Engine.NewSession()
  5577. defer tx.Close()
  5578. tx.Begin()
  5579. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5580. if err != nil {
  5581. tx.Rollback()
  5582. logs.Error(err)
  5583. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5584. return
  5585. }
  5586. if parammaps.Get("type").ValueStr() == "1" {
  5587. _, err := tx.SQL(`UPDATE feedp fp
  5588. set
  5589. fp.ftweight= IFNULL(IF(
  5590. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5591. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5592. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5594. ),0),fp.feedweight = IFNULL(IF(
  5595. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5596. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5597. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5598. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5599. ),0) +ifnull(fp.supplyweight,0)
  5600. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5601. if err != nil {
  5602. tx.Rollback()
  5603. logs.Error(err)
  5604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5605. return
  5606. }
  5607. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5608. _, err = tx.SQL(`
  5609. UPDATE fpdetail fpd
  5610. INNER JOIN feedp fp
  5611. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5612. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5613. ptuse= 0
  5614. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5615. if err != nil {
  5616. tx.Rollback()
  5617. logs.Error(err)
  5618. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5619. return
  5620. }
  5621. } else {
  5622. _, err := tx.SQL(`UPDATE feedp fp
  5623. SET
  5624. fp.supplyweight= IFNULL(IF(
  5625. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5626. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5627. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5629. ),0),fp.feedweight = IFNULL(IF(
  5630. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5631. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5632. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5633. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5634. ),0) + ifnull(fp.supplyweight,0)
  5635. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5636. if err != nil {
  5637. tx.Rollback()
  5638. logs.Error(err)
  5639. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5640. return
  5641. }
  5642. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5643. _, err = tx.SQL(`
  5644. UPDATE fpdetail fpd
  5645. INNER JOIN feedp fp
  5646. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5647. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5648. ptsrate = 0
  5649. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5650. if err != nil {
  5651. tx.Rollback()
  5652. logs.Error(err)
  5653. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5654. return
  5655. }
  5656. }
  5657. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5658. if err != nil {
  5659. tx.Rollback()
  5660. logs.Error(err)
  5661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5662. return
  5663. }
  5664. err = tx.Commit()
  5665. if err != nil {
  5666. tx.Rollback()
  5667. logs.Error(err)
  5668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5669. return
  5670. }
  5671. appG.Response(http.StatusOK, e.SUCCESS, true)
  5672. }
  5673. func DeleteSpillageAll(c *gin.Context) {
  5674. appG := app.Gin{C: c}
  5675. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5676. fsion := gofasion.NewFasion(string(dataByte))
  5677. parammaps := fsion.Get("parammaps")
  5678. pastureid := parammaps.Get("pastureid").ValueStr()
  5679. times := parammaps.Get("times").ValueStr()
  5680. barid := parammaps.Get("barid").ValueStr()
  5681. tx := restful.Engine.NewSession()
  5682. defer tx.Close()
  5683. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5684. if err != nil {
  5685. logs.Error(err)
  5686. appG.Response(http.StatusOK, e.ERROR, false)
  5687. return
  5688. }
  5689. now := time.Now()
  5690. for _, item := range lpplandtl1List {
  5691. go func(item map[string]interface{}) {
  5692. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5693. background,cowcount,ccountradio,lweighthis,createdate)
  5694. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5695. item["pastureid"], item["lppid"], item["barid"],
  5696. item["barname"], item["fpdid"], item["fttype"],
  5697. item["lweight"], item["sort"], item["tmrid"],
  5698. item["tmrname"], item["background"], item["cowcount"],
  5699. item["ccountradio"], item["lweighthis"], now).Execute()
  5700. if err != nil {
  5701. logs.Error(err)
  5702. appG.Response(http.StatusOK, e.ERROR, false)
  5703. return
  5704. }
  5705. }(item)
  5706. }
  5707. tx.Begin()
  5708. _, 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()
  5709. if err != nil {
  5710. tx.Rollback()
  5711. logs.Error(err)
  5712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5713. return
  5714. }
  5715. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5716. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5717. if err != nil {
  5718. tx.Rollback()
  5719. logs.Error(err)
  5720. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5721. return
  5722. }
  5723. err = tx.Commit()
  5724. if err != nil {
  5725. tx.Rollback()
  5726. logs.Error(err)
  5727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5728. return
  5729. }
  5730. appG.Response(http.StatusOK, e.SUCCESS, true)
  5731. }
  5732. func GetTMRListEnableTypeAll(c *gin.Context) {
  5733. appG := app.Gin{C: c}
  5734. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5735. fsion := gofasion.NewFasion(string(dataByte))
  5736. parammaps := fsion.Get("parammaps")
  5737. pastureid := parammaps.Get("pastureid").ValueStr()
  5738. tx := restful.Engine.NewSession()
  5739. defer tx.Close()
  5740. dataList, err := tx.SQL(`SELECT
  5741. eqcode,
  5742. tname,
  5743. datacaptureno,
  5744. trim(tclassid) tclassid,
  5745. concat(tname,' / ',eqcode) tmrmix,
  5746. d.label tclassname,
  5747. maxstirfeed,
  5748. remark,
  5749. tmr.enable,
  5750. TRIM(tmr.id) id,
  5751. TRIM(tmr.pastureid)pastureid
  5752. FROM
  5753. tmr
  5754. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5755. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5756. ORDER BY id DESC`, pastureid).Query().List()
  5757. if err != nil {
  5758. logs.Error(err)
  5759. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5760. return
  5761. }
  5762. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5763. if err != nil {
  5764. logs.Error(err)
  5765. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5766. return
  5767. }
  5768. var carNum int64
  5769. for _, sysopt := range sysoptData {
  5770. if sysopt["inforvalue"] == nil {
  5771. carNum = 1
  5772. } else {
  5773. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5774. }
  5775. }
  5776. id := 200
  5777. n := 0
  5778. for i := carNum; i > 0; i-- {
  5779. id++
  5780. n++
  5781. data := make(map[string]interface{}, 0)
  5782. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5783. data["tname"] = fmt.Sprintf("任意车%d", n)
  5784. data["datacaptureno"] = -2
  5785. data["tclassid"] = -2
  5786. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5787. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5788. data["maxstirfeed"] = 100000
  5789. data["remark"] = fmt.Sprintf("任意车%d", n)
  5790. data["enable"] = 1
  5791. data["id"] = fmt.Sprintf("%d", id)
  5792. data["pastureid"] = pastureid
  5793. // data := make(map[string]interface{}, 0)
  5794. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5795. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5796. // data["datacaptureno"] = -2
  5797. // data["tclassid"] = -2
  5798. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5799. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5800. // data["maxstirfeed"] = 100000
  5801. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5802. // data["enable"] = 1
  5803. // data["id"] = fmt.Sprintf("%d", id)
  5804. // data["pastureid"] = pastureid
  5805. dataList = append(dataList, data)
  5806. }
  5807. // UNION ALL
  5808. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5809. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5810. }
  5811. func GetFeedpHistory(c *gin.Context) {
  5812. appG := app.Gin{C: c}
  5813. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5814. fsion := gofasion.NewFasion(string(dataByte))
  5815. // parammaps := fsion.Get("parammaps")
  5816. bar := fsion.Get("barname").ValueStr()
  5817. startDate := fsion.Get("startDate").ValueStr()
  5818. endDate := fsion.Get("endDate").ValueStr()
  5819. tx := restful.Engine.NewSession()
  5820. defer tx.Close()
  5821. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5822. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5823. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5824. if err != nil {
  5825. logs.Error(err)
  5826. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5827. return
  5828. }
  5829. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5830. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5831. and createdate between ? and ? order by createdate desc, times asc`, bar, 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. // LastftList, err := tx.SQL(` select tname ,id
  5839. // from feedtemplethistory where id = ?
  5840. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5841. // if err != nil {
  5842. // logs.Error(err)
  5843. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5844. // return
  5845. // }
  5846. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5847. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5848. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5849. if err != nil {
  5850. logs.Error(err)
  5851. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5852. return
  5853. }
  5854. var ftname interface{}
  5855. ftnamestatus := 0
  5856. ftname = feedp["ftname"]
  5857. var lastftid int64
  5858. if len(nextfeedpList) > 0 {
  5859. for _, ft := range nextfeedpList {
  5860. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5861. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5862. lastftid = ft["ftid"].(int64)
  5863. ftnamestatus = 1
  5864. break
  5865. }
  5866. }
  5867. }
  5868. for i, fpd := range fpdList {
  5869. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5870. fpd["weightstatus"] = 0
  5871. fpd["tratiostatus"] = 0
  5872. fpd["ftnamestatus"] = ftnamestatus
  5873. for k, fpd2 := range fpdList {
  5874. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5875. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5876. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5877. fpd["weightstatus"] = 1
  5878. }
  5879. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5880. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5881. fpd["tratiostatus"] = 1
  5882. }
  5883. break
  5884. }
  5885. }
  5886. fpd["barid"] = feedp["barid"]
  5887. fpd["barname"] = feedp["barname"]
  5888. fpd["ccount"] = feedp["ccount"]
  5889. fpd["ratio"] = feedp["ratio"]
  5890. fpd["ccountratio"] = feedp["ccountratio"]
  5891. fpd["ftid"] = feedp["ftid"]
  5892. fpd["ftname"] = ftname
  5893. fpd["ccountstatus"] = 0
  5894. fpd["ccountratiostatus"] = 0
  5895. fpd["ratiostatus"] = 0
  5896. fpd["ftnamestatus"] = 0
  5897. fpd["lastftid"] = lastftid
  5898. for _, next := range nextfeedpList {
  5899. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5900. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5901. fpd["ccountstatus"] = 1
  5902. }
  5903. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5904. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5905. fpd["ccountratiostatus"] = 1
  5906. }
  5907. if next["ratio"].(string) != fpd["ratio"].(string) {
  5908. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5909. fpd["ratiostatus"] = 1
  5910. }
  5911. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5912. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5913. // fpd["ftnamestatus"] = 1
  5914. // }
  5915. }
  5916. }
  5917. }
  5918. }
  5919. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5920. }
  5921. // func GetLpplandtl1History(c *gin.Context) {
  5922. // appG := app.Gin{C: c}
  5923. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5924. // fsion := gofasion.NewFasion(string(dataByte))
  5925. // // parammaps := fsion.Get("parammaps")
  5926. // barid := fsion.Get("barid").ValueStr()
  5927. // startDate := fsion.Get("startDate").ValueStr()
  5928. // endDate := fsion.Get("endDate").ValueStr()
  5929. // tx := restful.Engine.NewSession()
  5930. // defer tx.Close()
  5931. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5932. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5933. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5934. // // if err != nil {
  5935. // // logs.Error(err)
  5936. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5937. // // return
  5938. // // }
  5939. // // for _, feedp := range feedpList {
  5940. // // fmt.Println(feedp)
  5941. // // for i, fpd := range fpdList {
  5942. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5943. // // for k, fpd2 := range fpdList {
  5944. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5945. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5946. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5947. // // }
  5948. // // break
  5949. // // }
  5950. // // }
  5951. // // fpd["barid"] = feedp["barid"]
  5952. // // fpd["barname"] = feedp["barname"]
  5953. // // fpd["ccount"] = feedp["ccount"]
  5954. // // fpd["ratio"] = feedp["ratio"]
  5955. // // fpd["ccountratio"] = feedp["ccountratio"]
  5956. // // fpd["ftid"] = feedp["ftid"]
  5957. // // fpd["ftname"] = feedp["ftname"]
  5958. // // }
  5959. // // }
  5960. // // }
  5961. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5962. // }
  5963. func GetRemind(c *gin.Context) {
  5964. appG := app.Gin{C: c}
  5965. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5966. fsion := gofasion.NewFasion(string(dataByte))
  5967. parammaps := fsion.Get("parammaps")
  5968. pastureid := parammaps.Get("pastureid").ValueStr()
  5969. tx := restful.Engine.NewSession()
  5970. defer tx.Close()
  5971. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5972. if err != nil {
  5973. logs.Error(err)
  5974. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5975. return
  5976. }
  5977. // pastureid = "3"
  5978. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5979. if err != nil {
  5980. logs.Error(err)
  5981. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5982. return
  5983. }
  5984. defer resp.Body.Close()
  5985. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5986. buf.ReadFrom(resp.Body)
  5987. fmt.Println(string(buf.Bytes()))
  5988. respMap := make(map[string]interface{}, 0)
  5989. err = json.Unmarshal(buf.Bytes(), &respMap)
  5990. if err != nil {
  5991. logs.Error(err)
  5992. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5993. return
  5994. }
  5995. for _, data := range dataList {
  5996. r := make(map[string]interface{}, 0)
  5997. r["sys_name"] = ""
  5998. r["service_id"] = ""
  5999. r["pasture_id"] = ""
  6000. r["type_name"] = ""
  6001. r["remind_type_id"] = ""
  6002. r["remind_type"] = ""
  6003. r["push_date"] = ""
  6004. r["push_time"] = ""
  6005. r["interval_time"] = ""
  6006. r["push_limit"] = ""
  6007. r["template_id"] = ""
  6008. r["roles_id"] = ""
  6009. r["users_id"] = ""
  6010. r["date_type"] = ""
  6011. r["cycle_type"] = ""
  6012. data["data"] = r
  6013. for _, resp := range respMap["data"].([]interface{}) {
  6014. resp1 := resp.(map[string]interface{})
  6015. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6016. if resp1["push_time"] == nil {
  6017. resp1["push_time"] = ""
  6018. }
  6019. data["data"] = resp1
  6020. break
  6021. }
  6022. }
  6023. }
  6024. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6025. }
  6026. type NoticeMsgtype struct {
  6027. SysName string `json:"sys_name"`
  6028. PastureId int64 `json:"pasture_id"`
  6029. ServiceId int64 `json:"service_id"`
  6030. TypeName string `json:"type_name"`
  6031. RemindType int64 `json:"remind_type"`
  6032. PushDate int64 `json:"push_date"`
  6033. PushTime string `json:"push_time"`
  6034. IntervalTime int64 `json:"interval_time"`
  6035. PushLimit int64 `json:"push_limit"`
  6036. TemplateId string `json:"template_id"`
  6037. UsersId string `json:"users_id"`
  6038. DateType int64 `json:"date_type"`
  6039. CycleType int64 `json:"cycle_type"`
  6040. DelayTime int64 `json:"delay_time"`
  6041. Status int64 `json:"status"`
  6042. }
  6043. func UpdateRemind(c *gin.Context) {
  6044. appG := app.Gin{C: c}
  6045. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6046. parammaps := gofasion.NewFasion(string(dataByte))
  6047. // parammaps := fsion.Get("parammaps")
  6048. // user := parammaps.Get("user").ValueStr()
  6049. id := parammaps.Get("id").ValueInt64()
  6050. noticeMsgtype := new(NoticeMsgtype)
  6051. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6052. noticeMsgtype.ServiceId = id
  6053. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6054. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6055. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6056. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6057. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6058. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6059. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6060. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6061. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6062. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6063. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6064. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6065. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6066. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6067. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6068. //TODO
  6069. noticeMsgtype.SysName = "tmrWatch"
  6070. userList := parammaps.Get("user").Array()
  6071. var userstr []string
  6072. for _, user := range userList {
  6073. userstr = append(userstr, user.ValueStr())
  6074. }
  6075. tx := restful.Engine.NewSession()
  6076. defer tx.Close()
  6077. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6078. if err != nil {
  6079. logs.Error(err)
  6080. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6081. return
  6082. }
  6083. // var jsonStr = []byte(noticeMsgtype
  6084. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6085. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6086. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6087. req.Header.Set("Content-Type", "application/json")
  6088. client := &http.Client{}
  6089. resp, err := client.Do(req)
  6090. if err != nil {
  6091. logs.Error(err)
  6092. }
  6093. defer resp.Body.Close()
  6094. body, _ := ioutil.ReadAll(resp.Body)
  6095. fmt.Println("response Body:", string(body))
  6096. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6097. if err != nil {
  6098. logs.Error(err)
  6099. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6100. return
  6101. }
  6102. defer getresp.Body.Close()
  6103. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6104. buf.ReadFrom(getresp.Body)
  6105. // fmt.Println(string(buf.Bytes()))
  6106. respMap := make(map[string]interface{}, 0)
  6107. err = json.Unmarshal(buf.Bytes(), &respMap)
  6108. if err != nil {
  6109. logs.Error(err)
  6110. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6111. return
  6112. }
  6113. for _, resp := range respMap["data"].([]interface{}) {
  6114. resp1 := resp.(map[string]interface{})
  6115. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6116. if err != nil {
  6117. logs.Error(err)
  6118. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6119. return
  6120. }
  6121. }
  6122. appG.Response(http.StatusOK, e.SUCCESS, true)
  6123. }
  6124. func GetSpillageallHistory(c *gin.Context) {
  6125. appG := app.Gin{C: c}
  6126. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6127. parammaps := gofasion.NewFasion(string(dataByte))
  6128. barname := parammaps.Get("barname").ValueStr()
  6129. pastureid := parammaps.Get("pastureid").ValueStr()
  6130. startdate := parammaps.Get("startDate").ValueStr()
  6131. enddate := parammaps.Get("endDate").ValueStr()
  6132. tx := restful.Engine.NewSession()
  6133. defer tx.Close()
  6134. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,
  6135. DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate ,u.username
  6136. from lpplandtl1history lppland
  6137. join lpplan lpp on lpp.id = lppland.lppid
  6138. left join user u on u.id = lppland.userId
  6139. where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6140. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6141. if err != nil {
  6142. logs.Error(err)
  6143. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6144. return
  6145. }
  6146. respMap := make([]map[string]interface{}, 0)
  6147. data := make(map[interface{}]interface{})
  6148. for _, history := range historyList {
  6149. data[history["createdate"]] = history["createdate"]
  6150. }
  6151. createList := []string{}
  6152. for _, v := range data {
  6153. createList = append(createList, v.(string))
  6154. }
  6155. // sort.Sort()
  6156. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6157. sort.Slice(createList, func(i, j int) bool {
  6158. return createList[i] > createList[j]
  6159. })
  6160. for _, v := range createList {
  6161. a := make(map[string]interface{})
  6162. a["createdate"] = data[v]
  6163. // createList = append(createList, v.(string))
  6164. respMap = append(respMap, a)
  6165. }
  6166. number := 0
  6167. dataMap := make([]interface{}, 0)
  6168. for k, resp := range respMap {
  6169. createdate := resp["createdate"].(string)
  6170. var nextcreatedate string
  6171. if len(respMap) > k+1 {
  6172. nextcreatedate = respMap[k+1]["createdate"].(string)
  6173. }
  6174. // dataList := make(map[string][]interface{})
  6175. // list := make(map[string]interface{})
  6176. times := make(map[interface{}]int)
  6177. for _, history := range historyList {
  6178. // List := make(map[interface{}][]interface{})
  6179. i := 0
  6180. if history["createdate"].(string) == createdate {
  6181. times[history["times"]]++
  6182. data := make(map[string]interface{})
  6183. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6184. // exist := false
  6185. if nextcreatedate != "" {
  6186. for _, history1 := range historyList {
  6187. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6188. history1["times"].(int64) == history["times"].(int64) {
  6189. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6190. break
  6191. // exist = true
  6192. }
  6193. }
  6194. }
  6195. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6196. i++
  6197. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6198. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6199. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6200. // resp["times"] = history["times"]
  6201. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6202. data1 := make(map[string]interface{})
  6203. data1["times"] = history["times"]
  6204. data1["empname"] = history["username"]
  6205. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6206. data1["createdate"] = resp["createdate"]
  6207. // fmt.Println(dataList)
  6208. dataMap = append(dataMap, data1)
  6209. }
  6210. if i > number {
  6211. number = i
  6212. }
  6213. // respMap = append(respMap, dataList)
  6214. }
  6215. // for k, data := range dataList {
  6216. // resp[k] = data
  6217. // }
  6218. // resp["data"] = dataList
  6219. }
  6220. // resp := make(map[string]interface{})
  6221. // sort.Strings(createList)
  6222. //
  6223. // for _, create := range createList {
  6224. // for _, r := range respMap {
  6225. // if create == r["createdate"].(string) {
  6226. // resp[create] = r
  6227. // break
  6228. // }
  6229. // }
  6230. // }
  6231. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6232. var trainsList []interface{}
  6233. for i := 0; i < number; i++ {
  6234. trains := make(map[string]interface{})
  6235. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6236. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6237. trainsList = append(trainsList, trains)
  6238. }
  6239. respdata := make(map[string]interface{})
  6240. respdata["data"] = dataMap
  6241. respdata["trains"] = trainsList
  6242. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6243. }
  6244. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6245. appG := app.Gin{C: c}
  6246. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6247. parammaps := gofasion.NewFasion(string(dataByte))
  6248. ftid := parammaps.Get("ftid").ValueInt64()
  6249. lastftid := parammaps.Get("lastftid").ValueInt64()
  6250. pastureid := parammaps.Get("pastureid").ValueInt64()
  6251. // createdate := parammaps.Get("createdate").ValueStr()
  6252. tx := restful.Engine.NewSession()
  6253. defer tx.Close()
  6254. data := make(map[string]interface{})
  6255. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6256. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6257. if err != nil {
  6258. logs.Error(err)
  6259. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6260. return
  6261. }
  6262. feedtemplet := make(map[string]interface{})
  6263. for _, f := range feedtempletList {
  6264. feedtemplet = f
  6265. }
  6266. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6267. if err != nil {
  6268. logs.Error(err)
  6269. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6270. return
  6271. }
  6272. feedtemplet["fit"] = fitList
  6273. data["current"] = feedtemplet
  6274. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6275. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6276. if err != nil {
  6277. logs.Error(err)
  6278. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6279. return
  6280. }
  6281. lastfeedtemplet := make(map[string]interface{})
  6282. for _, f := range lastfeedtempletList {
  6283. lastfeedtemplet = f
  6284. }
  6285. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6286. if err != nil {
  6287. logs.Error(err)
  6288. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6289. return
  6290. }
  6291. lastfeedtemplet["fit"] = lastfitList
  6292. data["last"] = lastfeedtemplet
  6293. appG.Response(http.StatusOK, e.SUCCESS, data)
  6294. }
  6295. func GetFeedtempletHistory(c *gin.Context) {
  6296. appG := app.Gin{C: c}
  6297. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6298. parammaps := gofasion.NewFasion(string(dataByte))
  6299. ftid := parammaps.Get("ftid").ValueStr()
  6300. pastureid := parammaps.Get("pastureid").ValueInt64()
  6301. start := parammaps.Get("startdate").ValueStr()
  6302. end := parammaps.Get("enddate").ValueStr()
  6303. tx := restful.Engine.NewSession()
  6304. defer tx.Close()
  6305. 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 ?
  6306. and id = ? and pastureid = ? order by createdate desc `,
  6307. start, end, ftid, pastureid).Query().List()
  6308. if err != nil {
  6309. logs.Error(err)
  6310. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6311. return
  6312. }
  6313. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6314. ftid, pastureid).Query().List()
  6315. if err != nil {
  6316. logs.Error(err)
  6317. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6318. return
  6319. }
  6320. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6321. for i, ft := range ftList {
  6322. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6323. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6324. (select empname from user where id = fit.userId) empname,
  6325. 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
  6326. where fit.fitid = ?
  6327. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6328. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6329. if err != nil {
  6330. logs.Error(err)
  6331. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6332. return
  6333. }
  6334. ft["createdate"] = ft["createdate1"]
  6335. // data["tname"] = ft["tname"]
  6336. // data["tcode"] = ft["tcode"]
  6337. // data["tcolor"] = ft["tcolor"]
  6338. // data["fttype"] = ft["fttype"]
  6339. // data["ccname"] = ft["ccname"]
  6340. // data["source"] = ft["source"]
  6341. // data["version"] = ft["version"]
  6342. // data["remark"] = ft["remark"]
  6343. for n, ft2 := range ftList {
  6344. if i < n {
  6345. if ft["tname"].(string) != ft2["tname"].(string) {
  6346. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6347. }
  6348. if _, ok := ft["tcode"]; ok {
  6349. if _, ok := ft2["tcode"]; ok {
  6350. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6351. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6352. }
  6353. }
  6354. }
  6355. if _, ok := ft["tcolor"]; ok {
  6356. if _, ok := ft2["tcolor"]; ok {
  6357. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6358. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6359. }
  6360. }
  6361. }
  6362. if _, ok := ft["fttype"]; ok {
  6363. if _, ok := ft2["fttype"]; ok {
  6364. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6365. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6366. }
  6367. }
  6368. }
  6369. if _, ok := ft["ccname"]; ok {
  6370. if _, ok := ft2["ccname"]; ok {
  6371. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6372. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6373. }
  6374. }
  6375. }
  6376. if _, ok := ft["source"]; ok {
  6377. if _, ok := ft2["source"]; ok {
  6378. if ft["source"].(string) != ft2["source"].(string) {
  6379. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6380. }
  6381. }
  6382. }
  6383. if _, ok := ft["version"]; ok {
  6384. if _, ok := ft2["version"]; ok {
  6385. if ft["version"].(int64) != ft2["version"].(int64) {
  6386. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6387. }
  6388. }
  6389. }
  6390. if _, ok := ft["remark"]; ok {
  6391. if _, ok := ft2["remark"]; ok {
  6392. if ft["remark"].(string) != ft2["remark"].(string) {
  6393. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6394. }
  6395. }
  6396. }
  6397. break
  6398. }
  6399. }
  6400. dataList := make([]map[string]interface{}, 0)
  6401. if len(fithisList) > 0 {
  6402. for _, fit := range fithisList {
  6403. data := make(map[string]interface{})
  6404. data["feedgroup"] = fit["feedgroup"]
  6405. data["fname"] = fit["fname"]
  6406. data["empname"] = fit["empname"]
  6407. if fit["Eweight"] != nil {
  6408. if fit["Eweight"].(string) != fit["weight"].(string) {
  6409. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6410. } else {
  6411. data["fweight"] = fit["Eweight"]
  6412. }
  6413. data["fweightstatus"] = 1
  6414. } else {
  6415. data["fweight"] = fit["weight"]
  6416. data["fweightstatus"] = 0
  6417. }
  6418. data["autosecond"] = fit["autosecond"]
  6419. // data["tname"] = ft["tname"]
  6420. // data["tcode"] = ft["tcode"]
  6421. // data["tcolor"] = ft["tcolor"]
  6422. // data["fttype"] = ft["fttype"]
  6423. // data["ccname"] = ft["ccname"]
  6424. // data["source"] = ft["source"]
  6425. // data["version"] = ft["version"]
  6426. // data["remark"] = ft["remark"]
  6427. // data["createdate"] = ft["createdate1"]
  6428. // ft["fit"] = data
  6429. dataList = append(dataList, data)
  6430. }
  6431. } else {
  6432. for _, fit := range ftdetailList {
  6433. data := make(map[string]interface{})
  6434. data["feedgroup"] = fit["feedgroup"]
  6435. data["fname"] = fit["fname"]
  6436. // if fit["Eweight"] != nil {
  6437. // data["weight"] = fit["Eweight"]
  6438. // } else {
  6439. data["fweight"] = fit["fweight"]
  6440. // }
  6441. data["autosecond"] = fit["autosecond"]
  6442. // ft["fit"] = data
  6443. dataList = append(dataList, data)
  6444. }
  6445. }
  6446. ft["fit"] = dataList
  6447. }
  6448. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6449. }
  6450. func UpdateMaterialTMR(c *gin.Context) {
  6451. appG := app.Gin{C: c}
  6452. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6453. parammaps := gofasion.NewFasion(string(dataByte))
  6454. tmrid := parammaps.Get("tmrid").ValueStr()
  6455. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6456. lppid := parammaps.Get("lppid").ValueStr()
  6457. times := parammaps.Get("times").ValueStr()
  6458. pastureid := parammaps.Get("pastureid").ValueStr()
  6459. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6460. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6461. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6462. tx := restful.Engine.NewSession()
  6463. defer tx.Close()
  6464. tx.Begin()
  6465. if tmrid != "1000" {
  6466. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6467. if err != nil {
  6468. logs.Error(err)
  6469. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6470. return
  6471. }
  6472. var maxstirfeed float64
  6473. for _, tmr := range tmrList {
  6474. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6475. }
  6476. if status == 0 {
  6477. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6478. if err != nil {
  6479. tx.Rollback()
  6480. logs.Error(err)
  6481. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6482. return
  6483. }
  6484. var lweight float64
  6485. for _, item := range lpplandtl1List {
  6486. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6487. lweight += fl
  6488. }
  6489. if lweight > maxstirfeed {
  6490. lweight = lweight - maxstirfeed
  6491. } else {
  6492. lweight = 0
  6493. }
  6494. if lweight > 0 {
  6495. lweight1 := lweight / float64(len(lpplandtl1List))
  6496. number := 0
  6497. for _, item := range lpplandtl1List {
  6498. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6499. if lweight1 >= fl {
  6500. number++
  6501. }
  6502. }
  6503. lweight := lweight / float64((len(lpplandtl1List) - number))
  6504. for _, item := range lpplandtl1List {
  6505. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6506. if lweight1 >= fl {
  6507. continue
  6508. }
  6509. if tmrtype == "1" {
  6510. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6511. if err != nil {
  6512. tx.Rollback()
  6513. logs.Error(err)
  6514. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6515. return
  6516. }
  6517. } else if tmrtype == "2" {
  6518. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6519. if err != nil {
  6520. tx.Rollback()
  6521. logs.Error(err)
  6522. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6523. return
  6524. }
  6525. }
  6526. if item["fttype"].(int64) == 0 {
  6527. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6528. if err != nil {
  6529. tx.Rollback()
  6530. logs.Error(err)
  6531. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6532. return
  6533. }
  6534. } else {
  6535. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6536. if err != nil {
  6537. tx.Rollback()
  6538. logs.Error(err)
  6539. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6540. return
  6541. }
  6542. }
  6543. }
  6544. } else {
  6545. for _, item := range lpplandtl1List {
  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 if status == 1 {
  6567. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", 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. var lweight float64
  6575. for _, item := range lpplandtl1List {
  6576. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6577. lweight += fl
  6578. }
  6579. if lweight > maxstirfeed {
  6580. lweight = lweight - maxstirfeed
  6581. } else {
  6582. lweight = 0
  6583. }
  6584. for _, item := range lpplandtl1List {
  6585. if lweight > 0 {
  6586. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6587. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6588. if fl >= lweight {
  6589. item["lweight"] = fl - lweight
  6590. lweight = 0
  6591. if tmrtype == "1" {
  6592. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], 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. } else if tmrtype == "2" {
  6600. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6601. if err != nil {
  6602. logs.Error(err)
  6603. tx.Rollback()
  6604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6605. return
  6606. }
  6607. }
  6608. if item["fttype"].(int64) == 0 {
  6609. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6610. if err != nil {
  6611. logs.Error(err)
  6612. tx.Rollback()
  6613. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6614. return
  6615. }
  6616. } else {
  6617. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6618. if err != nil {
  6619. logs.Error(err)
  6620. tx.Rollback()
  6621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6622. return
  6623. }
  6624. }
  6625. } else {
  6626. lweight = lweight - fl
  6627. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6628. if err != nil {
  6629. logs.Error(err)
  6630. tx.Rollback()
  6631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6632. return
  6633. }
  6634. if item["fttype"].(int64) == 0 {
  6635. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6636. if err != nil {
  6637. logs.Error(err)
  6638. tx.Rollback()
  6639. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6640. return
  6641. }
  6642. } else {
  6643. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6644. if err != nil {
  6645. logs.Error(err)
  6646. tx.Rollback()
  6647. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6648. return
  6649. }
  6650. }
  6651. }
  6652. } else {
  6653. // 自走式
  6654. if tmrtype == "1" {
  6655. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6656. if err != nil {
  6657. logs.Error(err)
  6658. tx.Rollback()
  6659. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6660. return
  6661. }
  6662. } else if tmrtype == "2" {
  6663. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6664. if err != nil {
  6665. logs.Error(err)
  6666. tx.Rollback()
  6667. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6668. return
  6669. }
  6670. }
  6671. }
  6672. }
  6673. } else {
  6674. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6675. if err != nil {
  6676. logs.Error(err)
  6677. tx.Rollback()
  6678. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6679. return
  6680. }
  6681. for _, item := range lpplandtl1List {
  6682. if item["fttype"].(int64) == 0 {
  6683. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6684. if err != nil {
  6685. logs.Error(err)
  6686. tx.Rollback()
  6687. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6688. return
  6689. }
  6690. } else {
  6691. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6692. if err != nil {
  6693. logs.Error(err)
  6694. tx.Rollback()
  6695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6696. return
  6697. }
  6698. }
  6699. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6700. if err != nil {
  6701. logs.Error(err)
  6702. tx.Rollback()
  6703. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6704. return
  6705. }
  6706. }
  6707. }
  6708. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. } else {
  6716. if status == 2 {
  6717. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6718. if err != nil {
  6719. logs.Error(err)
  6720. tx.Rollback()
  6721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6722. return
  6723. }
  6724. for _, item := range lpplandtl1List {
  6725. if item["fttype"].(int64) == 0 {
  6726. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6727. if err != nil {
  6728. logs.Error(err)
  6729. tx.Rollback()
  6730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6731. return
  6732. }
  6733. } else {
  6734. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6735. if err != nil {
  6736. logs.Error(err)
  6737. tx.Rollback()
  6738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6739. return
  6740. }
  6741. }
  6742. }
  6743. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6744. if err != nil {
  6745. logs.Error(err)
  6746. tx.Rollback()
  6747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6748. return
  6749. }
  6750. } else {
  6751. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6752. if err != nil {
  6753. logs.Error(err)
  6754. tx.Rollback()
  6755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6756. return
  6757. }
  6758. }
  6759. }
  6760. err := tx.Commit()
  6761. if err != nil {
  6762. logs.Error(err)
  6763. tx.Rollback()
  6764. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6765. return
  6766. }
  6767. appG.Response(http.StatusOK, e.SUCCESS, true)
  6768. }
  6769. func UpdateMaterialTMRDate(c *gin.Context) {
  6770. appG := app.Gin{C: c}
  6771. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6772. parammaps := gofasion.NewFasion(string(dataByte))
  6773. tmrid := parammaps.Get("tmrid").ValueStr()
  6774. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6775. lppid := parammaps.Get("lppid").ValueStr()
  6776. times := parammaps.Get("times").ValueStr()
  6777. pastureid := parammaps.Get("pastureid").ValueStr()
  6778. date := parammaps.Get("date").ValueStr()
  6779. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6780. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6781. tx := restful.Engine.NewSession()
  6782. defer tx.Close()
  6783. tx.Begin()
  6784. if tmrid != "1000" {
  6785. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6786. if err != nil {
  6787. logs.Error(err)
  6788. tx.Rollback()
  6789. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6790. return
  6791. }
  6792. var maxstirfeed float64
  6793. for _, tmr := range tmrList {
  6794. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6795. }
  6796. if status == 0 {
  6797. 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()
  6798. if err != nil {
  6799. logs.Error(err)
  6800. tx.Rollback()
  6801. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6802. return
  6803. }
  6804. var lweight float64
  6805. for _, item := range lpplandtl1List {
  6806. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6807. lweight += fl
  6808. }
  6809. if lweight > maxstirfeed {
  6810. lweight = lweight - maxstirfeed
  6811. } else {
  6812. lweight = 0
  6813. }
  6814. if lweight > 0 {
  6815. lweight1 := lweight / float64(len(lpplandtl1List))
  6816. number := 0
  6817. for _, item := range lpplandtl1List {
  6818. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6819. if lweight1 >= fl {
  6820. number++
  6821. }
  6822. }
  6823. lweight := lweight / float64((len(lpplandtl1List) - number))
  6824. for _, item := range lpplandtl1List {
  6825. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6826. if lweight1 >= fl {
  6827. continue
  6828. }
  6829. if tmrtype == "1" {
  6830. _, 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()
  6831. if err != nil {
  6832. logs.Error(err)
  6833. tx.Rollback()
  6834. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6835. return
  6836. }
  6837. } else if tmrtype == "2" {
  6838. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6839. if err != nil {
  6840. logs.Error(err)
  6841. tx.Rollback()
  6842. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6843. return
  6844. }
  6845. }
  6846. if item["fttype"].(int64) == 0 {
  6847. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6848. if err != nil {
  6849. logs.Error(err)
  6850. tx.Rollback()
  6851. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6852. return
  6853. }
  6854. } else {
  6855. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6856. if err != nil {
  6857. logs.Error(err)
  6858. tx.Rollback()
  6859. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6860. return
  6861. }
  6862. }
  6863. }
  6864. } else {
  6865. for _, item := range lpplandtl1List {
  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 if status == 1 {
  6887. 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()
  6888. if err != nil {
  6889. logs.Error(err)
  6890. tx.Rollback()
  6891. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6892. return
  6893. }
  6894. var lweight float64
  6895. for _, item := range lpplandtl1List {
  6896. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6897. lweight += fl
  6898. }
  6899. if lweight > maxstirfeed {
  6900. lweight = lweight - maxstirfeed
  6901. } else {
  6902. lweight = 0
  6903. }
  6904. for _, item := range lpplandtl1List {
  6905. if lweight > 0 {
  6906. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6907. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6908. if fl >= lweight {
  6909. item["lweight"] = fl - lweight
  6910. lweight = 0
  6911. if tmrtype == "1" {
  6912. _, 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()
  6913. if err != nil {
  6914. logs.Error(err)
  6915. tx.Rollback()
  6916. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6917. return
  6918. }
  6919. } else if tmrtype == "2" {
  6920. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6921. if err != nil {
  6922. logs.Error(err)
  6923. tx.Rollback()
  6924. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6925. return
  6926. }
  6927. }
  6928. if item["fttype"].(int64) == 0 {
  6929. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6930. if err != nil {
  6931. logs.Error(err)
  6932. tx.Rollback()
  6933. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6934. return
  6935. }
  6936. } else {
  6937. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6938. if err != nil {
  6939. logs.Error(err)
  6940. tx.Rollback()
  6941. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6942. return
  6943. }
  6944. }
  6945. } else {
  6946. lweight = lweight - fl
  6947. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], 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. if item["fttype"].(int64) == 0 {
  6955. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6956. if err != nil {
  6957. logs.Error(err)
  6958. tx.Rollback()
  6959. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6960. return
  6961. }
  6962. } else {
  6963. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6964. if err != nil {
  6965. logs.Error(err)
  6966. tx.Rollback()
  6967. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6968. return
  6969. }
  6970. }
  6971. }
  6972. } else {
  6973. // 自走式
  6974. if tmrtype == "1" {
  6975. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6976. if err != nil {
  6977. logs.Error(err)
  6978. tx.Rollback()
  6979. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6980. return
  6981. }
  6982. } else if tmrtype == "2" {
  6983. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6984. if err != nil {
  6985. logs.Error(err)
  6986. tx.Rollback()
  6987. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6988. return
  6989. }
  6990. }
  6991. }
  6992. }
  6993. } else {
  6994. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6995. if err != nil {
  6996. logs.Error(err)
  6997. tx.Rollback()
  6998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6999. return
  7000. }
  7001. for _, item := range lpplandtl1List {
  7002. if item["fttype"].(int64) == 0 {
  7003. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7004. if err != nil {
  7005. logs.Error(err)
  7006. tx.Rollback()
  7007. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7008. return
  7009. }
  7010. } else {
  7011. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7012. if err != nil {
  7013. logs.Error(err)
  7014. tx.Rollback()
  7015. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7016. return
  7017. }
  7018. }
  7019. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7020. if err != nil {
  7021. logs.Error(err)
  7022. tx.Rollback()
  7023. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7024. return
  7025. }
  7026. }
  7027. }
  7028. _, 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()
  7029. if err != nil {
  7030. logs.Error(err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7033. return
  7034. }
  7035. } else {
  7036. if status == 2 {
  7037. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7038. if err != nil {
  7039. logs.Error(err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7042. return
  7043. }
  7044. for _, item := range lpplandtl1List {
  7045. if item["fttype"].(int64) == 0 {
  7046. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7047. if err != nil {
  7048. logs.Error(err)
  7049. tx.Rollback()
  7050. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7051. return
  7052. }
  7053. } else {
  7054. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7055. if err != nil {
  7056. logs.Error(err)
  7057. tx.Rollback()
  7058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7059. return
  7060. }
  7061. }
  7062. }
  7063. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7064. if err != nil {
  7065. logs.Error(err)
  7066. tx.Rollback()
  7067. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7068. return
  7069. }
  7070. } else {
  7071. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7072. if err != nil {
  7073. logs.Error(err)
  7074. tx.Rollback()
  7075. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7076. return
  7077. }
  7078. }
  7079. }
  7080. err := tx.Commit()
  7081. if err != nil {
  7082. logs.Error(err)
  7083. tx.Rollback()
  7084. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7085. return
  7086. }
  7087. appG.Response(http.StatusOK, e.SUCCESS, true)
  7088. }
  7089. func Decimal(value float64) float64 {
  7090. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7091. return value
  7092. }
  7093. func UpdateDailyData(c *gin.Context) {
  7094. appG := app.Gin{C: c}
  7095. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7096. parammaps := gofasion.NewFasion(string(dataByte))
  7097. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7098. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7099. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7100. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7101. date := parammaps.Get("date").ValueStr()
  7102. tx := restful.Engine.NewSession()
  7103. defer tx.Close()
  7104. 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()
  7105. if err != nil {
  7106. logs.Error("UpdateDailyData-error-0:", err)
  7107. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7108. return
  7109. }
  7110. if count > 0 {
  7111. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7112. return
  7113. }
  7114. tx.Begin()
  7115. if location == 0 {
  7116. fid := parammaps.Get("fid").ValueStr()
  7117. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7118. if err != nil {
  7119. logs.Error("UpdateDailyData-error-1:", err)
  7120. tx.Rollback()
  7121. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7122. return
  7123. }
  7124. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7125. if err != nil {
  7126. logs.Error("UpdateDailyData-error-1:", err)
  7127. tx.Rollback()
  7128. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7129. return
  7130. }
  7131. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7132. if err != nil {
  7133. fmt.Println("Error:", err)
  7134. return
  7135. }
  7136. actualWeight := weight - num
  7137. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7138. if err != nil {
  7139. logs.Error("UpdateDailyData-error-2:", err)
  7140. tx.Rollback()
  7141. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7142. return
  7143. }
  7144. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7145. if err != nil {
  7146. logs.Error("UpdateDailyData-error-3:", err)
  7147. tx.Rollback()
  7148. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7149. return
  7150. }
  7151. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7152. if err != nil {
  7153. logs.Error("UpdateDailyData-error-4:", err)
  7154. tx.Rollback()
  7155. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7156. return
  7157. }
  7158. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7159. if err != nil {
  7160. logs.Error("UpdateDailyData-error-5:", err)
  7161. tx.Rollback()
  7162. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7163. return
  7164. }
  7165. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7166. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7167. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7168. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7169. if err != nil {
  7170. fmt.Println("Error:", err)
  7171. return
  7172. }
  7173. // actual := actualWeight / float64(len(downloadedplanList))
  7174. for _, item := range downloadedplanList {
  7175. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7176. if err != nil {
  7177. fmt.Println("Error:", err)
  7178. return
  7179. }
  7180. actual := itemLweight / lweight * actualWeight
  7181. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7182. if err != nil {
  7183. logs.Error("UpdateDailyData-error-6:", err)
  7184. tx.Rollback()
  7185. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7186. return
  7187. }
  7188. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7189. if err != nil {
  7190. logs.Error("UpdateDailyData-error-7:", err)
  7191. tx.Rollback()
  7192. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7193. return
  7194. }
  7195. _, 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()
  7196. if err != nil {
  7197. logs.Error("UpdateDailyData-error-8:", err)
  7198. tx.Rollback()
  7199. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7200. return
  7201. }
  7202. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7203. if err != nil {
  7204. logs.Error("UpdateDailyData-error-9:", err)
  7205. tx.Rollback()
  7206. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7207. return
  7208. }
  7209. }
  7210. } else {
  7211. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7212. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7213. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7214. // if err != nil {
  7215. // fmt.Println("Error:", err)
  7216. // return
  7217. // }
  7218. for _, item := range downloadedplanList {
  7219. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7220. if err != nil {
  7221. logs.Error("UpdateDailyData-error-6:", err)
  7222. tx.Rollback()
  7223. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7224. return
  7225. }
  7226. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7227. item["lweight"], actualWeight, item["id"]).Execute()
  7228. if err != nil {
  7229. logs.Error("UpdateDailyData-error-7:", err)
  7230. tx.Rollback()
  7231. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7232. return
  7233. }
  7234. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7235. where pid = ?`, item["id"]).Execute()
  7236. if err != nil {
  7237. logs.Error("UpdateDailyData-error-8:", err)
  7238. tx.Rollback()
  7239. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7240. return
  7241. }
  7242. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7243. if err != nil {
  7244. logs.Error("UpdateDailyData-error-9:", err)
  7245. tx.Rollback()
  7246. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7247. return
  7248. }
  7249. }
  7250. }
  7251. } else {
  7252. fbarid := parammaps.Get("fbarid").ValueStr()
  7253. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7254. if err != nil {
  7255. logs.Error("UpdateDailyData-error-10:", err)
  7256. tx.Rollback()
  7257. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7258. return
  7259. }
  7260. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7261. if err != nil {
  7262. logs.Error("UpdateDailyData-error-1:", err)
  7263. tx.Rollback()
  7264. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7265. return
  7266. }
  7267. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7268. if err != nil {
  7269. fmt.Println("Error:", err)
  7270. return
  7271. }
  7272. actualWeight := weight - num
  7273. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7274. if err != nil {
  7275. logs.Error("UpdateDailyData-error-11:", err)
  7276. tx.Rollback()
  7277. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7278. return
  7279. }
  7280. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7281. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7282. if err != nil {
  7283. logs.Error("UpdateDailyData-error-12:", err)
  7284. tx.Rollback()
  7285. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7286. return
  7287. }
  7288. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7289. where pid = ? `, pid).Execute()
  7290. if err != nil {
  7291. logs.Error("UpdateDailyData-error-13:", err)
  7292. tx.Rollback()
  7293. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7294. return
  7295. }
  7296. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7297. if err != nil {
  7298. logs.Error("UpdateDailyData-error-14:", err)
  7299. tx.Rollback()
  7300. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7301. return
  7302. }
  7303. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7304. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7305. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7306. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7307. if err != nil {
  7308. fmt.Println("Error:", err)
  7309. return
  7310. }
  7311. for _, item := range downloadedplanList {
  7312. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7313. if err != nil {
  7314. fmt.Println("Error:", err)
  7315. return
  7316. }
  7317. actual := itemLweight / lweight * actualWeight
  7318. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7319. if err != nil {
  7320. logs.Error("UpdateDailyData-error-6:", err)
  7321. tx.Rollback()
  7322. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7323. return
  7324. }
  7325. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7326. if err != nil {
  7327. logs.Error("UpdateDailyData-error-7:", err)
  7328. tx.Rollback()
  7329. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7330. return
  7331. }
  7332. _, 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()
  7333. if err != nil {
  7334. logs.Error("UpdateDailyData-error-8:", err)
  7335. tx.Rollback()
  7336. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7337. return
  7338. }
  7339. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7340. if err != nil {
  7341. logs.Error("UpdateDailyData-error-9:", err)
  7342. tx.Rollback()
  7343. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7344. return
  7345. }
  7346. }
  7347. } else {
  7348. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7349. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7350. for _, item := range downloadedplanList {
  7351. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7352. // if err != nil {
  7353. // fmt.Println("Error:", err)
  7354. // return
  7355. // }
  7356. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7357. if err != nil {
  7358. logs.Error("UpdateDailyData-error-6:", err)
  7359. tx.Rollback()
  7360. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7361. return
  7362. }
  7363. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7364. item["lweight"], actualWeight, item["id"]).Execute()
  7365. if err != nil {
  7366. logs.Error("UpdateDailyData-error-7:", err)
  7367. tx.Rollback()
  7368. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7369. return
  7370. }
  7371. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7372. where pid = ?`, item["id"]).Execute()
  7373. if err != nil {
  7374. logs.Error("UpdateDailyData-error-8:", err)
  7375. tx.Rollback()
  7376. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7377. return
  7378. }
  7379. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7380. if err != nil {
  7381. logs.Error("UpdateDailyData-error-9:", err)
  7382. tx.Rollback()
  7383. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7384. return
  7385. }
  7386. }
  7387. }
  7388. }
  7389. err = tx.Commit()
  7390. if err != nil {
  7391. logs.Error("UpdateDailyData-error-20:", err)
  7392. tx.Rollback()
  7393. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7394. return
  7395. }
  7396. appG.Response(http.StatusOK, e.SUCCESS, true)
  7397. }
  7398. func GetFormulaStatistics(c *gin.Context) {
  7399. appG := app.Gin{C: c}
  7400. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7401. parammaps := gofasion.NewFasion(string(dataByte))
  7402. startTime := parammaps.Get("startTime").ValueStr()
  7403. endTime := parammaps.Get("endTime").ValueStr()
  7404. pastureId := parammaps.Get("pastureId").ValueStr()
  7405. tx := restful.Engine.NewSession()
  7406. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7407. if err != nil {
  7408. logs.Error("GetFormulaStatistics-error-1:", err)
  7409. tx.Rollback()
  7410. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7411. return
  7412. }
  7413. var feedtemplet, dateList []string
  7414. for _, f := range feedtempletList {
  7415. feedtemplet = append(feedtemplet, f["tname"].(string))
  7416. }
  7417. layout := "2006-01-02"
  7418. // s := "2023-05-01"
  7419. // e := "2023-05-23"
  7420. start, err := time.Parse(layout, startTime)
  7421. if err != nil {
  7422. fmt.Println(err)
  7423. return
  7424. }
  7425. end, err := time.Parse(layout, endTime)
  7426. if err != nil {
  7427. fmt.Println(err)
  7428. return
  7429. }
  7430. end = end.AddDate(0, 0, 1)
  7431. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7432. dateList = append(dateList, d.Format("2006-01-02"))
  7433. }
  7434. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7435. 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= ?
  7436. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7437. if err != nil {
  7438. logs.Error("GetFormulaStatistics-error-2:", err)
  7439. tx.Rollback()
  7440. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7441. return
  7442. }
  7443. var data2 [][]interface{}
  7444. for _, f := range feedtemplet {
  7445. var data1 []interface{}
  7446. for _, date := range dateList {
  7447. exist := false
  7448. for _, item := range downloadedplanList {
  7449. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7450. data1 = append(data1, item["total"])
  7451. exist = true
  7452. break
  7453. }
  7454. }
  7455. if !exist {
  7456. data1 = append(data1, 0)
  7457. }
  7458. }
  7459. data2 = append(data2, data1)
  7460. }
  7461. //前端让加的
  7462. feedtemplet = append(feedtemplet, "")
  7463. {
  7464. var data1 []interface{}
  7465. for _, f := range dateList {
  7466. // f = f + "\n"
  7467. fmt.Println(f)
  7468. data1 = append(data1, 0)
  7469. }
  7470. data2 = append(data2, data1)
  7471. }
  7472. resp := make(map[string]interface{}, 0)
  7473. resp["xdata"] = dateList
  7474. resp["data1"] = feedtemplet
  7475. resp["data2"] = data2
  7476. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7477. }
  7478. func GetPlanData(c *gin.Context) {
  7479. appG := app.Gin{C: c}
  7480. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7481. fsion := gofasion.NewFasion(string(dataByte))
  7482. sqlnamestr := fsion.Get("name").ValueStr()
  7483. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7484. offset := fsion.Get("offset").ValueDefaultInt(0)
  7485. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7486. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7487. month := fsion.Get("month").ValueDefaultStr("map")
  7488. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7489. tx := restful.Engine.NewSession()
  7490. err := tx.Begin()
  7491. defer func() {
  7492. switch {
  7493. case err != nil:
  7494. if tx != nil {
  7495. tx.Rollback()
  7496. }
  7497. default:
  7498. if tx != nil {
  7499. err = tx.Commit()
  7500. }
  7501. }
  7502. if tx != nil {
  7503. tx.Close()
  7504. }
  7505. }()
  7506. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7507. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7508. if sql != "" {
  7509. s_params := make([]interface{}, 0)
  7510. if fsion.HasKey("parammaps") {
  7511. parammaps := fsion.Get("parammaps")
  7512. paramslist := strings.Split(p, ",")
  7513. if len(paramslist) > 0 && p != "" {
  7514. for _, value := range paramslist {
  7515. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7516. if tempv, exists := c.Get("jwt_username"); exists {
  7517. s_params = append(s_params, tempv.(string))
  7518. } else {
  7519. s_params = append(s_params, "")
  7520. }
  7521. } else {
  7522. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7523. }
  7524. }
  7525. }
  7526. }
  7527. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7528. if err != nil {
  7529. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7530. } else {
  7531. paramslist1 := strings.Split(p1, ",")
  7532. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7533. s_params1 := make([]interface{}, 0)
  7534. if len(paramslist1) > 0 && p1 != "" {
  7535. for _, v := range paramslist1 {
  7536. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7537. }
  7538. }
  7539. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7540. for _, item := range arr {
  7541. trgaddressList := []string{}
  7542. if _, ok := item["trgaddress"]; ok {
  7543. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7544. for _, str := range trgaddressList1 {
  7545. if str != "" {
  7546. trgaddressList = append(trgaddressList, str)
  7547. }
  7548. }
  7549. }
  7550. item["trgaddressList"] = trgaddressList
  7551. }
  7552. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7553. }
  7554. // var wg sync.WaitGroup
  7555. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7556. // wg.Add(1)
  7557. // go func(value map[string]interface{}) {
  7558. // defer wg.Done()
  7559. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7560. // }(value)
  7561. // }
  7562. // wg.Wait()
  7563. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7564. }
  7565. } else {
  7566. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7567. }
  7568. }
  7569. func PostPlanData(c *gin.Context) {
  7570. appG := app.Gin{C: c}
  7571. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7572. fsion := gofasion.NewFasion(string(dataByte))
  7573. logging.Info("PostRJSBData err: ", string(dataByte))
  7574. s_params := make([]interface{}, 0)
  7575. tx := restful.Engine.NewSession()
  7576. err := tx.Begin()
  7577. defer func() {
  7578. switch {
  7579. case err != nil:
  7580. if tx != nil {
  7581. tx.Rollback()
  7582. }
  7583. default:
  7584. if tx != nil {
  7585. err = tx.Commit()
  7586. }
  7587. }
  7588. if tx != nil {
  7589. tx.Close()
  7590. }
  7591. }()
  7592. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7593. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7594. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7595. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7596. if !fsion.HasKey("parammaps") {
  7597. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7598. return
  7599. }
  7600. parammaps := fsion.Get("parammaps")
  7601. // paramslist := strings.Split(p, ",")
  7602. // if len(paramslist) > 0 && p != "" {
  7603. // for _, value := range paramslist {
  7604. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7605. // }
  7606. // }
  7607. // _, err = tx.SQL(sql, s_params...).Execute()
  7608. // if err != nil {
  7609. // logging.Error("PostRJSBData err: ", err)
  7610. // msg := geterrmsg(err.Error())
  7611. // appG.Response(http.StatusOK, e.ERROR, msg)
  7612. // return
  7613. // }
  7614. s_params = make([]interface{}, 0)
  7615. paramslist := strings.Split(p1, ",")
  7616. if len(paramslist) > 0 && p1 != "" {
  7617. for _, value := range paramslist {
  7618. // if value == "ID" {
  7619. // id := parammaps.Get("ID").ValueStr()
  7620. // pastureid := parammaps.Get("pastureid").ValueStr()
  7621. // 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
  7622. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7623. // if err != nil {
  7624. // logging.Error("PostRJSBData err: ", err)
  7625. // msg := geterrmsg(err.Error())
  7626. // appG.Response(http.StatusOK, e.ERROR, msg)
  7627. // return
  7628. // }
  7629. // for _, item := range datalist {
  7630. // id = item["id"]
  7631. // }
  7632. // s_params = append(s_params, id)
  7633. // } else {
  7634. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7635. // }
  7636. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7637. }
  7638. }
  7639. _, err = tx.SQL(sql1, s_params...).Execute()
  7640. if err != nil {
  7641. logging.Error("PostRJSBData1 err: ", err)
  7642. msg := geterrmsg(err.Error())
  7643. appG.Response(http.StatusOK, e.ERROR, msg)
  7644. return
  7645. }
  7646. s_params = make([]interface{}, 0)
  7647. paramslist = strings.Split(p2, ",")
  7648. if len(paramslist) > 0 && p2 != "" {
  7649. for _, value := range paramslist {
  7650. if value == "ID" {
  7651. id := parammaps.Get("ID").ValueStr()
  7652. pastureid := parammaps.Get("pastureid").ValueStr()
  7653. 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
  7654. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7655. if err != nil {
  7656. logging.Error("PostRJSBData err: ", err)
  7657. msg := geterrmsg(err.Error())
  7658. appG.Response(http.StatusOK, e.ERROR, msg)
  7659. return
  7660. }
  7661. for _, item := range datalist {
  7662. id = item["id"]
  7663. }
  7664. s_params = append(s_params, id)
  7665. } else {
  7666. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7667. }
  7668. }
  7669. }
  7670. _, err = tx.SQL(sql2, s_params...).Execute()
  7671. if err != nil {
  7672. logging.Error("PostRJSBData2 err: ", err)
  7673. msg := geterrmsg(err.Error())
  7674. appG.Response(http.StatusOK, e.ERROR, msg)
  7675. return
  7676. }
  7677. s_params = make([]interface{}, 0)
  7678. paramslist = strings.Split(p3, ",")
  7679. if len(paramslist) > 0 && p3 != "" {
  7680. for _, value := range paramslist {
  7681. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7682. }
  7683. }
  7684. _, err = tx.SQL(sql3, s_params...).Execute()
  7685. if err != nil {
  7686. logging.Error("PostRJSBData3 err: ", err)
  7687. msg := geterrmsg(err.Error())
  7688. appG.Response(http.StatusOK, e.ERROR, msg)
  7689. return
  7690. }
  7691. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7692. }
  7693. func CheckFeedTrgaddress(c *gin.Context) {
  7694. appG := app.Gin{C: c}
  7695. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7696. fsion := gofasion.NewFasion(string(dataByte))
  7697. fclassid := fsion.Get("fclassid").ValueStr()
  7698. feedId := fsion.Get("feedId").ValueStr()
  7699. backup1 := fsion.Get("backup1").ValueStr()
  7700. backup1List := strings.Split(backup1, ",")
  7701. tx := restful.Engine.NewSession()
  7702. defer tx.Close()
  7703. // if backup1 != "" {
  7704. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7705. for _, feed := range feedList {
  7706. if feed["backup1"] == "" {
  7707. continue
  7708. }
  7709. feedbackupList := strings.Split(feed["backup1"], ",")
  7710. for _, feedbackup := range feedbackupList {
  7711. for _, backup := range backup1List {
  7712. if feedbackup == backup {
  7713. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7714. return
  7715. }
  7716. }
  7717. }
  7718. }
  7719. // }
  7720. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7721. }
  7722. func ThiGetDataByName(c *gin.Context) {
  7723. appG := app.Gin{C: c}
  7724. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7725. fsion := gofasion.NewFasion(string(dataByte))
  7726. sqlnamestr := fsion.Get("name").ValueStr()
  7727. offset := fsion.Get("offset").ValueDefaultInt(0)
  7728. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7729. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7730. tx := restful.Engine.NewSession()
  7731. err := tx.Begin()
  7732. defer func() {
  7733. switch {
  7734. case err != nil:
  7735. logging.Error("tx.Begin 事务启动失败__error:", err)
  7736. if tx != nil {
  7737. tx.Rollback()
  7738. }
  7739. default:
  7740. if tx != nil {
  7741. err = tx.Commit()
  7742. }
  7743. }
  7744. if tx != nil {
  7745. tx.Close()
  7746. }
  7747. }()
  7748. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7749. if sql != "" {
  7750. s_params := make([]interface{}, 0)
  7751. if fsion.HasKey("parammaps") {
  7752. parammaps := fsion.Get("parammaps")
  7753. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7754. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7755. }
  7756. paramslist := strings.Split(p, ",")
  7757. if len(paramslist) > 0 && p != "" {
  7758. for _, value := range paramslist {
  7759. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7760. if tempv, exists := c.Get("jwt_username"); exists {
  7761. s_params = append(s_params, tempv.(string))
  7762. } else {
  7763. s_params = append(s_params, "")
  7764. }
  7765. } else {
  7766. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7767. }
  7768. }
  7769. }
  7770. } else if fsion.HasKey("params") {
  7771. params := fsion.Get("params").Array()
  7772. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7773. for _, v_params := range params {
  7774. s_params = append(s_params, v_params.ValueStr())
  7775. }
  7776. }
  7777. if returntype == "xlsx" {
  7778. var xlsxfile *xlsx.File
  7779. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7780. //c.File("c:/dd.xlsx")
  7781. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7782. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7783. c.Header("Content-Transfer-Encoding", "binary")
  7784. _ = xlsxfile.Write(c.Writer)
  7785. } else {
  7786. if sqlnamestr == "getHomepageStr" {
  7787. parammaps := fsion.Get("parammaps")
  7788. pastureid := parammaps.Get("pastureid").ValueStr()
  7789. var montimeList []float64
  7790. var montime float64
  7791. var wg sync.WaitGroup
  7792. now := time.Now()
  7793. for i := 0; i < 30; i++ {
  7794. wg.Add(1)
  7795. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7796. go func(nowstr string) {
  7797. defer wg.Done()
  7798. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7799. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7800. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7801. montimeList = append(montimeList, m)
  7802. }(nowstr)
  7803. }
  7804. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7805. if err != nil {
  7806. logging.Error("GetDataByName err: ", err)
  7807. msg := geterrmsg(err.Error())
  7808. appG.Response(http.StatusOK, e.ERROR, msg)
  7809. }
  7810. wg.Wait()
  7811. for _, m := range montimeList {
  7812. montime += m
  7813. }
  7814. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7815. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7816. return
  7817. }
  7818. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7819. if err != nil {
  7820. logging.Error("GetDataByName err: ", err)
  7821. msg := geterrmsg(err.Error())
  7822. appG.Response(http.StatusOK, e.ERROR, msg)
  7823. } else {
  7824. if sqlnamestr == "getFeedTrgaddressList" {
  7825. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7826. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7827. trgaddressList := []string{}
  7828. for _, str := range trgaddressList1 {
  7829. if str != "" {
  7830. trgaddressList = append(trgaddressList, str)
  7831. }
  7832. }
  7833. item["trgaddressList"] = trgaddressList
  7834. }
  7835. }
  7836. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7837. }
  7838. }
  7839. } else {
  7840. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7841. }
  7842. }
  7843. // func ToggleCcount(c *gin.Context) {
  7844. // appG := app.Gin{C: c}
  7845. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7846. // fsion := gofasion.NewFasion(string(dataByte))
  7847. // // 0 实际 1 软件
  7848. // status := fsion.Get("status").ValueDefaultInt64(0)
  7849. // pastureId := fsion.Get("pastureId").ValueStr()
  7850. // tx := restful.Engine.NewSession()
  7851. // err := tx.Begin()
  7852. // defer func() {
  7853. // switch {
  7854. // case err != nil:
  7855. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7856. // if tx != nil {
  7857. // tx.Rollback()
  7858. // }
  7859. // default:
  7860. // if tx != nil {
  7861. // err = tx.Commit()
  7862. // }
  7863. // }
  7864. // if tx != nil {
  7865. // tx.Close()
  7866. // }
  7867. // }()
  7868. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7869. // if err != nil {
  7870. // logs.Error(err)
  7871. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7872. // return
  7873. // }
  7874. // for _, bar := range barList {
  7875. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7876. // if err != nil {
  7877. // logs.Error(err)
  7878. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7879. // return
  7880. // }
  7881. // if !exist {
  7882. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7883. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7884. // if err != nil {
  7885. // logs.Error(err)
  7886. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7887. // return
  7888. // }
  7889. // }
  7890. // }
  7891. // if status == 0 {
  7892. // tx.Exec(`update feedp set ccount = actualcount `)
  7893. // }else{
  7894. // tx.Exec(`update feedp set ccount = softccount `)
  7895. // }
  7896. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7897. // if err != nil {
  7898. // logs.Error(err)
  7899. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7900. // return
  7901. // }
  7902. // for _, feedpData :=range feedpList{
  7903. // var feedpargs []interface{}
  7904. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7905. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7906. // if _, ok := feedpData["ftname"]; ok {
  7907. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7908. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7909. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7910. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7911. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7912. // } else {
  7913. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7914. // }
  7915. // if _, ok := feedpData["ptsfname"]; ok {
  7916. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7917. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7918. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7919. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7920. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7921. // } else {
  7922. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7923. // }
  7924. // upFeedpSql += " where barname = ? and pastureid = ? "
  7925. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7926. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7927. // if err != nil {
  7928. // logs.Error(err)
  7929. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7930. // return
  7931. // }
  7932. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7933. // if err != nil {
  7934. // logs.Error(err)
  7935. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7936. // return
  7937. // }
  7938. // if !exist1 {
  7939. // _, 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) `,
  7940. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7941. // if err != nil {
  7942. // logs.Error(err)
  7943. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7944. // return
  7945. // }
  7946. // }
  7947. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7948. // if err != nil {
  7949. // logs.Error(err)
  7950. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7951. // return
  7952. // }
  7953. // if !exist2 {
  7954. // _, 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) `,
  7955. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7956. // if err != nil {
  7957. // logs.Error(err)
  7958. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7959. // return
  7960. // }
  7961. // }
  7962. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7963. // if err != nil {
  7964. // logs.Error(err)
  7965. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7966. // return
  7967. // }
  7968. // if !exist3 {
  7969. // _, 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) `,
  7970. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7971. // if err != nil {
  7972. // logs.Error(err)
  7973. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7974. // return
  7975. // }
  7976. // }
  7977. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7978. // if err != nil {
  7979. // logs.Error(err)
  7980. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7981. // return
  7982. // }
  7983. // if !exist4 {
  7984. // _, 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) `,
  7985. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7986. // if err != nil {
  7987. // logs.Error(err)
  7988. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7989. // return
  7990. // }
  7991. // }
  7992. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7993. // if err != nil {
  7994. // logs.Error(err)
  7995. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7996. // return
  7997. // }
  7998. // if !exist5 {
  7999. // _, 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) `,
  8000. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8001. // if err != nil {
  8002. // logs.Error(err)
  8003. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8004. // return
  8005. // }
  8006. // }
  8007. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  8008. // if err != nil {
  8009. // logs.Error(err)
  8010. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8011. // return
  8012. // }
  8013. // if !exist6 {
  8014. // _, 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) `,
  8015. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8016. // if err != nil {
  8017. // logs.Error(err)
  8018. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8019. // return
  8020. // }
  8021. // }
  8022. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8023. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8024. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8025. // and pastureid = ? and times = ?`
  8026. // var fpdargs1 []interface{}
  8027. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8028. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8029. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8030. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8031. // if err != nil {
  8032. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8033. // return
  8034. // }
  8035. // var fpdargs2 []interface{}
  8036. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8037. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8038. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8039. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8040. // if err != nil {
  8041. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8042. // return
  8043. // }
  8044. // var fpdargs3 []interface{}
  8045. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8046. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8047. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8048. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8049. // if err != nil {
  8050. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8051. // return
  8052. // }
  8053. // var fpdargs4 []interface{}
  8054. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8055. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8056. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8057. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8058. // if err != nil {
  8059. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8060. // return
  8061. // }
  8062. // var fpdargs5 []interface{}
  8063. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8064. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8065. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8066. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8067. // if err != nil {
  8068. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8069. // return
  8070. // }
  8071. // var fpdargs6 []interface{}
  8072. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8073. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8074. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8075. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8076. // if err != nil {
  8077. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8078. // return
  8079. // }
  8080. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8081. // 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()
  8082. // if err != nil {
  8083. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8084. // return
  8085. // }
  8086. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8087. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8088. // upFpdetailList := make([]*upFpdetail, 0)
  8089. // for _, newfpd := range newList {
  8090. // for _, oldfpd := range oldFpdList {
  8091. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8092. // var oldweight, newweight float64
  8093. // if oldfpd["weight"] != nil {
  8094. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8095. // }
  8096. // if newfpd["weight"] != nil {
  8097. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8098. // }
  8099. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8100. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8101. // Old: oldweight,
  8102. // New: newweight,
  8103. // Times: newfpd["times"].(int64),
  8104. // Ptid: newfpd["ptid"].(int64),
  8105. // Fweight: fweight,
  8106. // Id: oldfpd["id"].(int64),
  8107. // })
  8108. // break
  8109. // }
  8110. // }
  8111. // }
  8112. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8113. // }
  8114. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8115. // }
  8116. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8117. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8118. if err != nil {
  8119. return err
  8120. }
  8121. for _, item := range feedpList {
  8122. // if item["ftid"].(string) != data["ftid"].(string) {
  8123. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8124. if err != nil {
  8125. return err
  8126. }
  8127. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8128. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8129. if err != nil {
  8130. return err
  8131. }
  8132. // }
  8133. }
  8134. return nil
  8135. }
  8136. func PostPlanDatas(c *gin.Context) {
  8137. appG := app.Gin{C: c}
  8138. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8139. fsions := gofasion.NewFasion(string(dataByte))
  8140. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8141. tx := restful.Engine.NewSession()
  8142. err := tx.Begin()
  8143. defer func() {
  8144. switch {
  8145. case err != nil:
  8146. if tx != nil {
  8147. tx.Rollback()
  8148. }
  8149. default:
  8150. if tx != nil {
  8151. err = tx.Commit()
  8152. }
  8153. }
  8154. if tx != nil {
  8155. tx.Close()
  8156. }
  8157. }()
  8158. pastureId := fsions.Get("pastureid").ValueStr()
  8159. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8160. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8161. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8162. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8163. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8164. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8165. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8166. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8167. for _, parammaps := range fsions.Get("arrList").Array() {
  8168. fmt.Println(parammaps.Json())
  8169. if parammaps.Json() == "null" {
  8170. continue
  8171. }
  8172. // if !fsion.HasKey("arrList") {
  8173. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8174. // return
  8175. // continue
  8176. // }
  8177. // parammaps := fsion.Get("arrList")
  8178. s_params := make([]interface{}, 0)
  8179. // paramslist := strings.Split(p, ",")
  8180. // if len(paramslist) > 0 && p != "" {
  8181. // for _, value := range paramslist {
  8182. // if value == "pastureid" {
  8183. // s_params = append(s_params, pastureId)
  8184. // } else {
  8185. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8186. // }
  8187. // }
  8188. // }
  8189. // _, err = tx.SQL(sql, s_params...).Execute()
  8190. // if err != nil {
  8191. // logging.Error("PostRJSBData err: ", err)
  8192. // msg := geterrmsg(err.Error())
  8193. // appG.Response(http.StatusOK, e.ERROR, msg)
  8194. // return
  8195. // }
  8196. s_params = make([]interface{}, 0)
  8197. paramslist := strings.Split(p1, ",")
  8198. if len(paramslist) > 0 && p1 != "" {
  8199. for _, value := range paramslist {
  8200. // if value == "ID" {
  8201. // id := parammaps.Get("ID").ValueStr()
  8202. // pastureid := parammaps.Get("pastureid").ValueStr()
  8203. // 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
  8204. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8205. // if err != nil {
  8206. // logging.Error("PostRJSBData err: ", err)
  8207. // msg := geterrmsg(err.Error())
  8208. // appG.Response(http.StatusOK, e.ERROR, msg)
  8209. // return
  8210. // }
  8211. // for _, item := range datalist {
  8212. // id = item["id"]
  8213. // }
  8214. // s_params = append(s_params, id)
  8215. // } else {
  8216. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8217. // }
  8218. if value == "pastureid" {
  8219. s_params = append(s_params, pastureId)
  8220. } else {
  8221. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8222. }
  8223. }
  8224. }
  8225. _, err = tx.SQL(sql1, s_params...).Execute()
  8226. if err != nil {
  8227. logging.Error("PostRJSBData1 err: ", err)
  8228. msg := geterrmsg(err.Error())
  8229. appG.Response(http.StatusOK, e.ERROR, msg)
  8230. return
  8231. }
  8232. s_params = make([]interface{}, 0)
  8233. paramslist = strings.Split(p2, ",")
  8234. if len(paramslist) > 0 && p2 != "" {
  8235. for _, value := range paramslist {
  8236. if value == "ID" {
  8237. id := parammaps.Get("ID").ValueStr()
  8238. pastureid := parammaps.Get("pastureid").ValueStr()
  8239. 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
  8240. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8241. if err != nil {
  8242. logging.Error("PostRJSBData err: ", err)
  8243. msg := geterrmsg(err.Error())
  8244. appG.Response(http.StatusOK, e.ERROR, msg)
  8245. return
  8246. }
  8247. for _, item := range datalist {
  8248. id = item["id"]
  8249. }
  8250. s_params = append(s_params, id)
  8251. } else if value == "pastureid" {
  8252. s_params = append(s_params, pastureId)
  8253. } else {
  8254. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8255. }
  8256. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8257. }
  8258. }
  8259. _, err = tx.SQL(sql2, s_params...).Execute()
  8260. if err != nil {
  8261. logging.Error("PostRJSBData2 err: ", err)
  8262. msg := geterrmsg(err.Error())
  8263. appG.Response(http.StatusOK, e.ERROR, msg)
  8264. return
  8265. }
  8266. s_params = make([]interface{}, 0)
  8267. paramslist = strings.Split(p3, ",")
  8268. if len(paramslist) > 0 && p3 != "" {
  8269. for _, value := range paramslist {
  8270. if value == "pastureid" {
  8271. s_params = append(s_params, pastureId)
  8272. } else {
  8273. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8274. }
  8275. }
  8276. }
  8277. _, err = tx.SQL(sql3, s_params...).Execute()
  8278. if err != nil {
  8279. logging.Error("PostRJSBData3 err: ", err)
  8280. msg := geterrmsg(err.Error())
  8281. appG.Response(http.StatusOK, e.ERROR, msg)
  8282. return
  8283. }
  8284. }
  8285. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8286. }
  8287. func FpdBatchEdit(c *gin.Context) {
  8288. appG := app.Gin{C: c}
  8289. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8290. fsions := gofasion.NewFasion(string(dataByte))
  8291. barList := fsions.Get("barList").Array()
  8292. pastureid := fsions.Get("pastureId").ValueStr()
  8293. tx := restful.Engine.NewSession()
  8294. defer tx.Close()
  8295. 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
  8296. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8297. if err != nil {
  8298. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8299. return
  8300. }
  8301. for _, barFsions := range barList {
  8302. dataexcel := make(map[string]interface{}, 0)
  8303. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8304. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8305. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8306. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8307. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8308. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8309. continue
  8310. }
  8311. /*
  8312. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8313. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8314. if err != nil {
  8315. logs.Error(err)
  8316. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8317. return
  8318. }
  8319. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8320. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8321. if err != nil {
  8322. logs.Error(err)
  8323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8324. return
  8325. }
  8326. */
  8327. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8328. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8329. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8330. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8331. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8332. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8333. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8334. if err != nil {
  8335. logs.Error(err)
  8336. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8337. return
  8338. }
  8339. if !ftexist {
  8340. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8341. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8342. if err != nil {
  8343. logs.Error(err)
  8344. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8345. return
  8346. }
  8347. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8348. if err != nil {
  8349. logs.Error(err)
  8350. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8351. return
  8352. }
  8353. }
  8354. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8355. if err != nil {
  8356. logs.Error(err)
  8357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8358. return
  8359. }
  8360. if !exist {
  8361. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8362. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8363. if err != nil {
  8364. logs.Error(err)
  8365. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8366. return
  8367. }
  8368. }
  8369. var feedpargs []interface{}
  8370. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8371. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8372. if _, ok := dataexcel["ftname"]; ok {
  8373. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8374. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8375. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8376. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8377. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8378. } else {
  8379. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8380. }
  8381. if _, ok := dataexcel["ptsfname"]; ok {
  8382. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8383. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8384. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8385. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8386. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8387. } else {
  8388. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8389. }
  8390. upFeedpSql += " where barname = ? and pastureid = ? "
  8391. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8392. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8393. if err != nil {
  8394. logs.Error(err)
  8395. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8396. return
  8397. }
  8398. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8399. if err != nil {
  8400. logs.Error(err)
  8401. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8402. return
  8403. }
  8404. if !exist1 {
  8405. _, 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) `,
  8406. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8407. if err != nil {
  8408. logs.Error(err)
  8409. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8410. return
  8411. }
  8412. }
  8413. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8414. if err != nil {
  8415. logs.Error(err)
  8416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8417. return
  8418. }
  8419. if !exist2 {
  8420. _, 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) `,
  8421. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8422. if err != nil {
  8423. logs.Error(err)
  8424. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8425. return
  8426. }
  8427. }
  8428. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8429. if err != nil {
  8430. logs.Error(err)
  8431. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8432. return
  8433. }
  8434. if !exist3 {
  8435. _, 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) `,
  8436. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8437. if err != nil {
  8438. logs.Error(err)
  8439. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8440. return
  8441. }
  8442. }
  8443. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8444. if err != nil {
  8445. logs.Error(err)
  8446. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8447. return
  8448. }
  8449. if !exist4 {
  8450. _, 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) `,
  8451. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8452. if err != nil {
  8453. logs.Error(err)
  8454. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8455. return
  8456. }
  8457. }
  8458. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8459. if err != nil {
  8460. logs.Error(err)
  8461. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8462. return
  8463. }
  8464. if !exist5 {
  8465. _, 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) `,
  8466. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8467. if err != nil {
  8468. logs.Error(err)
  8469. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8470. return
  8471. }
  8472. }
  8473. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8474. if err != nil {
  8475. logs.Error(err)
  8476. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8477. return
  8478. }
  8479. if !exist6 {
  8480. _, 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) `,
  8481. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8482. if err != nil {
  8483. logs.Error(err)
  8484. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8485. return
  8486. }
  8487. }
  8488. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8489. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8490. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8491. and pastureid = ? and times = ?`
  8492. var fpdargs1 []interface{}
  8493. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8494. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8495. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8496. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8497. if err != nil {
  8498. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8499. return
  8500. }
  8501. var fpdargs2 []interface{}
  8502. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8503. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8504. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8505. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8506. if err != nil {
  8507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8508. return
  8509. }
  8510. var fpdargs3 []interface{}
  8511. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8512. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8513. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8514. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8515. if err != nil {
  8516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8517. return
  8518. }
  8519. var fpdargs4 []interface{}
  8520. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8521. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8522. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8523. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8524. if err != nil {
  8525. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8526. return
  8527. }
  8528. var fpdargs5 []interface{}
  8529. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8530. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8531. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8532. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8533. if err != nil {
  8534. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8535. return
  8536. }
  8537. var fpdargs6 []interface{}
  8538. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8539. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8540. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8541. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8542. if err != nil {
  8543. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8544. return
  8545. }
  8546. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8547. 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()
  8548. if err != nil {
  8549. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8550. return
  8551. }
  8552. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8553. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8554. upFpdetailList := make([]*upFpdetail, 0)
  8555. for _, newfpd := range newList {
  8556. for _, oldfpd := range oldFpdList {
  8557. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8558. var oldweight, newweight float64
  8559. if oldfpd["weight"] != nil {
  8560. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8561. }
  8562. if newfpd["weight"] != nil {
  8563. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8564. }
  8565. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8566. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8567. Old: oldweight,
  8568. New: newweight,
  8569. Times: newfpd["times"].(int64),
  8570. Ptid: newfpd["ptid"].(int64),
  8571. Fweight: fweight,
  8572. Id: oldfpd["id"].(int64),
  8573. })
  8574. break
  8575. }
  8576. }
  8577. }
  8578. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8579. }
  8580. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8581. }
  8582. func UdBarSync(c *gin.Context) {
  8583. appG := app.Gin{C: c}
  8584. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8585. fsions := gofasion.NewFasion(string(dataByte))
  8586. pastureid := fsions.Get("pastureId").ValueStr()
  8587. tx := restful.Engine.NewSession()
  8588. defer tx.Close()
  8589. pastureinfo := new(udPastureInfo)
  8590. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8591. if err != nil {
  8592. logs.Error(err)
  8593. return
  8594. }
  8595. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8596. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8597. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8598. }
  8599. func UdFeedSync(c *gin.Context) {
  8600. appG := app.Gin{C: c}
  8601. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8602. fsions := gofasion.NewFasion(string(dataByte))
  8603. pastureid := fsions.Get("pastureId").ValueStr()
  8604. tx := restful.Engine.NewSession()
  8605. defer tx.Close()
  8606. pastureinfo := new(udPastureInfo)
  8607. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8608. if err != nil {
  8609. logs.Error(err)
  8610. return
  8611. }
  8612. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8613. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8614. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8615. }
  8616. func UdFeedtempletPush(c *gin.Context) {
  8617. appG := app.Gin{C: c}
  8618. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8619. fsions := gofasion.NewFasion(string(dataByte))
  8620. pastureid := fsions.Get("pastureId").ValueStr()
  8621. date := fsions.Get("date").ValueStr()
  8622. tx := restful.Engine.NewSession()
  8623. defer tx.Close()
  8624. pastureinfo := new(udPastureInfo)
  8625. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8626. if err != nil {
  8627. logs.Error(err)
  8628. return
  8629. }
  8630. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8631. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8632. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8633. }
  8634. func UdUtirPush(c *gin.Context) {
  8635. appG := app.Gin{C: c}
  8636. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8637. fsions := gofasion.NewFasion(string(dataByte))
  8638. pastureid := fsions.Get("pastureId").ValueStr()
  8639. date := fsions.Get("date").ValueStr()
  8640. tx := restful.Engine.NewSession()
  8641. defer tx.Close()
  8642. pastureinfo := new(udPastureInfo)
  8643. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8644. if err != nil {
  8645. logs.Error(err)
  8646. return
  8647. }
  8648. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8649. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8650. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8651. }
  8652. func UdBarFeedRemainPush(c *gin.Context) {
  8653. appG := app.Gin{C: c}
  8654. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8655. fsions := gofasion.NewFasion(string(dataByte))
  8656. pastureid := fsions.Get("pastureId").ValueStr()
  8657. date := fsions.Get("date").ValueStr()
  8658. tx := restful.Engine.NewSession()
  8659. defer tx.Close()
  8660. pastureinfo := new(udPastureInfo)
  8661. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8662. if err != nil {
  8663. logs.Error(err)
  8664. return
  8665. }
  8666. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8667. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8668. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8669. }
  8670. func UdMaterialIssuePush(c *gin.Context) {
  8671. appG := app.Gin{C: c}
  8672. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8673. fsions := gofasion.NewFasion(string(dataByte))
  8674. pastureid := fsions.Get("pastureId").ValueStr()
  8675. date := fsions.Get("date").ValueStr()
  8676. tx := restful.Engine.NewSession()
  8677. defer tx.Close()
  8678. pastureinfo := new(udPastureInfo)
  8679. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8680. if err != nil {
  8681. logs.Error(err)
  8682. return
  8683. }
  8684. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8685. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8686. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8687. }
  8688. //搅拌
  8689. func YmyUtirPush(c *gin.Context) {
  8690. appG := app.Gin{C: c}
  8691. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8692. fsions := gofasion.NewFasion(string(dataByte))
  8693. pastureid := fsions.Get("pastureId").ValueStr()
  8694. date := fsions.Get("date").ValueStr()
  8695. tx := restful.Engine.NewSession()
  8696. defer tx.Close()
  8697. pastureinfo := new(udPastureInfo)
  8698. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8699. if err != nil {
  8700. logs.Error(err)
  8701. return
  8702. }
  8703. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8704. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8705. }
  8706. //撒料
  8707. func YmyMaterialIssuePush(c *gin.Context) {
  8708. appG := app.Gin{C: c}
  8709. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8710. fsions := gofasion.NewFasion(string(dataByte))
  8711. pastureid := fsions.Get("pastureId").ValueStr()
  8712. date := fsions.Get("date").ValueStr()
  8713. tx := restful.Engine.NewSession()
  8714. defer tx.Close()
  8715. pastureinfo := new(udPastureInfo)
  8716. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8717. if err != nil {
  8718. logs.Error(err)
  8719. return
  8720. }
  8721. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8722. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8723. }
  8724. func YmyFeedtempletPush(c *gin.Context) {
  8725. appG := app.Gin{C: c}
  8726. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8727. fsions := gofasion.NewFasion(string(dataByte))
  8728. pastureid := fsions.Get("pastureId").ValueStr()
  8729. date := fsions.Get("date").ValueStr()
  8730. tx := restful.Engine.NewSession()
  8731. defer tx.Close()
  8732. pastureinfo := new(udPastureInfo)
  8733. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8734. if err != nil {
  8735. logs.Error(err)
  8736. return
  8737. }
  8738. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8739. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8740. }
  8741. //饲料
  8742. func YmySyncFeed(c *gin.Context) {
  8743. appG := app.Gin{C: c}
  8744. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8745. fsions := gofasion.NewFasion(string(dataByte))
  8746. pastureid := fsions.Get("pastureId").ValueStr()
  8747. // date := fsions.Get("date").ValueStr()
  8748. tx := restful.Engine.NewSession()
  8749. defer tx.Close()
  8750. ymy.YmySyncFeed(pastureid)
  8751. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8752. }
  8753. // 栏舍
  8754. func YmySyncBar(c *gin.Context) {
  8755. appG := app.Gin{C: c}
  8756. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8757. fsions := gofasion.NewFasion(string(dataByte))
  8758. pastureid := fsions.Get("pastureId").ValueStr()
  8759. // date := fsions.Get("date").ValueStr()
  8760. tx := restful.Engine.NewSession()
  8761. defer tx.Close()
  8762. pastureinfo := new(udPastureInfo)
  8763. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8764. if err != nil {
  8765. logs.Error(err)
  8766. return
  8767. }
  8768. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8769. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8770. }
  8771. func DelFeedTemplet(c *gin.Context) {
  8772. appG := app.Gin{C: c}
  8773. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8774. fsions := gofasion.NewFasion(string(dataByte))
  8775. ftId := fsions.Get("ftId").ValueStr()
  8776. // userId := fsions.Get("userId").ValueStr()
  8777. tx := restful.Engine.NewSession()
  8778. defer tx.Close()
  8779. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8780. if err != nil {
  8781. logs.Error(err)
  8782. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8783. return
  8784. }
  8785. /*
  8786. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8787. if err != nil {
  8788. logs.Error(err)
  8789. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8790. return
  8791. }
  8792. */
  8793. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8794. if err != nil {
  8795. logs.Error(err)
  8796. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8797. return
  8798. }
  8799. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8800. if err != nil {
  8801. logs.Error(err)
  8802. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8803. return
  8804. }
  8805. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8806. if count > 0 {
  8807. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8808. if err != nil {
  8809. logs.Error(err)
  8810. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8811. return
  8812. }
  8813. }
  8814. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8815. if err != nil {
  8816. logs.Error(err)
  8817. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8818. return
  8819. }
  8820. // var barIdStr []string
  8821. // for _, bar := range barIdList {
  8822. // barIdStr = append(barIdStr, bar["barid"])
  8823. // }
  8824. // if len(barIdStr) > 0 {
  8825. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8826. // if err != nil {
  8827. // logs.Error(err)
  8828. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8829. // return
  8830. // }
  8831. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8832. // if err != nil {
  8833. // logs.Error(err)
  8834. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8835. // return
  8836. // }
  8837. // now := time.Now()
  8838. // for _, newFpd := range newFpdDataList {
  8839. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8840. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8841. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8842. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8843. // if err != nil {
  8844. // logs.Error(err)
  8845. // appG.Response(http.StatusOK, e.ERROR, false)
  8846. // return
  8847. // }
  8848. // }
  8849. // for _, newFeedp := range newFeedpList {
  8850. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8851. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8852. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8853. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8854. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8855. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8856. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8857. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8858. // if err != nil {
  8859. // logs.Error(err)
  8860. // appG.Response(http.StatusOK, e.ERROR, false)
  8861. // return
  8862. // }
  8863. // }
  8864. // }
  8865. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8866. }
  8867. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8868. sysOpt := new(models.SysOpt)
  8869. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8870. lweight := 0.0
  8871. if sysOpt.InforValue != "" {
  8872. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8873. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8874. return
  8875. }
  8876. fmt.Println(sysOpt)
  8877. data := fasion["parammaps"].(map[string]interface{})
  8878. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8879. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8880. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8881. fmt.Println(lweight)
  8882. for _, downloadedplan := range downloadedplanList {
  8883. if downloadedplan.LWeight < lweight {
  8884. break
  8885. }
  8886. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8887. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8888. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8889. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8890. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8891. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8892. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8893. for i := 0; i <= int(lweightCount); i++ {
  8894. if i == 0 {
  8895. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8896. for _, downloadplandtl1 := range downloadplandtl1List {
  8897. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8898. }
  8899. for _, downloadplandtl2 := range downloadplandtl2List {
  8900. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8901. }
  8902. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8903. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8904. }
  8905. // && downloadedplan.LWeight >lweight
  8906. } else if i < int(lweightCount) {
  8907. parts := strings.Split(downloadedplan.ProjName, ".")
  8908. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8909. data := &models.DownloadedPlan{
  8910. PastureID: downloadedplan.PastureID,
  8911. MyDate: downloadedplan.MyDate,
  8912. ProjName: strings.Join(parts, "."),
  8913. DataCaptureNo: downloadedplan.DataCaptureNo,
  8914. TmrID: downloadedplan.TmrID,
  8915. TmrtName: downloadedplan.TmrtName,
  8916. HaveButton: downloadedplan.HaveButton,
  8917. InButtonType: downloadedplan.InButtonType,
  8918. PlanTime: downloadedplan.PlanTime,
  8919. InTime: downloadedplan.InTime,
  8920. CompletedTime: downloadedplan.CompletedTime,
  8921. IsCompleted: downloadedplan.IsCompleted,
  8922. LpPlanType: downloadedplan.LpPlanType,
  8923. Times: downloadedplan.Times,
  8924. Sort: downloadedplan.Sort,
  8925. Remark: downloadedplan.Remark,
  8926. ItemNum: downloadedplan.ItemNum,
  8927. OutItems: downloadedplan.OutItems,
  8928. FeedPName: downloadedplan.FeedPName,
  8929. FeedPCount: downloadedplan.FeedPCount,
  8930. Pid: downloadedplan.Pid,
  8931. TempID: downloadedplan.TempID,
  8932. TempletName: downloadedplan.TempletName,
  8933. PtsTempID: downloadedplan.PtsTempID,
  8934. PtsTempletName: downloadedplan.PtsTempletName,
  8935. ThoWeight: downloadedplan.ThoWeight,
  8936. FpWeight: downloadedplan.FpWeight,
  8937. LWeight: lweight,
  8938. IWeight: downloadedplan.IWeight,
  8939. OWeight: downloadedplan.OWeight,
  8940. TVersion: downloadedplan.TVersion,
  8941. PtVersion: downloadedplan.PtVersion,
  8942. Enable: downloadedplan.Enable,
  8943. IsUse: downloadedplan.IsUse,
  8944. OldTmrID: downloadedplan.OldTmrID,
  8945. DriverID: downloadedplan.DriverID,
  8946. Artificial: downloadedplan.Artificial,
  8947. }
  8948. _, err := tx.Insert(data)
  8949. fmt.Println(data, err)
  8950. for _, downloadplandtl1 := range downloadplandtl1List {
  8951. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8952. d1 := &models.DownloadPlanDtl1{
  8953. PastureID: downloadplandtl1.PastureID,
  8954. Pid: data.ID,
  8955. Flpid: downloadplandtl1.Flpid,
  8956. Fid: downloadplandtl1.Fid,
  8957. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8958. Sort: downloadplandtl1.Sort,
  8959. ButtonType: downloadplandtl1.ButtonType,
  8960. OptDevice: downloadplandtl1.OptDevice,
  8961. FeedCode: downloadplandtl1.FeedCode,
  8962. FName: downloadplandtl1.FName,
  8963. FeedSort: downloadplandtl1.FeedSort,
  8964. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8965. StirDelay: downloadplandtl1.StirDelay,
  8966. FWeight: downloadplandtl1.FWeight,
  8967. TmrLoadName: downloadplandtl1.TmrLoadName,
  8968. DryFeed: downloadplandtl1.DryFeed,
  8969. PriceFeed: downloadplandtl1.PriceFeed,
  8970. OutWeight: downloadplandtl1.OutWeight,
  8971. ErrRatio: downloadplandtl1.ErrRatio,
  8972. Date: downloadplandtl1.Date,
  8973. ButtonSucc: downloadplandtl1.ButtonSucc,
  8974. Type: downloadplandtl1.Type,
  8975. Deviation: downloadplandtl1.Deviation,
  8976. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8977. }
  8978. tx.Insert(d1)
  8979. }
  8980. for _, downloadplandtl2 := range downloadplandtl2List {
  8981. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8982. d2 := &models.DownloadPlanDtl2{
  8983. PastureID: downloadplandtl2.PastureID,
  8984. Pid: data.ID,
  8985. Flpid: downloadplandtl2.Flpid,
  8986. Fbarid: downloadplandtl2.Fbarid,
  8987. FName: downloadplandtl2.FName,
  8988. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8989. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8990. RemainLeftW: downloadplandtl2.RemainLeftW,
  8991. AllowRW: downloadplandtl2.AllowRW,
  8992. Sort: downloadplandtl2.Sort,
  8993. HaveButton: downloadplandtl2.HaveButton,
  8994. BeginTag: downloadplandtl2.BeginTag,
  8995. EndTag: downloadplandtl2.EndTag,
  8996. ButtonType: downloadplandtl2.ButtonType,
  8997. OptDevice: downloadplandtl2.OptDevice,
  8998. CowCount: downloadplandtl2.CowCount,
  8999. CowClassID: downloadplandtl2.CowClassID,
  9000. CowClassName: downloadplandtl2.CowClassName,
  9001. BigCowName: downloadplandtl2.BigCowName,
  9002. PWeight: downloadplandtl2.PWeight,
  9003. CCountRatio: downloadplandtl2.CCountRatio,
  9004. SumRTime: downloadplandtl2.SumRTime,
  9005. FeedTempletID: downloadplandtl2.FeedTempletID,
  9006. FeedTempletName: downloadplandtl2.FeedTempletName,
  9007. DryWeight: downloadplandtl2.DryWeight,
  9008. SumWeight: downloadplandtl2.SumWeight,
  9009. PriceWeight: downloadplandtl2.PriceWeight,
  9010. // ProcessTime :downloadplandtl2.ProcessTime ,
  9011. Fpid: downloadplandtl2.Fpid,
  9012. UseInBarType: downloadplandtl2.UseInBarType,
  9013. Date: downloadplandtl2.Date,
  9014. AllowRatio: downloadplandtl2.AllowRatio,
  9015. ErrRatio: downloadplandtl2.ErrRatio,
  9016. ButtonSucc: downloadplandtl2.ButtonSucc,
  9017. Type: downloadplandtl2.Type,
  9018. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9019. XxwBarCode: downloadplandtl2.XxwBarCode,
  9020. }
  9021. _, err := tx.Insert(d2)
  9022. fmt.Println(err)
  9023. }
  9024. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9025. d2 := &models.DownloadPlanDtl1Exec{
  9026. PastureID: downloadplandtl2.PastureID,
  9027. Pid: data.ID,
  9028. Flpid: downloadplandtl2.Flpid,
  9029. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9030. HaveButton: downloadplandtl2.HaveButton,
  9031. ButtonType: downloadplandtl2.ButtonType,
  9032. OptDevice: downloadplandtl2.OptDevice,
  9033. Sort: downloadplandtl2.Sort,
  9034. FName: downloadplandtl2.FName,
  9035. FCount: downloadplandtl2.FCount,
  9036. TmrLoadName: downloadplandtl2.TmrLoadName,
  9037. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9038. StirDelay: downloadplandtl2.StirDelay,
  9039. ButtonSucc: downloadplandtl2.ButtonSucc,
  9040. ErrRatio: downloadplandtl2.ErrRatio,
  9041. Date: downloadplandtl2.Date,
  9042. Type: downloadplandtl2.Type,
  9043. Deviation: downloadplandtl2.Deviation,
  9044. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9045. }
  9046. _, err := tx.Insert(d2)
  9047. fmt.Println(err)
  9048. }
  9049. } else {
  9050. parts := strings.Split(downloadedplan.ProjName, ".")
  9051. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9052. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9053. continue
  9054. }
  9055. data := &models.DownloadedPlan{
  9056. PastureID: downloadedplan.PastureID,
  9057. MyDate: downloadedplan.MyDate,
  9058. ProjName: strings.Join(parts, "."),
  9059. DataCaptureNo: downloadedplan.DataCaptureNo,
  9060. TmrID: downloadedplan.TmrID,
  9061. TmrtName: downloadedplan.TmrtName,
  9062. HaveButton: downloadedplan.HaveButton,
  9063. InButtonType: downloadedplan.InButtonType,
  9064. PlanTime: downloadedplan.PlanTime,
  9065. InTime: downloadedplan.InTime,
  9066. CompletedTime: downloadedplan.CompletedTime,
  9067. IsCompleted: downloadedplan.IsCompleted,
  9068. LpPlanType: downloadedplan.LpPlanType,
  9069. Times: downloadedplan.Times,
  9070. Sort: downloadedplan.Sort,
  9071. Remark: downloadedplan.Remark,
  9072. ItemNum: downloadedplan.ItemNum,
  9073. OutItems: downloadedplan.OutItems,
  9074. FeedPName: downloadedplan.FeedPName,
  9075. FeedPCount: downloadedplan.FeedPCount,
  9076. Pid: downloadedplan.Pid,
  9077. TempID: downloadedplan.TempID,
  9078. TempletName: downloadedplan.TempletName,
  9079. PtsTempID: downloadedplan.PtsTempID,
  9080. PtsTempletName: downloadedplan.PtsTempletName,
  9081. ThoWeight: downloadedplan.ThoWeight,
  9082. FpWeight: downloadedplan.FpWeight,
  9083. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9084. IWeight: downloadedplan.IWeight,
  9085. OWeight: downloadedplan.OWeight,
  9086. TVersion: downloadedplan.TVersion,
  9087. PtVersion: downloadedplan.PtVersion,
  9088. Enable: downloadedplan.Enable,
  9089. IsUse: downloadedplan.IsUse,
  9090. OldTmrID: downloadedplan.OldTmrID,
  9091. DriverID: downloadedplan.DriverID,
  9092. Artificial: downloadedplan.Artificial,
  9093. }
  9094. _, err := tx.Insert(data)
  9095. fmt.Println(data, err)
  9096. for _, downloadplandtl1 := range downloadplandtl1List {
  9097. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9098. d1 := &models.DownloadPlanDtl1{
  9099. PastureID: downloadplandtl1.PastureID,
  9100. Pid: data.ID,
  9101. Flpid: downloadplandtl1.Flpid,
  9102. Fid: downloadplandtl1.Fid,
  9103. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9104. Sort: downloadplandtl1.Sort,
  9105. ButtonType: downloadplandtl1.ButtonType,
  9106. OptDevice: downloadplandtl1.OptDevice,
  9107. FeedCode: downloadplandtl1.FeedCode,
  9108. FName: downloadplandtl1.FName,
  9109. FeedSort: downloadplandtl1.FeedSort,
  9110. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9111. StirDelay: downloadplandtl1.StirDelay,
  9112. FWeight: downloadplandtl1.FWeight,
  9113. TmrLoadName: downloadplandtl1.TmrLoadName,
  9114. DryFeed: downloadplandtl1.DryFeed,
  9115. PriceFeed: downloadplandtl1.PriceFeed,
  9116. OutWeight: downloadplandtl1.OutWeight,
  9117. ErrRatio: downloadplandtl1.ErrRatio,
  9118. Date: downloadplandtl1.Date,
  9119. ButtonSucc: downloadplandtl1.ButtonSucc,
  9120. Type: downloadplandtl1.Type,
  9121. Deviation: downloadplandtl1.Deviation,
  9122. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9123. }
  9124. tx.Insert(d1)
  9125. }
  9126. for _, downloadplandtl2 := range downloadplandtl2List {
  9127. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9128. d2 := &models.DownloadPlanDtl2{
  9129. PastureID: downloadplandtl2.PastureID,
  9130. Pid: data.ID,
  9131. Flpid: downloadplandtl2.Flpid,
  9132. Fbarid: downloadplandtl2.Fbarid,
  9133. FName: downloadplandtl2.FName,
  9134. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9135. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9136. RemainLeftW: downloadplandtl2.RemainLeftW,
  9137. AllowRW: downloadplandtl2.AllowRW,
  9138. Sort: downloadplandtl2.Sort,
  9139. HaveButton: downloadplandtl2.HaveButton,
  9140. BeginTag: downloadplandtl2.BeginTag,
  9141. EndTag: downloadplandtl2.EndTag,
  9142. ButtonType: downloadplandtl2.ButtonType,
  9143. OptDevice: downloadplandtl2.OptDevice,
  9144. CowCount: downloadplandtl2.CowCount,
  9145. CowClassID: downloadplandtl2.CowClassID,
  9146. CowClassName: downloadplandtl2.CowClassName,
  9147. BigCowName: downloadplandtl2.BigCowName,
  9148. PWeight: downloadplandtl2.PWeight,
  9149. CCountRatio: downloadplandtl2.CCountRatio,
  9150. SumRTime: downloadplandtl2.SumRTime,
  9151. FeedTempletID: downloadplandtl2.FeedTempletID,
  9152. FeedTempletName: downloadplandtl2.FeedTempletName,
  9153. DryWeight: downloadplandtl2.DryWeight,
  9154. SumWeight: downloadplandtl2.SumWeight,
  9155. PriceWeight: downloadplandtl2.PriceWeight,
  9156. // ProcessTime :downloadplandtl2.ProcessTime ,
  9157. Fpid: downloadplandtl2.Fpid,
  9158. UseInBarType: downloadplandtl2.UseInBarType,
  9159. Date: downloadplandtl2.Date,
  9160. AllowRatio: downloadplandtl2.AllowRatio,
  9161. ErrRatio: downloadplandtl2.ErrRatio,
  9162. ButtonSucc: downloadplandtl2.ButtonSucc,
  9163. Type: downloadplandtl2.Type,
  9164. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9165. XxwBarCode: downloadplandtl2.XxwBarCode,
  9166. }
  9167. _, err := tx.Insert(d2)
  9168. fmt.Println(err)
  9169. }
  9170. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9171. d2 := &models.DownloadPlanDtl1Exec{
  9172. PastureID: downloadplandtl2.PastureID,
  9173. Pid: data.ID,
  9174. Flpid: downloadplandtl2.Flpid,
  9175. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9176. HaveButton: downloadplandtl2.HaveButton,
  9177. ButtonType: downloadplandtl2.ButtonType,
  9178. OptDevice: downloadplandtl2.OptDevice,
  9179. Sort: downloadplandtl2.Sort,
  9180. FName: downloadplandtl2.FName,
  9181. FCount: downloadplandtl2.FCount,
  9182. TmrLoadName: downloadplandtl2.TmrLoadName,
  9183. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9184. StirDelay: downloadplandtl2.StirDelay,
  9185. ButtonSucc: downloadplandtl2.ButtonSucc,
  9186. ErrRatio: downloadplandtl2.ErrRatio,
  9187. Date: downloadplandtl2.Date,
  9188. Type: downloadplandtl2.Type,
  9189. Deviation: downloadplandtl2.Deviation,
  9190. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9191. }
  9192. fmt.Println(d2)
  9193. _, err := tx.Insert(d2)
  9194. fmt.Println(err)
  9195. }
  9196. }
  9197. }
  9198. }
  9199. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9200. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9201. for i, d := range downloadedplanSortList {
  9202. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9203. }
  9204. }
  9205. func EditPlanSort(c *gin.Context) {
  9206. appG := app.Gin{C: c}
  9207. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9208. fsions := gofasion.NewFasion(string(dataByte))
  9209. planIdStr := fsions.Get("planId").ValueStr()
  9210. mydate := fsions.Get("mydate").ValueStr()
  9211. sort := fsions.Get("sort").ValueStr()
  9212. tx := restful.Engine.NewSession()
  9213. defer tx.Close()
  9214. tx.Begin()
  9215. type downloadedplan struct {
  9216. Id int64 `xorm:"id"`
  9217. Sort int `xorm:"sort"`
  9218. Pid int64 `xorm:"pid"`
  9219. }
  9220. planInfo := new(downloadedplan)
  9221. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9222. if err != nil {
  9223. logs.Error(err)
  9224. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9225. tx.Rollback()
  9226. return
  9227. }
  9228. sort1, _ := strconv.Atoi(sort)
  9229. if sort1 == planInfo.Sort {
  9230. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9231. tx.Rollback()
  9232. return
  9233. }
  9234. 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()
  9235. if err != nil {
  9236. logs.Error(err)
  9237. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9238. tx.Rollback()
  9239. return
  9240. }
  9241. if count1 == 0 {
  9242. tx.Rollback()
  9243. logs.Error(err)
  9244. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9245. return
  9246. }
  9247. 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()
  9248. if err != nil {
  9249. logs.Error(err)
  9250. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9251. tx.Rollback()
  9252. return
  9253. }
  9254. if count > 0 {
  9255. tx.Rollback()
  9256. logs.Error(err)
  9257. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9258. return
  9259. }
  9260. if planInfo.Sort > sort1 {
  9261. 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()
  9262. if err != nil {
  9263. logs.Error(err)
  9264. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9265. tx.Rollback()
  9266. return
  9267. }
  9268. var minSort, pidCount int
  9269. for _, sort := range minSortList {
  9270. minSort, _ = strconv.Atoi(sort["sort"])
  9271. }
  9272. planList := make([]*downloadedplan, 0)
  9273. 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)
  9274. if err != nil {
  9275. logs.Error(err)
  9276. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9277. tx.Rollback()
  9278. return
  9279. }
  9280. planPid := planInfo.Pid
  9281. planList1 := make([]*downloadedplan, 0)
  9282. planList2 := make([]*downloadedplan, 0)
  9283. for _, plan := range planList {
  9284. if plan.Pid == planPid {
  9285. pidCount++
  9286. planList1 = append(planList1, plan)
  9287. } else {
  9288. planList2 = append(planList2, plan)
  9289. }
  9290. }
  9291. planList1 = append(planList1, planList2...)
  9292. for i, plan := range planList1 {
  9293. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9294. if err != nil {
  9295. logs.Error(err)
  9296. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9297. tx.Rollback()
  9298. return
  9299. }
  9300. }
  9301. } else {
  9302. 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()
  9303. if err != nil {
  9304. logs.Error(err)
  9305. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9306. tx.Rollback()
  9307. return
  9308. }
  9309. var maxSort int
  9310. for _, sort := range maxSortList {
  9311. maxSort, _ = strconv.Atoi(sort["sort"])
  9312. }
  9313. planList := make([]*downloadedplan, 0)
  9314. 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)
  9315. if err != nil {
  9316. logs.Error(err)
  9317. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9318. tx.Rollback()
  9319. return
  9320. }
  9321. planPid := planInfo.Pid
  9322. planList1 := make([]*downloadedplan, 0)
  9323. planList2 := make([]*downloadedplan, 0)
  9324. for _, plan := range planList {
  9325. if plan.Pid == planPid {
  9326. // pidCount++
  9327. planList1 = append(planList1, plan)
  9328. } else {
  9329. planList2 = append(planList2, plan)
  9330. }
  9331. }
  9332. planList2 = append(planList2, planList1...)
  9333. for i, plan := range planList2 {
  9334. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9335. if err != nil {
  9336. logs.Error(err)
  9337. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9338. tx.Rollback()
  9339. return
  9340. }
  9341. }
  9342. }
  9343. err = tx.Commit()
  9344. if err != nil {
  9345. logs.Error(err)
  9346. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9347. tx.Rollback()
  9348. return
  9349. }
  9350. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9351. }
  9352. func EditDownloadedplanArtificial(c *gin.Context) {
  9353. appG := app.Gin{C: c}
  9354. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9355. fsions := gofasion.NewFasion(string(dataByte))
  9356. planIdStr := fsions.Get("planId").ValueStr()
  9357. tx := restful.Engine.NewSession()
  9358. defer tx.Close()
  9359. tx.Begin()
  9360. planIdList := strings.Split(planIdStr, ",")
  9361. for _, planId := range planIdList {
  9362. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9363. if err != nil {
  9364. logs.Error(err)
  9365. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9366. tx.Rollback()
  9367. return
  9368. }
  9369. }
  9370. err := tx.Commit()
  9371. if err != nil {
  9372. logs.Error(err)
  9373. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9374. tx.Rollback()
  9375. return
  9376. }
  9377. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9378. }
  9379. type PlanRFID struct {
  9380. RFID string `json:"RFID"`
  9381. Lweight string `json:"lweight"`
  9382. Gear string `json:"gear"`
  9383. Speed string `json:"speed"`
  9384. }
  9385. func GetPlanRFID(c *gin.Context) {
  9386. appG := app.Gin{C: c}
  9387. RFIDStr := c.Query("RFID")
  9388. planRFIDList := make([]*PlanRFID, 0)
  9389. planRFIDList = append(planRFIDList, &PlanRFID{
  9390. RFID: RFIDStr,
  9391. Lweight: "1411.1",
  9392. Gear: "1",
  9393. Speed: "10",
  9394. })
  9395. planRFIDList = append(planRFIDList, &PlanRFID{
  9396. RFID: RFIDStr,
  9397. Lweight: "1322.1",
  9398. Gear: "1",
  9399. Speed: "10",
  9400. })
  9401. planRFIDList = append(planRFIDList, &PlanRFID{
  9402. RFID: RFIDStr,
  9403. Lweight: "1904.1",
  9404. Gear: "1",
  9405. Speed: "10",
  9406. })
  9407. planRFIDList = append(planRFIDList, &PlanRFID{
  9408. RFID: RFIDStr,
  9409. Lweight: "1870.1",
  9410. Gear: "1",
  9411. Speed: "10",
  9412. })
  9413. planRFIDList = append(planRFIDList, &PlanRFID{
  9414. RFID: RFIDStr,
  9415. Lweight: "2041.1",
  9416. Gear: "1",
  9417. Speed: "10",
  9418. })
  9419. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9420. }
  9421. type tmrEquipmentMuster struct {
  9422. A string
  9423. N string
  9424. }
  9425. func GetTmrEquipmentMuster(c *gin.Context) {
  9426. appG := app.Gin{C: c}
  9427. id := c.Query("id")
  9428. tx := restful.Engine.NewSession()
  9429. defer tx.Close()
  9430. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9431. if err != nil {
  9432. logs.Error(err)
  9433. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9434. return
  9435. }
  9436. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9437. for _, data := range dataList {
  9438. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9439. for _, g := range tmrEquipmentMusterList {
  9440. a, _ := strconv.ParseFloat(g.A, 64)
  9441. n, _ := strconv.ParseFloat(g.N, 64)
  9442. a1, n1 := ddmmtoddd(a, n)
  9443. g.A = fmt.Sprintf("%f", n1)
  9444. g.N = fmt.Sprintf("%f", a1)
  9445. }
  9446. }
  9447. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9448. }
  9449. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9450. lngDegree := fmt.Sprintf("%f", lng/100)
  9451. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9452. lngDegreeInt := int(lngDegreefloat * 1000000)
  9453. dd := lngDegreeInt / 100 * 100 / 60
  9454. fmt.Println(dd)
  9455. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9456. latDegree := fmt.Sprintf("%f", lat/100)
  9457. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9458. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9459. latDegreeInt := int(latDegreefloat * 1000000)
  9460. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9461. a, _ := strconv.ParseFloat(lngStr, 64)
  9462. b, _ := strconv.ParseFloat(latStr, 64)
  9463. return coordtransform.WGS84toGCJ02(b, a)
  9464. }
  9465. func EditDownloadedplanExecWeight(c *gin.Context) {
  9466. appG := app.Gin{C: c}
  9467. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9468. fsions := gofasion.NewFasion(string(dataByte))
  9469. pid := fsions.Get("pid").ValueStr()
  9470. sort := fsions.Get("sort").ValueStr()
  9471. weight := fsions.Get("weight").ValueStr()
  9472. userId := fsions.Get("userId").ValueStr()
  9473. tx := restful.Engine.NewSession()
  9474. defer tx.Close()
  9475. tx.Begin()
  9476. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9477. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9478. pid, sort, pid, sort, weight, userId)
  9479. if err != nil {
  9480. logs.Error(err)
  9481. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9482. tx.Rollback()
  9483. return
  9484. }
  9485. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9486. if err != nil {
  9487. logs.Error(err)
  9488. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9489. tx.Rollback()
  9490. return
  9491. }
  9492. _, 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)
  9493. if err != nil {
  9494. logs.Error(err)
  9495. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9496. tx.Rollback()
  9497. return
  9498. }
  9499. err = tx.Commit()
  9500. if err != nil {
  9501. logs.Error(err)
  9502. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9503. tx.Rollback()
  9504. return
  9505. }
  9506. appG.Response(http.StatusOK, e.SUCCESS, true)
  9507. }
  9508. func EditDownloadplandtl2Weight(c *gin.Context) {
  9509. appG := app.Gin{C: c}
  9510. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9511. fsions := gofasion.NewFasion(string(dataByte))
  9512. pid := fsions.Get("pid").ValueStr()
  9513. sort := fsions.Get("sort").ValueStr()
  9514. weight := fsions.Get("weight").ValueStr()
  9515. userId := fsions.Get("userId").ValueStr()
  9516. tx := restful.Engine.NewSession()
  9517. defer tx.Close()
  9518. tx.Begin()
  9519. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9520. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9521. pid, sort, pid, sort, weight, userId)
  9522. if err != nil {
  9523. logs.Error(err)
  9524. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9525. tx.Rollback()
  9526. return
  9527. }
  9528. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9529. if err != nil {
  9530. logs.Error(err)
  9531. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9532. tx.Rollback()
  9533. return
  9534. }
  9535. err = tx.Commit()
  9536. if err != nil {
  9537. logs.Error(err)
  9538. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9539. tx.Rollback()
  9540. return
  9541. }
  9542. appG.Response(http.StatusOK, e.SUCCESS, true)
  9543. }
  9544. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9545. params := fasion.Get("parammaps")
  9546. surplus := params.Get("surplus").ValueStr()
  9547. surplusId := params.Get("surplusId").ValueStr()
  9548. tx := restful.Engine.NewSession()
  9549. defer tx.Close()
  9550. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9551. if surplusId != "0" {
  9552. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9553. if err != nil {
  9554. log.Println("PostDataByName-error-1: ", err)
  9555. return errors.New("配方修改失败!")
  9556. }
  9557. type ftdetail struct {
  9558. Id string
  9559. Fname string
  9560. Sort int64
  9561. }
  9562. ftList := make([]*ftdetail, 0)
  9563. for _, data := range dataList {
  9564. ft := new(ftdetail)
  9565. ft.Fname = data["fname"]
  9566. ft.Id = data["id"]
  9567. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9568. if err != nil {
  9569. log.Println("PostDataByName-error-2: ", err)
  9570. return err
  9571. }
  9572. ft.Sort = sort
  9573. ftList = append(ftList, ft)
  9574. }
  9575. if surplus == "日粮" {
  9576. for _, ft := range ftList {
  9577. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9578. }
  9579. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9580. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9581. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9582. fmt.Println(err)
  9583. } else {
  9584. var sort int64
  9585. for _, ft := range ftList {
  9586. if ft.Fname == surplus {
  9587. sort = ft.Sort
  9588. break
  9589. }
  9590. }
  9591. if sort == 0 {
  9592. for _, ft := range ftList {
  9593. ft.Sort = ft.Sort + 1
  9594. }
  9595. } else {
  9596. for _, ft := range ftList {
  9597. if ft.Sort >= sort {
  9598. ft.Sort = ft.Sort + 1
  9599. }
  9600. }
  9601. }
  9602. for _, ft := range ftList {
  9603. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9604. }
  9605. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9606. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9607. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9608. if err != nil {
  9609. log.Println("PostDataByName-error-1: ", err)
  9610. fmt.Println(err)
  9611. return errors.New("配方修改失败!")
  9612. }
  9613. }
  9614. }
  9615. return nil
  9616. }
  9617. func FeedSurplus(fasion *gofasion.Fasion) {
  9618. tx := restful.Engine.NewSession()
  9619. defer tx.Close()
  9620. params := fasion.Get("parammaps")
  9621. feedId := params.Get("id").ValueStr()
  9622. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9623. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9624. }
  9625. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9626. // params := fasion.Get("parammaps")
  9627. // surplus := params.Get("surplus").ValueStr()
  9628. // surplusId := params.Get("surplusId").ValueStr()
  9629. tx := restful.Engine.NewSession()
  9630. defer tx.Close()
  9631. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9632. if surplusId != "0" {
  9633. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9634. if err != nil {
  9635. log.Println("PostDataByName-error-1: ", err)
  9636. return errors.New("配方修改失败!")
  9637. }
  9638. type ftdetail struct {
  9639. Id string
  9640. Fname string
  9641. Sort int64
  9642. }
  9643. ftList := make([]*ftdetail, 0)
  9644. for _, data := range dataList {
  9645. ft := new(ftdetail)
  9646. ft.Fname = data["fname"]
  9647. ft.Id = data["id"]
  9648. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9649. if err != nil {
  9650. log.Println("PostDataByName-error-2: ", err)
  9651. return err
  9652. }
  9653. ft.Sort = sort
  9654. ftList = append(ftList, ft)
  9655. }
  9656. if surplus == "日粮" {
  9657. for _, ft := range ftList {
  9658. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9659. }
  9660. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9661. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9662. pastureId, id, surplusId, surplusId, surplusId)
  9663. fmt.Println(err)
  9664. } else {
  9665. var sort int64
  9666. for _, ft := range ftList {
  9667. if ft.Fname == surplus {
  9668. sort = ft.Sort
  9669. break
  9670. }
  9671. }
  9672. if sort == 0 {
  9673. for _, ft := range ftList {
  9674. ft.Sort = ft.Sort + 1
  9675. }
  9676. } else {
  9677. for _, ft := range ftList {
  9678. if ft.Sort >= sort {
  9679. ft.Sort = ft.Sort + 1
  9680. }
  9681. }
  9682. }
  9683. for _, ft := range ftList {
  9684. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9685. }
  9686. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9687. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9688. id, surplusId, surplusId, sort, surplusId, pastureId)
  9689. if err != nil {
  9690. log.Println("PostDataByName-error-1: ", err)
  9691. fmt.Println(err)
  9692. return errors.New("配方修改失败!")
  9693. }
  9694. }
  9695. }
  9696. return nil
  9697. }
  9698. func GetLanguageStatus() string {
  9699. tx := restful.Engine.NewSession()
  9700. defer tx.Close()
  9701. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9702. if err != nil {
  9703. log.Println(err)
  9704. return "0"
  9705. }
  9706. return dataList[0]["inforvalue"]
  9707. }
  9708. func EditLanguage(c *gin.Context) {
  9709. appG := app.Gin{C: c}
  9710. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9711. fsions := gofasion.NewFasion(string(dataByte))
  9712. language := fsions.Get("language").ValueStr()
  9713. tx := restful.Engine.NewSession()
  9714. defer tx.Close()
  9715. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9716. if err != nil {
  9717. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9718. return
  9719. }
  9720. if language == "0" {
  9721. _, err := tx.Exec(`delete from dictlist `)
  9722. if err != nil {
  9723. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9724. return
  9725. }
  9726. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9727. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9728. if err != nil {
  9729. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9730. return
  9731. }
  9732. } else {
  9733. _, err := tx.Exec(`delete from dictlist `)
  9734. if err != nil {
  9735. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9736. return
  9737. }
  9738. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9739. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9740. if err != nil {
  9741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9742. return
  9743. }
  9744. }
  9745. appG.Response(http.StatusOK, e.SUCCESS, true)
  9746. }
  9747. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9748. tx := restful.Engine.NewSession()
  9749. defer tx.Close()
  9750. 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
  9751. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9752. if err != nil {
  9753. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9754. return
  9755. }
  9756. for _, dataexcel := range barList {
  9757. // dataexcel := make(map[string]interface{}, 0)
  9758. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9759. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9760. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9761. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9762. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9763. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9764. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9765. // if err != nil {
  9766. // logs.Error(err)
  9767. // return
  9768. // }
  9769. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9770. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9771. // if err != nil {
  9772. // logs.Error(err)
  9773. // return
  9774. // }
  9775. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9776. continue
  9777. }
  9778. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9779. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9780. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9781. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9782. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9783. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9784. /*
  9785. tx.SQL(` update lpplandtl1 set lweight = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9786. if err != nil {
  9787. logs.Error(err)
  9788. return
  9789. }
  9790. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9791. if err != nil {
  9792. logs.Error(err)
  9793. return
  9794. }
  9795. */
  9796. exist, err := tx.SQL(` select id from feedp where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9797. if err != nil {
  9798. logs.Error(err)
  9799. return
  9800. }
  9801. if !exist {
  9802. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9803. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9804. if err != nil {
  9805. logs.Error(err)
  9806. return
  9807. }
  9808. }
  9809. var feedpargs []interface{}
  9810. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9811. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9812. if _, ok := dataexcel["ftname"]; ok {
  9813. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9814. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9815. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9816. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9817. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9818. } else {
  9819. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9820. }
  9821. if _, ok := dataexcel["ptsfname"]; ok {
  9822. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9823. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9824. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9825. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9826. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9827. } else {
  9828. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9829. }
  9830. upFeedpSql += " where barname = ? and pastureid = ? "
  9831. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9832. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9833. if err != nil {
  9834. logs.Error(err)
  9835. return
  9836. }
  9837. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9838. if err != nil {
  9839. logs.Error(err)
  9840. return
  9841. }
  9842. if !exist1 {
  9843. _, 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) `,
  9844. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9845. if err != nil {
  9846. logs.Error(err)
  9847. return
  9848. }
  9849. }
  9850. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9851. if err != nil {
  9852. logs.Error(err)
  9853. return
  9854. }
  9855. if !exist2 {
  9856. _, 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) `,
  9857. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9858. if err != nil {
  9859. logs.Error(err)
  9860. return
  9861. }
  9862. }
  9863. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9864. if err != nil {
  9865. logs.Error(err)
  9866. return
  9867. }
  9868. if !exist3 {
  9869. _, 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) `,
  9870. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9871. if err != nil {
  9872. logs.Error(err)
  9873. return
  9874. }
  9875. }
  9876. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9877. if err != nil {
  9878. logs.Error(err)
  9879. return
  9880. }
  9881. if !exist4 {
  9882. _, 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) `,
  9883. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9884. if err != nil {
  9885. logs.Error(err)
  9886. return
  9887. }
  9888. }
  9889. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9890. if err != nil {
  9891. logs.Error(err)
  9892. return
  9893. }
  9894. if !exist5 {
  9895. _, 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) `,
  9896. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9897. if err != nil {
  9898. logs.Error(err)
  9899. return
  9900. }
  9901. }
  9902. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9903. if err != nil {
  9904. logs.Error(err)
  9905. return
  9906. }
  9907. if !exist6 {
  9908. _, 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) `,
  9909. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9910. if err != nil {
  9911. logs.Error(err)
  9912. return
  9913. }
  9914. }
  9915. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9916. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9917. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9918. and pastureid = ? and times = ?`
  9919. var fpdargs1 []interface{}
  9920. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9921. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9922. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9923. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9924. if err != nil {
  9925. fmt.Println(err)
  9926. return
  9927. }
  9928. var fpdargs2 []interface{}
  9929. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9930. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9931. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9932. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9933. if err != nil {
  9934. fmt.Println(err)
  9935. return
  9936. }
  9937. var fpdargs3 []interface{}
  9938. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9939. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9940. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9941. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9942. if err != nil {
  9943. fmt.Println(err)
  9944. return
  9945. }
  9946. var fpdargs4 []interface{}
  9947. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9948. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9949. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9950. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9951. if err != nil {
  9952. fmt.Println(err)
  9953. return
  9954. }
  9955. var fpdargs5 []interface{}
  9956. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9957. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9958. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9959. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9960. if err != nil {
  9961. fmt.Println(err)
  9962. return
  9963. }
  9964. var fpdargs6 []interface{}
  9965. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9966. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9967. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9968. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9969. if err != nil {
  9970. fmt.Println(err)
  9971. return
  9972. }
  9973. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9974. 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()
  9975. if err != nil {
  9976. return
  9977. }
  9978. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9979. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9980. upFpdetailList := make([]*upFpdetail, 0)
  9981. for _, newfpd := range newList {
  9982. for _, oldfpd := range oldFpdList {
  9983. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9984. var oldweight, newweight float64
  9985. if oldfpd["weight"] != nil {
  9986. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9987. }
  9988. if newfpd["weight"] != nil {
  9989. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9990. }
  9991. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9992. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9993. Old: oldweight,
  9994. New: newweight,
  9995. Times: newfpd["times"].(int64),
  9996. Ptid: newfpd["ptid"].(int64),
  9997. Fweight: fweight,
  9998. Id: oldfpd["id"].(int64),
  9999. })
  10000. break
  10001. }
  10002. }
  10003. }
  10004. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  10005. }
  10006. }
  10007. func AddXxwFtdetail(c *gin.Context) {
  10008. appG := app.Gin{C: c}
  10009. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10010. c.Bind(&xxwFtdetailList)
  10011. tx := restful.Engine.NewSession()
  10012. defer tx.Close()
  10013. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10014. if err != nil {
  10015. logs.Error(err)
  10016. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10017. }
  10018. _, err = tx.Insert(xxwFtdetailList)
  10019. if err != nil {
  10020. logs.Error(err)
  10021. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10022. }
  10023. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10024. appG.Response(http.StatusOK, e.SUCCESS, true)
  10025. }
  10026. func AddXxwFeedtemplet(c *gin.Context) {
  10027. appG := app.Gin{C: c}
  10028. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10029. c.Bind(&xxwFeedtempletList)
  10030. tx := restful.Engine.NewSession()
  10031. defer tx.Close()
  10032. pastureinfo := new(udPastureInfo)
  10033. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10034. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10035. if err != nil {
  10036. logs.Error(err)
  10037. return
  10038. }
  10039. for _, ft := range xxwFeedtempletList {
  10040. ids, err := setting.SnowIds.NextId()
  10041. if err != nil {
  10042. ids = time.Now().UnixNano()
  10043. logging.Info("create SnowIds err", err)
  10044. }
  10045. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10046. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10047. ft.RecipeobjName, ft.RecipeobjName)
  10048. if err != nil {
  10049. logs.Error(err)
  10050. return
  10051. }
  10052. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10053. _, 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')),
  10054. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10055. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10056. if err != nil {
  10057. logs.Error(err)
  10058. return
  10059. }
  10060. }
  10061. appG.Response(http.StatusOK, e.SUCCESS, true)
  10062. }
  10063. func ProcessExcel(c *gin.Context) {
  10064. appG := app.Gin{C: c}
  10065. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10066. fasion := gofasion.NewFasion(string(dataByte))
  10067. params := fasion.Get("parammaps")
  10068. pastureid := params.Get("pastureid").ValueStr()
  10069. startTime := params.Get("startTime").ValueStr()
  10070. stopTime := params.Get("stopTime").ValueStr()
  10071. iscompleted := params.Get("iscompleted").ValueStr()
  10072. lpplantype := params.Get("lpplantype").ValueStr()
  10073. error := params.Get("error").ValueStr()
  10074. hlwc1 := params.Get("hlwc1").ValueStr()
  10075. hlwc2 := params.Get("hlwc2").ValueStr()
  10076. slwc1 := params.Get("slwc1").ValueStr()
  10077. slwc2 := params.Get("slwc2").ValueStr()
  10078. hlzq1 := params.Get("hlzq1").ValueStr()
  10079. hlzq2 := params.Get("hlzq2").ValueStr()
  10080. slzq1 := params.Get("slzq1").ValueStr()
  10081. slzq2 := params.Get("slzq2").ValueStr()
  10082. fclassid := params.Get("fclassid").ValueStr()
  10083. minproesstime := params.Get("minproesstime").ValueStr()
  10084. maxproesstime := params.Get("maxproesstime").ValueStr()
  10085. tx := restful.Engine.NewSession()
  10086. defer tx.Close()
  10087. planList, err := tx.SQL(`SELECT
  10088. 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
  10089. FROM downloadedplan d
  10090. join pasture p on p.pastureid = d.pastureid
  10091. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10092. AND mydate >= ? AND mydate <= ?
  10093. AND (iscompleted=? or ?='')
  10094. AND (lpplantype = ? or ? = '')
  10095. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10096. 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
  10097. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10098. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10099. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10100. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10101. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10102. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10103. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10104. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10105. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10106. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10107. 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,
  10108. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10109. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10110. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10111. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10112. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10113. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10114. or (?= '' and ? = '' ))
  10115. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10116. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10117. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10118. maxproesstime, minproesstime, maxproesstime).QueryString()
  10119. if err != nil {
  10120. logs.Error(err)
  10121. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10122. return
  10123. }
  10124. planExecList, err := tx.SQL(`SELECT
  10125. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10126. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10127. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10128. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10129. ) proesstime,
  10130. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10131. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10132. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10133. sumproesstime, d1.pid,
  10134. d1.sort,
  10135. d1.fname,
  10136. d1.lweight,
  10137. d1.actualweightminus,
  10138. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10139. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10140. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10141. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10142. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10143. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10144. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10145. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10146. d1.begintime stoptime,
  10147. d1.lastactualweight,
  10148. d1.actualweight,
  10149. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10150. case d1.buttontype
  10151. when 1 then '自动'
  10152. when 2 then '手动'
  10153. when 3 then '手动'
  10154. end,
  10155. case d1.buttontype
  10156. when 1 then 'Automatic'
  10157. when 2 then 'Manual'
  10158. when 3 then 'Manual'
  10159. end
  10160. ) buttontype
  10161. FROM
  10162. downloadplandtl1_exec d1
  10163. WHERE d1.date between ? and ?
  10164. ORDER BY sort
  10165. `, startTime, stopTime).QueryString()
  10166. if err != nil {
  10167. logs.Error(err)
  10168. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10169. return
  10170. }
  10171. planExec2, err := tx.SQL(`SELECT
  10172. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10173. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10174. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10175. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10176. ) proesstime,
  10177. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10178. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10179. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10180. d1.sort,
  10181. d1.fname,
  10182. d1.lweight,
  10183. d1.actualweightminus,
  10184. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10185. ABS(d1.lweight- d1.actualweightminus) diff,
  10186. 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,
  10187. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10188. d1.begintime stoptime,
  10189. d1.lastactualweight,
  10190. d1.actualweight,d1.pid
  10191. FROM
  10192. downloadplandtl2 d1
  10193. WHERE d1.date between ? and ?
  10194. ORDER BY sort`, startTime, stopTime).QueryString()
  10195. if err != nil {
  10196. logs.Error(err)
  10197. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10198. return
  10199. }
  10200. // 创建一个新的 Excel 文件
  10201. f := excelizexuri.NewFile()
  10202. // 创建工作表名称
  10203. sheetName := "Sheet1"
  10204. // border := []excelizexuri.Border{
  10205. // {Type: "left", Color: "000000", Style: 1},
  10206. // {Type: "right", Color: "000000", Style: 1},
  10207. // {Type: "top", Color: "000000", Style: 1},
  10208. // {Type: "bottom", Color: "000000", Style: 1},
  10209. // }
  10210. // 创建新的样式
  10211. style := &excelizexuri.Style{
  10212. // Border: border,
  10213. Alignment: &excelizexuri.Alignment{
  10214. Vertical: "center",
  10215. Horizontal: "center",
  10216. ShrinkToFit: true,
  10217. WrapText: true,
  10218. },
  10219. }
  10220. styleTitle := &excelizexuri.Style{
  10221. Fill: excelizexuri.Fill{
  10222. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10223. },
  10224. // Border: border,
  10225. Font: &excelizexuri.Font{
  10226. Bold: true, // 加粗
  10227. Size: 24, // 字体大小
  10228. // Name: "宋体", // 字体名称
  10229. // WrapText :true,
  10230. Color: "000000", // 字体颜色(黑色)
  10231. },
  10232. Alignment: &excelizexuri.Alignment{
  10233. Vertical: "center", // 垂直居中
  10234. Horizontal: "center", // 水平居中
  10235. ShrinkToFit: true,
  10236. WrapText: true,
  10237. },
  10238. }
  10239. // 创建样式 ID
  10240. styleTitleId, err := f.NewStyle(styleTitle)
  10241. if err != nil {
  10242. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10243. return
  10244. }
  10245. // 创建样式 ID
  10246. styleID, err := f.NewStyle(style)
  10247. if err != nil {
  10248. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10249. return
  10250. }
  10251. // 合并单元格并设置内容
  10252. f.MergeCell(sheetName, "A1", "K1")
  10253. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10254. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10255. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10256. planExecMap := make(map[string][]map[string]string, 0)
  10257. for _, planExec := range planExecList {
  10258. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10259. }
  10260. plan2Map := make(map[string][]map[string]string, 0)
  10261. for _, plan2 := range planExec2 {
  10262. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10263. }
  10264. num := 2
  10265. var notBorder []int
  10266. for _, plan := range planList {
  10267. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10268. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10269. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10270. for i, header := range headers {
  10271. // 从 A2 开始
  10272. if header == "开始日期" {
  10273. cell := "%" + fmt.Sprintf("c%d", num)
  10274. cell = fmt.Sprintf(cell, 'A'+i+1)
  10275. f.SetCellValue(sheetName, cell, header)
  10276. f.SetCellStyle(sheetName, cell, cell, styleID)
  10277. continue
  10278. }
  10279. cell := "%" + fmt.Sprintf("c%d", num)
  10280. cell = fmt.Sprintf(cell, 'A'+i)
  10281. f.SetCellValue(sheetName, cell, header)
  10282. f.SetCellStyle(sheetName, cell, cell, styleID)
  10283. }
  10284. num += 1
  10285. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10286. cell := "%" + fmt.Sprintf("c%d", num)
  10287. cell = fmt.Sprintf(cell, 'A'+0)
  10288. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10289. f.SetCellStyle(sheetName, cell, cell, styleID)
  10290. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10291. cell = "%" + fmt.Sprintf("c%d", num)
  10292. cell = fmt.Sprintf(cell, 'A'+1)
  10293. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10294. f.SetCellStyle(sheetName, cell, cell, styleID)
  10295. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10296. cell = "%" + fmt.Sprintf("c%d", num)
  10297. cell = fmt.Sprintf(cell, 'A'+2)
  10298. f.SetCellValue(sheetName, cell, plan["projname"])
  10299. f.SetCellStyle(sheetName, cell, cell, styleID)
  10300. cell = "%" + fmt.Sprintf("c%d", num)
  10301. cell = fmt.Sprintf(cell, 'A'+3)
  10302. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10303. f.SetCellValue(sheetName, cell, plan["mydate"])
  10304. f.SetCellStyle(sheetName, cell, cell, styleID)
  10305. cell = "%" + fmt.Sprintf("c%d", num)
  10306. cell = fmt.Sprintf(cell, 'A'+6)
  10307. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10308. f.SetCellValue(sheetName, cell, plan["intime"])
  10309. f.SetCellStyle(sheetName, cell, cell, styleID)
  10310. num += 1
  10311. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10312. for i, header := range headers1 {
  10313. cell = "%" + fmt.Sprintf("c%d", num)
  10314. cell = fmt.Sprintf(cell, 'C'+i)
  10315. f.SetCellValue(sheetName, cell, header)
  10316. f.SetCellStyle(sheetName, cell, cell, styleID)
  10317. // maxWidth := len(header)
  10318. // colName := string('C' + i)
  10319. // f.SetColWidth(sheetName, colName, colName, 20)
  10320. f.SetColWidth(sheetName, header, header, 40)
  10321. }
  10322. num += 1
  10323. // 在循环外部创建红色样式(只创建一次)
  10324. redStyle := &excelizexuri.Style{
  10325. Fill: excelizexuri.Fill{
  10326. Type: "pattern",
  10327. Color: []string{"FF0000"},
  10328. Pattern: 1,
  10329. },
  10330. // Font: &excelizexuri.Font{
  10331. // Bold: true, // 加粗
  10332. // Size: 24, // 字体大小
  10333. // // Name: "宋体", // 字体名称
  10334. // // WrapText :true,
  10335. // Color: "FFFF0000", // 字体颜色(黑色)
  10336. // },
  10337. Alignment: &excelizexuri.Alignment{
  10338. Vertical: "center",
  10339. Horizontal: "center",
  10340. ShrinkToFit: true,
  10341. WrapText: true,
  10342. },
  10343. }
  10344. redStyleID, err := f.NewStyle(redStyle)
  10345. if err != nil {
  10346. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10347. return
  10348. }
  10349. // 在循环内部正确使用条件判断
  10350. for _, planExec := range planExecMap[plan["id"]] {
  10351. var currentStyleID int
  10352. if planExec["abnormal"] == "1" {
  10353. currentStyleID = redStyleID
  10354. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10355. } else {
  10356. currentStyleID = styleID
  10357. }
  10358. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10359. sort, _ := strconv.Atoi(planExec["sort"])
  10360. f.SetCellValue(sheetName, cell, sort)
  10361. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10362. cell = fmt.Sprintf("D%d", num)
  10363. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10364. f.SetCellValue(sheetName, cell, lweight)
  10365. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10366. cell = fmt.Sprintf("E%d", num)
  10367. if _, ok := planExec["actualweightminus"]; ok {
  10368. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10369. f.SetCellValue(sheetName, cell, actualweightminus)
  10370. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10371. } else {
  10372. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10373. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10374. }
  10375. cell = fmt.Sprintf("F%d", num)
  10376. f.SetCellValue(sheetName, cell, planExec["fname"])
  10377. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10378. cell = fmt.Sprintf("G%d", num)
  10379. if _, ok := planExec["diff"]; ok {
  10380. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10381. f.SetCellValue(sheetName, cell, diff)
  10382. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10383. } else {
  10384. f.SetCellValue(sheetName, cell, planExec["diff"])
  10385. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10386. }
  10387. cell = fmt.Sprintf("H%d", num)
  10388. if _, ok := planExec["diffRate"]; ok {
  10389. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10390. f.SetCellValue(sheetName, cell, diffRate)
  10391. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10392. } else {
  10393. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10394. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10395. }
  10396. cell = fmt.Sprintf("I%d", num)
  10397. f.SetCellValue(sheetName, cell, planExec["intime"])
  10398. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10399. cell = fmt.Sprintf("J%d", num)
  10400. if _, ok := planExec["lastactualweight"]; ok {
  10401. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10402. f.SetCellValue(sheetName, cell, lastactualweight)
  10403. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10404. } else {
  10405. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10406. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10407. }
  10408. cell = fmt.Sprintf("K%d", num)
  10409. if _, ok := planExec["actualweight"]; ok {
  10410. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10411. f.SetCellValue(sheetName, cell, actualweight)
  10412. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10413. } else {
  10414. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10415. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10416. }
  10417. num += 1
  10418. }
  10419. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10420. for i, header := range headers2 {
  10421. cell := "%" + fmt.Sprintf("c%d", num)
  10422. cell = fmt.Sprintf(cell, 'C'+i)
  10423. f.SetCellValue(sheetName, cell, header)
  10424. f.SetCellStyle(sheetName, cell, cell, styleID)
  10425. maxWidth := len(header)
  10426. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10427. }
  10428. num += 1
  10429. for _, plan2 := range plan2Map[plan["id"]] {
  10430. var currentStyleID int
  10431. if plan2["abnormal"] == "1" {
  10432. currentStyleID = redStyleID
  10433. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10434. } else {
  10435. currentStyleID = styleID
  10436. }
  10437. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10438. sort, _ := strconv.Atoi(plan2["sort"])
  10439. f.SetCellValue(sheetName, cell, sort)
  10440. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10441. cell = fmt.Sprintf("D%d", num)
  10442. f.SetCellValue(sheetName, cell, plan2["fname"])
  10443. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10444. cell = fmt.Sprintf("E%d", num)
  10445. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10446. f.SetCellValue(sheetName, cell, lweight)
  10447. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10448. cell = fmt.Sprintf("F%d", num)
  10449. if _, ok := plan2["actualweightminus"]; ok {
  10450. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10451. f.SetCellValue(sheetName, cell, actualweightminus)
  10452. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10453. } else {
  10454. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10455. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10456. }
  10457. cell = fmt.Sprintf("G%d", num)
  10458. if _, ok := plan2["diff"]; ok {
  10459. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10460. f.SetCellValue(sheetName, cell, diff)
  10461. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10462. } else {
  10463. f.SetCellValue(sheetName, cell, plan2["diff"])
  10464. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10465. }
  10466. cell = fmt.Sprintf("H%d", num)
  10467. if _, ok := plan2["diffRate"]; ok {
  10468. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10469. f.SetCellValue(sheetName, cell, diffRate)
  10470. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10471. } else {
  10472. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10473. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10474. }
  10475. cell = fmt.Sprintf("I%d", num)
  10476. f.SetCellValue(sheetName, cell, plan2["intime"])
  10477. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10478. cell = fmt.Sprintf("J%d", num)
  10479. if _, ok := plan2["lastactualweight"]; ok {
  10480. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10481. f.SetCellValue(sheetName, cell, lastactualweight)
  10482. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10483. } else {
  10484. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10485. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10486. }
  10487. cell = fmt.Sprintf("K%d", num)
  10488. if _, ok := plan2["lastactualweight"]; ok {
  10489. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10490. f.SetCellValue(sheetName, cell, actualweight)
  10491. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10492. } else {
  10493. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10494. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10495. }
  10496. num += 1
  10497. }
  10498. num += 1
  10499. notBorder = append(notBorder, num)
  10500. }
  10501. // for i := 2; i < num; i++ {
  10502. // exist := false
  10503. // for _, n := range notBorder {
  10504. // if i+1 == n {
  10505. // exist = true
  10506. // break
  10507. // }
  10508. // }
  10509. // if !exist {
  10510. // // 为 A-K 列设置边框
  10511. // for col := 'A'; col <= 'K'; col++ {
  10512. // cellName := fmt.Sprintf("%c%d", col, i)
  10513. // style, _ := f.NewStyle(&excelizexuri.Style{
  10514. // // Border: border,
  10515. // Alignment: &excelizexuri.Alignment{
  10516. // Vertical: "center",
  10517. // Horizontal: "center",
  10518. // ShrinkToFit: true,
  10519. // WrapText: true,
  10520. // },
  10521. // })
  10522. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10523. // }
  10524. // }
  10525. // }
  10526. for col := 'A'; col <= 'K'; col++ {
  10527. colName := string(col)
  10528. switch colName {
  10529. case "A", "B": // 牧场名称、TMR列
  10530. f.SetColWidth(sheetName, colName, colName, 10)
  10531. case "C": // 操作编号列
  10532. f.SetColWidth(sheetName, colName, colName, 10)
  10533. case "D", "E": // 计划重量、实际重量列
  10534. f.SetColWidth(sheetName, colName, colName, 12)
  10535. case "F": // 代表成分/投料位置列
  10536. f.SetColWidth(sheetName, colName, colName, 20)
  10537. case "G", "H": // 误差数、准确率列
  10538. f.SetColWidth(sheetName, colName, colName, 12)
  10539. case "I": // 完成时间列
  10540. f.SetColWidth(sheetName, colName, colName, 15)
  10541. case "J", "K": // 起始读数重量、完成读数重量列
  10542. f.SetColWidth(sheetName, colName, colName, 15)
  10543. }
  10544. }
  10545. // 设置响应头
  10546. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10547. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10548. c.Header("Content-Transfer-Encoding", "binary")
  10549. // 写入 Excel 文件到响应
  10550. if err := f.Write(c.Writer); err != nil {
  10551. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10552. return
  10553. }
  10554. }
  10555. func RestartMqtt(c *gin.Context) {
  10556. appG := app.Gin{C: c}
  10557. // 发送 GET 请求到 MQTT 重启接口
  10558. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10559. if err != nil {
  10560. logging.Error("RestartMqtt request failed:", err)
  10561. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10562. return
  10563. }
  10564. defer resp.Body.Close()
  10565. // 读取响应内容f
  10566. body, err := ioutil.ReadAll(resp.Body)
  10567. if err != nil {
  10568. logging.Error("RestartMqtt read response failed:", err)
  10569. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10570. return
  10571. }
  10572. // 检查响应状态码
  10573. if resp.StatusCode != http.StatusOK {
  10574. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10575. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10576. return
  10577. }
  10578. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10579. }
  10580. func FpdBatchEditByWeight(c *gin.Context) {
  10581. appG := app.Gin{C: c}
  10582. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10583. fsions := gofasion.NewFasion(string(dataByte))
  10584. barList := fsions.Get("barList").Array()
  10585. pastureid := fsions.Get("pastureId").ValueStr()
  10586. tx := restful.Engine.NewSession()
  10587. defer tx.Close()
  10588. 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
  10589. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10590. if err != nil {
  10591. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10592. return
  10593. }
  10594. for _, barFsions := range barList {
  10595. dataexcel := make(map[string]interface{}, 0)
  10596. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10597. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10598. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10599. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10600. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10601. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10602. continue
  10603. }
  10604. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10605. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10606. // if err != nil {
  10607. // logs.Error(err)
  10608. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10609. // return
  10610. // }
  10611. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10612. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10613. // if err != nil {
  10614. // logs.Error(err)
  10615. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10616. // return
  10617. // }
  10618. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10619. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10620. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10621. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10622. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10623. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10624. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10625. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10626. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10627. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10628. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10629. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10630. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10631. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10632. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10633. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10634. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10635. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10636. if err != nil {
  10637. logs.Error(err)
  10638. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10639. return
  10640. }
  10641. if !ftexist {
  10642. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10643. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10644. if err != nil {
  10645. logs.Error(err)
  10646. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10647. return
  10648. }
  10649. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10650. if err != nil {
  10651. logs.Error(err)
  10652. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10653. return
  10654. }
  10655. }
  10656. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10657. if err != nil {
  10658. logs.Error(err)
  10659. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10660. return
  10661. }
  10662. if !exist {
  10663. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10664. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10665. if err != nil {
  10666. logs.Error(err)
  10667. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10668. return
  10669. }
  10670. }
  10671. var feedpargs []interface{}
  10672. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10673. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10674. if _, ok := dataexcel["ftname"]; ok {
  10675. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10676. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10677. // upFeedpSql += `,ftweight = ? `
  10678. // feedpargs = append(feedpargs, weight)
  10679. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10680. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10681. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10682. } else {
  10683. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10684. }
  10685. // if _, ok := dataexcel["ptsfname"]; ok {
  10686. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10687. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10688. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10689. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10690. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10691. // } else {
  10692. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10693. // }
  10694. upFeedpSql += " where barname = ? and pastureid = ? "
  10695. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10696. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10697. if err != nil {
  10698. logs.Error(err)
  10699. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10700. return
  10701. }
  10702. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10703. if err != nil {
  10704. logs.Error(err)
  10705. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10706. return
  10707. }
  10708. if !exist1 {
  10709. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10710. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10711. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10712. if err != nil {
  10713. logs.Error(err)
  10714. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10715. return
  10716. }
  10717. }
  10718. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10719. if err != nil {
  10720. logs.Error(err)
  10721. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10722. return
  10723. }
  10724. if !exist2 {
  10725. _, 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) `,
  10726. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10727. if err != nil {
  10728. logs.Error(err)
  10729. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10730. return
  10731. }
  10732. }
  10733. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10734. if err != nil {
  10735. logs.Error(err)
  10736. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10737. return
  10738. }
  10739. if !exist3 {
  10740. _, 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) `,
  10741. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10742. if err != nil {
  10743. logs.Error(err)
  10744. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10745. return
  10746. }
  10747. }
  10748. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10749. if err != nil {
  10750. logs.Error(err)
  10751. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10752. return
  10753. }
  10754. if !exist4 {
  10755. _, 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) `,
  10756. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10757. if err != nil {
  10758. logs.Error(err)
  10759. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10760. return
  10761. }
  10762. }
  10763. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10764. if err != nil {
  10765. logs.Error(err)
  10766. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10767. return
  10768. }
  10769. if !exist5 {
  10770. _, 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) `,
  10771. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10772. if err != nil {
  10773. logs.Error(err)
  10774. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10775. return
  10776. }
  10777. }
  10778. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10779. if err != nil {
  10780. logs.Error(err)
  10781. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10782. return
  10783. }
  10784. if !exist6 {
  10785. _, 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) `,
  10786. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10787. if err != nil {
  10788. logs.Error(err)
  10789. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10790. return
  10791. }
  10792. }
  10793. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10794. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10795. and pastureid = ? and times = ?`
  10796. var fpdargs1 []interface{}
  10797. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10798. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10799. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10800. if err != nil {
  10801. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10802. return
  10803. }
  10804. var fpdargs2 []interface{}
  10805. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10806. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10807. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10808. if err != nil {
  10809. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10810. return
  10811. }
  10812. var fpdargs3 []interface{}
  10813. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10814. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10815. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10816. if err != nil {
  10817. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10818. return
  10819. }
  10820. var fpdargs4 []interface{}
  10821. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10822. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10823. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10824. if err != nil {
  10825. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10826. return
  10827. }
  10828. var fpdargs5 []interface{}
  10829. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10830. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10831. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10832. if err != nil {
  10833. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10834. return
  10835. }
  10836. var fpdargs6 []interface{}
  10837. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10838. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10839. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10840. if err != nil {
  10841. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10842. return
  10843. }
  10844. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10845. 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()
  10846. if err != nil {
  10847. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10848. return
  10849. }
  10850. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10851. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10852. upFpdetailList := make([]*upFpdetail, 0)
  10853. for _, newfpd := range newList {
  10854. for _, oldfpd := range oldFpdList {
  10855. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10856. var oldweight, newweight float64
  10857. if oldfpd["weight"] != nil {
  10858. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10859. }
  10860. if newfpd["weight"] != nil {
  10861. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10862. }
  10863. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10864. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10865. Old: oldweight,
  10866. New: newweight,
  10867. Times: newfpd["times"].(int64),
  10868. Ptid: newfpd["ptid"].(int64),
  10869. Fweight: fweight,
  10870. Id: oldfpd["id"].(int64),
  10871. })
  10872. break
  10873. }
  10874. }
  10875. }
  10876. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10877. }
  10878. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10879. }
  10880. func FtImportExcel(c *gin.Context) {
  10881. appG := app.Gin{C: c}
  10882. inputdata := ""
  10883. c.Request.ParseForm()
  10884. params := c.Request.Form
  10885. file, _, err := c.Request.FormFile("file")
  10886. if err != nil {
  10887. appG.Response(http.StatusOK, e.ERROR, err)
  10888. return
  10889. }
  10890. sqlnamestrs := params.Get("name")
  10891. sheetname := params.Get("sheetname")
  10892. pastureid := params.Get("pastureid")
  10893. //importParams := params.Get("importParams")
  10894. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10895. // 必输项参数 (字符串格式 "field1,field2,field3")
  10896. requiredParams := params.Get("requiredParams")
  10897. // 日期参数
  10898. dateParams := params.Get("dateParams")
  10899. // 数字参数
  10900. numParams := params.Get("numParams")
  10901. //将字符串分割开
  10902. dateParamslist := strings.Split(dateParams, ",")
  10903. requiredParamslist := strings.Split(requiredParams, ",")
  10904. numParamslist := strings.Split(numParams, ",")
  10905. queryData := make([]interface{}, 0)
  10906. sqlslist := strings.Split(sqlnamestrs, ",")
  10907. xlsx1, err := excelize.OpenReader(file)
  10908. if err != nil {
  10909. fmt.Println(err)
  10910. return
  10911. }
  10912. ok := 0
  10913. error := 0
  10914. isdone := true
  10915. rows := xlsx1.GetRows(sheetname)
  10916. // 限制10000条,多余的截取掉
  10917. if len(rows) > 10000 {
  10918. rows = rows[:10000]
  10919. }
  10920. tx := restful.Engine.NewSession()
  10921. ftNameList := make(map[string]interface{})
  10922. var ftNames []interface{}
  10923. for i, row := range rows {
  10924. if i > 0 {
  10925. entry := make(map[string]interface{})
  10926. outentry := make(map[string]interface{})
  10927. for j, colCell := range rows[0] {
  10928. for k, colCell1 := range row {
  10929. if j == k {
  10930. outentry[colCell] = colCell1
  10931. entry[colCell] = colCell1
  10932. }
  10933. }
  10934. }
  10935. inputdata = ""
  10936. a := ""
  10937. fmt.Println(outentry, entry)
  10938. //校验日期格式
  10939. for _, v := range dateParamslist {
  10940. if v == "" {
  10941. continue
  10942. }
  10943. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10944. dtime, err := TransfTime(d.(string))
  10945. if err != nil {
  10946. a = strings.Trim(v, " ")
  10947. break
  10948. }
  10949. outentry[strings.Trim(v, " ")] = dtime
  10950. }
  10951. }
  10952. if a != "" {
  10953. outentry["error_msg"] = a + " 格式错误"
  10954. error++
  10955. queryData = append(queryData, outentry)
  10956. continue
  10957. }
  10958. a = ""
  10959. //校验必填格式
  10960. for _, v := range requiredParamslist {
  10961. if v == "" {
  10962. continue
  10963. }
  10964. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10965. a = strings.Trim(v, " ")
  10966. break
  10967. }
  10968. }
  10969. if a != "" {
  10970. outentry["error_msg"] = a + " 未填或格式错误"
  10971. error++
  10972. queryData = append(queryData, outentry)
  10973. continue
  10974. }
  10975. a = ""
  10976. //校验数字格式
  10977. for _, v := range numParamslist {
  10978. if v == "" {
  10979. continue
  10980. }
  10981. d, ok := outentry[strings.Trim(v, " ")]
  10982. if !ok || d == "" {
  10983. outentry[strings.Trim(v, " ")] = 0
  10984. } else {
  10985. var fl float64
  10986. switch d.(type) {
  10987. case string:
  10988. fl, err = strconv.ParseFloat(d.(string), 64)
  10989. }
  10990. if err != nil || fl < 0 {
  10991. a = strings.Trim(v, " ")
  10992. break
  10993. }
  10994. }
  10995. }
  10996. if a != "" {
  10997. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10998. error++
  10999. queryData = append(queryData, outentry)
  11000. continue
  11001. }
  11002. err := tx.Begin()
  11003. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  11004. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  11005. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  11006. }
  11007. for _, sqlnamestr := range sqlslist {
  11008. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11009. paramslist := strings.Split(paramslists, ",")
  11010. if len(paramslist) > 0 {
  11011. s_params := make([]interface{}, 0)
  11012. for _, value := range paramslist {
  11013. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11014. if tempv, exists := c.Get("jwt_username"); exists {
  11015. s_params = append(s_params, tempv.(string))
  11016. } else {
  11017. s_params = append(s_params, "")
  11018. }
  11019. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11020. s_params = append(s_params, pastureid)
  11021. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11022. ids, err := setting.SnowIds.NextId()
  11023. if err != nil {
  11024. ids = time.Now().UnixNano()
  11025. logging.Info("create SnowIds err", err)
  11026. }
  11027. s_params = append(s_params, ids)
  11028. } else {
  11029. if outentry[strings.Trim(value, " ")] == nil {
  11030. s_params = append(s_params, "")
  11031. } else {
  11032. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11033. }
  11034. }
  11035. }
  11036. outentry["input"] = inputdata
  11037. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11038. if err != nil {
  11039. if tx != nil {
  11040. tx.Rollback()
  11041. }
  11042. if tx != nil {
  11043. tx.Close()
  11044. }
  11045. msg := geterrmsg(err.Error())
  11046. outentry["error_msg"] = msg
  11047. error++
  11048. queryData = append(queryData, outentry)
  11049. isdone = true
  11050. break
  11051. } else {
  11052. if len(returnmsgmap1) > 0 {
  11053. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11054. if tx != nil {
  11055. tx.Rollback()
  11056. }
  11057. if tx != nil {
  11058. tx.Close()
  11059. }
  11060. msg := geterrmsg(va.(string))
  11061. outentry["error_msg"] = msg
  11062. error++
  11063. queryData = append(queryData, outentry)
  11064. isdone = true
  11065. break
  11066. }
  11067. }
  11068. isdone = false
  11069. }
  11070. }
  11071. }
  11072. ftNames = append(ftNames, outentry["配方名称"])
  11073. switch {
  11074. case err != nil:
  11075. if tx != nil {
  11076. tx.Rollback()
  11077. }
  11078. default:
  11079. if tx != nil {
  11080. err = tx.Commit()
  11081. }
  11082. }
  11083. if tx != nil {
  11084. tx.Close()
  11085. }
  11086. }
  11087. if !isdone {
  11088. ok++
  11089. isdone = true
  11090. }
  11091. }
  11092. go ftSync(ftNames, pastureid)
  11093. data := make(map[string]interface{})
  11094. data["result"] = queryData
  11095. data["success"] = ok
  11096. data["err_count"] = error
  11097. appG.Response(http.StatusOK, e.SUCCESS, data)
  11098. }
  11099. func ftSync(ftNameList []interface{}, pastureId string) {
  11100. tx := restful.Engine.NewSession()
  11101. defer tx.Close()
  11102. for _, ftName := range ftNameList {
  11103. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11104. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11105. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11106. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11107. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11108. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11109. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11110. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11111. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11112. FpdBatchEditGrfd(pastureId, values1)
  11113. }
  11114. }
  11115. func CopyFeedtemplet(c *gin.Context) {
  11116. appG := app.Gin{C: c}
  11117. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11118. fsion := gofasion.NewFasion(string(dataByte))
  11119. pastureid := fsion.Get("pastureid").ValueStr()
  11120. newName := fsion.Get("newName").ValueStr()
  11121. id := fsion.Get("id").ValueStr()
  11122. tx := restful.Engine.NewSession()
  11123. defer tx.Close()
  11124. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11125. if err != nil {
  11126. appG.Response(http.StatusOK, e.ERROR, err)
  11127. return
  11128. }
  11129. if count > 0 {
  11130. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11131. return
  11132. }
  11133. type ftCode struct {
  11134. Tcode string `xorm:"tcode"`
  11135. }
  11136. code := new(ftCode)
  11137. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11138. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11139. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11140. if err != nil {
  11141. appG.Response(http.StatusOK, e.ERROR, err)
  11142. return
  11143. }
  11144. if code.Tcode == "" {
  11145. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11146. return
  11147. }
  11148. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11149. remark,enable,sort,volume,autozone)
  11150. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11151. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11152. if err != nil {
  11153. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11154. return
  11155. }
  11156. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11157. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11158. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11159. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11160. from ftdetail where ftid = ? `, code.Tcode, id)
  11161. if err != nil {
  11162. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11163. return
  11164. }
  11165. appG.Response(http.StatusOK, e.SUCCESS, true)
  11166. }
  11167. func Test(c *gin.Context) {
  11168. appG := app.Gin{C: c}
  11169. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11170. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11171. }
  11172. func GetPlanDry(c *gin.Context) {
  11173. appG := app.Gin{C: c}
  11174. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11175. fsion := gofasion.NewFasion(string(dataByte))
  11176. date := fsion.Get("date").ValueStr()
  11177. tx := restful.Engine.NewSession()
  11178. defer tx.Close()
  11179. dataList, err := tx.SQL(`SELECT
  11180. t.feedtempletName,
  11181. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11182. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11183. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11184. t.tmrno,
  11185. t.bname,
  11186. t.barid,
  11187. t.dry,
  11188. t.actualweightminus,
  11189. t.mydate,
  11190. t.pasturename,
  11191. t.endDate,
  11192. t.startDate,
  11193. t.times,
  11194. -- 计算startDate和endDate的中间时间
  11195. ifnull(DATE_FORMAT(
  11196. DATE_ADD(
  11197. t.startDate,
  11198. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11199. ),
  11200. '%Y-%m-%d %H:%i:%s'
  11201. ),'') AS midTime
  11202. FROM (
  11203. SELECT
  11204. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11205. b.bname,
  11206. b.id barid,
  11207. ROUND(IF(IFNULL(d2.actualweightminus,0) < 0, d2.lweight/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) , d2.actualweightminus/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) )*((SELECT IFNULL(AVG(dry),0) FROM downloadedplan dd
  11208. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11209. JOIN feednur fn ON fn.fid = dd1.fid
  11210. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11211. IF(IFNULL(d2.actualweightminus,0) < 0, d2.lweight/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) , d2.actualweightminus/(select sum(actualweightminus) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) ) actualweightminus,
  11212. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11213. p.pasture_name pastureName,
  11214. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11215. DATE_FORMAT(IFNULL(
  11216. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11217. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11218. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11219. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11220. ), '%Y-%m-%d %H:%i:%s') startDate,
  11221. d.times ,
  11222. ( SELECT
  11223. round(SUM(
  11224. IF(ftd.preftid<>0,
  11225. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11226. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11227. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11228. ftd.fweight*f.dry/100)) ,2)
  11229. dryweight
  11230. FROM ftdetaildate ftd
  11231. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11232. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11233. select
  11234. sum(ftd.fweight)
  11235. FROM ftdetaildate ftd
  11236. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11237. ( SELECT
  11238. round(SUM(
  11239. IF(ftd.preftid<>0,
  11240. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11241. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11242. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11243. ftd.fweight*f.uprice)) ,2)
  11244. dryweight
  11245. FROM ftdetaildate ftd
  11246. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11247. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11248. feedtempletPrice,d.templetname feedtempletName
  11249. FROM downloadedplan d
  11250. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11251. JOIN bar b ON b.id = d2.fbarid
  11252. JOIN pasture p ON p.pastureid = d.pastureid
  11253. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11254. AND d2.type = 0
  11255. AND d.havebutton = 1
  11256. ) t
  11257. WHERE 1=1 `, date).QueryString()
  11258. if err != nil {
  11259. logs.Error(err)
  11260. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11261. return
  11262. }
  11263. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11264. }
  11265. func GetBar(c *gin.Context) {
  11266. appG := app.Gin{C: c}
  11267. tx := restful.Engine.NewSession()
  11268. defer tx.Close()
  11269. pastureinfo := new(udPastureInfo)
  11270. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11271. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11272. if err != nil {
  11273. logs.Error(err)
  11274. return
  11275. }
  11276. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11277. if err != nil {
  11278. logs.Error(err)
  11279. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11280. return
  11281. }
  11282. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11283. }
  11284. func GetHomepage(c *gin.Context) {
  11285. appG := app.Gin{C: c}
  11286. tx := restful.Engine.NewSession()
  11287. defer tx.Close()
  11288. dataList, err := tx.SQL(` SELECT
  11289. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11290. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11291. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11292. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11293. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11294. AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) )monRateHL , -- 近30日混料准确率
  11295. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11296. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11297. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11298. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11299. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11300. AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) )monRateSL, -- 进30日撒料准确率
  11301. ifnull((SELECT CONCAT(ROUND(IF(COUNT(de.id)>0,SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio,1,0))/COUNT(de.id),0)*100,2),'%') -- 正确率
  11302. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11303. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11304. (SELECT CONCAT(ROUND(IF(COUNT(de.id)>0,SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio,1,0))/COUNT(de.id),0)*100,2),'%') -- 正确率
  11305. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11306. WHERE dt.pastureid = d.pastureid
  11307. AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')) monRateSLR, -- 近30日正确率
  11308. (SELECT COUNT(*)FROM downloadedplan dt WHERE dt.pastureid= d.pastureid AND dt.mydate = d.mydate and dt.iscompleted=1 and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) )) doneTimes,
  11309. (SELECT COUNT(*)FROM downloadedplan dt WHERE dt.pastureid= d.pastureid AND dt.mydate = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ) planTimes,
  11310. ifnull((SELECT SUM(dc.actualweightminus) FROM downloadplandtl1_exec dc join downloadedplan dt on dt.id = dc.pid WHERE dc.pastureid = 0 AND dc.date = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ),0) doneWeight,
  11311. ifnull((SELECT SUM(dc.lweight ) FROM downloadplandtl1_exec dc join downloadedplan dt on dt.id = dc.pid WHERE dc.pastureid = 0 AND dc.date = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ),0) planWeight,
  11312. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11313. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11314. FROM
  11315. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11316. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid') as pastureid,date_format(now(),'%Y-%m-%d') mydate) d `, setting.DatabaseSetting.Name).QueryString()
  11317. if err != nil {
  11318. logs.Error(err)
  11319. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11320. return
  11321. }
  11322. dataList1, err := tx.SQL(`select
  11323. ifnull(round(sum(if(d1.feedcode = '-1', d1.actualweightminus * (ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.ftid = d1.fid ))* f.uprice,f.uprice * d1.actualweightminus )) / (select sum(ccount) from downloadplandtl2 d2 join bar b on b.id = d2.fbarid join feedp fp on fp.barid = b.id where date = d1.date),2),0) cost , ifnull(round(sum(if(d1.feedcode = '-1', d1.actualweightminus * (ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.ftid = d1.fid ))* f.uprice,f.uprice * d1.actualweightminus )),2),0) totalCost from downloadplandtl1 d1
  11324. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11325. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11326. if err != nil {
  11327. logs.Error(err)
  11328. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11329. return
  11330. }
  11331. for _, data := range dataList {
  11332. for _, data1 := range dataList1 {
  11333. data["totalCost"] = data1["totalCost"]
  11334. data["cost"] = data1["cost"]
  11335. }
  11336. }
  11337. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11338. }
  11339. func GetFeedingManagement(c *gin.Context) {
  11340. appG := app.Gin{C: c}
  11341. typea := c.Query("typea") // 0 栏舍 1 日期
  11342. startDate := c.Query("startdate")
  11343. endDate := c.Query("enddate")
  11344. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11345. // fsion := gofasion.NewFasion(string(dataByte))
  11346. tx := restful.Engine.NewSession()
  11347. defer tx.Close()
  11348. if typea == "0" {
  11349. dataList, err := tx.SQL(`select t.bname typea ,round(t.actualweightminus,2) actualweightminus ,round(t.dryweight,2) dryweight ,round(t.priceweight,2) totalcost ,round(t.priceweight / t.ccount,2) cost,t.ccount from (SELECT
  11350. SUM(
  11351. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11352. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11353. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11354. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11355. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11356. )
  11357. )actualweightminus ,
  11358. SUM(
  11359. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11360. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11361. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11362. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11363. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11364. ) * ifnull(fn.dry,0)
  11365. ) dryweight , SUM(
  11366. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11367. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11368. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11369. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11370. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11371. ) * ifnull(f.uprice,0)
  11372. ) priceweight
  11373. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11374. FROM
  11375. downloadedplan d
  11376. JOIN downloadplandtl2 d2
  11377. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11378. JOIN downloadplandtl1 d1
  11379. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11380. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11381. LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = ftd1.id AND d1.feedcode = '-1' AND ftd.date =d1.date AND ftd.version = ftd1.version
  11382. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11383. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11384. left join feednur fn on fn.fid = f.id
  11385. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11386. if err != nil {
  11387. logs.Error(err)
  11388. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11389. return
  11390. }
  11391. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11392. } else {
  11393. dataList, err := tx.SQL(`select date_format(t.date ,'%Y-%m-%d') typea ,round(t.actualweightminus,2) actualweightminus ,round(t.dryweight,2) dryweight ,round(t.priceweight,2) totalcost ,round(t.priceweight / (select sum(ccount) from feedpdate fp where fp.date = t.date and fp.barid in(select fbarid from downloadplandtl2 where date = t.date and type = 0) ) ,2) cost,(select sum(ccount) from feedpdate fp where fp.date = t.date and fp.barid in(select fbarid from downloadplandtl2 where date = t.date and type = 0) ) ccount from (SELECT
  11394. SUM(
  11395. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11396. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11397. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11398. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11399. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11400. )
  11401. )actualweightminus ,
  11402. SUM(
  11403. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11404. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11405. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11406. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11407. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11408. ) * ifnull(fn.dry,0)
  11409. ) dryweight , SUM(
  11410. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11411. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11412. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11413. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11414. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11415. ) * ifnull(f.uprice,0)
  11416. ) priceweight
  11417. ,(select sum(ccount) from feedpdate fp join downloadplandtl2 dd2 on dd2.fbarid = fp.barid where fp.date = d2.date and dd2.date = d2.date ) ccount,d2.date
  11418. FROM
  11419. downloadedplan d
  11420. JOIN downloadplandtl2 d2
  11421. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11422. JOIN downloadplandtl1 d1
  11423. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11424. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11425. LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = ftd1.id AND d1.feedcode = '-1' AND ftd.date =d1.date AND ftd.version = ftd1.version
  11426. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11427. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11428. left join feednur fn on fn.fid = f.id
  11429. WHERE d.mydate BETWEEN ? AND ?
  11430. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11431. if err != nil {
  11432. logs.Error(err)
  11433. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11434. return
  11435. }
  11436. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11437. }
  11438. }
  11439. func GetFpdetailFname(c *gin.Context) {
  11440. appG := app.Gin{C: c}
  11441. // id := c.Query("id")
  11442. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11443. fsion := gofasion.NewFasion(string(dataByte))
  11444. id := fsion.Get("id").ValueDefaultStr("")
  11445. tx := restful.Engine.NewSession()
  11446. defer tx.Close()
  11447. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11448. err := tx.SQL(` SELECT
  11449. TRIM(ftid)ftid,TRIM(fid)fid,
  11450. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11451. fweight,sort,
  11452. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11453. FROM
  11454. ftdetail
  11455. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11456. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11457. if err != nil {
  11458. logs.Error(err)
  11459. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11460. return
  11461. }
  11462. fpdetailList := make([]*models.Fpdetail, 0)
  11463. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11464. if err != nil {
  11465. logs.Error(err)
  11466. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11467. return
  11468. }
  11469. for _, f := range fpdetailFnameList {
  11470. f.FWeight = 0
  11471. for _, fpd := range fpdetailList {
  11472. value := f.SumFWeight * fpd.Weight
  11473. // 将其四舍五入到小数点后两位
  11474. roundedValue := math.Round(value*100) / 100
  11475. if fpd.Times == 1 {
  11476. f.TimesOne = roundedValue
  11477. } else if fpd.Times == 2 {
  11478. f.TimesTwo = roundedValue
  11479. } else if fpd.Times == 3 {
  11480. f.TimesThree = roundedValue
  11481. } else if fpd.Times == 4 {
  11482. f.TimesFour = roundedValue
  11483. } else if fpd.Times == 5 {
  11484. f.TimesFive = roundedValue
  11485. } else if fpd.Times == 6 {
  11486. f.TimesSix = roundedValue
  11487. }
  11488. f.FWeight += value
  11489. }
  11490. }
  11491. fpdetailFname := new(models.FpdetailFname)
  11492. fpdetailFname.FName = "合计"
  11493. for _, f := range fpdetailFnameList {
  11494. fpdetailFname.TimesOne += f.TimesOne
  11495. fpdetailFname.TimesTwo += f.TimesTwo
  11496. fpdetailFname.TimesThree += f.TimesThree
  11497. fpdetailFname.TimesFour += f.TimesFour
  11498. fpdetailFname.TimesFive += f.TimesFive
  11499. fpdetailFname.TimesSix += f.TimesSix
  11500. fpdetailFname.FWeight += f.FWeight
  11501. f.FWeight = RoundFloat(f.FWeight, 2)
  11502. }
  11503. // 在处理代码中
  11504. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11505. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11506. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11507. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11508. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11509. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11510. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11511. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11512. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11513. }
  11514. func RoundFloat(x float64, prec int) float64 {
  11515. output := math.Pow(10, float64(prec))
  11516. return math.Round(x*output) / output
  11517. }
  11518. func GetLyUdData(c *gin.Context) {
  11519. appG := app.Gin{C: c}
  11520. // id := c.Query("id")
  11521. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11522. fsion := gofasion.NewFasion(string(dataByte))
  11523. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11524. times := fsion.Get("Times").ValueDefaultStr("")
  11525. name := fsion.Get("name").ValueDefaultStr("")
  11526. tx := restful.Engine.NewSession()
  11527. defer tx.Close()
  11528. if name == "dateplanlist" {
  11529. data, err := tx.SQL(`select dl.id as did,if(dl.HaveButton=1,1,0) isDo, dl.id as id,dl.ProjName,dl.tmrtname TNAME, '' DNAME,DATE_FORMAT(dl.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dl.templetName fName, DATE_FORMAT(dl.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dl.Times as Times, dl.Sort ,'是' Status, p.pasturecode kptCattleId from downloadedplan dl
  11530. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11531. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11532. select dd.id as did,if(dd.HaveButton=1,1,0) isDo, dd.id as id,dd.ProjName,dd.tmrtname TNAME, '' DNAME,DATE_FORMAT(dd.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dd.templetName fName, DATE_FORMAT(dd.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dd.Times as Times, dd.Sort ,'是' Status, p.pasturecode kptCattleId
  11533. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11534. JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId inner join downloadedplan dd on dd.pid=dl.pid and dd.mydate=dl.mydate and dd.lpplanType=1 and dl.pastureId=dd.pastureId
  11535. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11536. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11537. fmt.Println(err)
  11538. appG.Response(http.StatusOK, e.SUCCESS, data)
  11539. return
  11540. } else if name == "getAddFeed" {
  11541. data, _ := tx.SQL(`SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId ) LWEIGHT,
  11542. round(d1.lweight,2) expWeight,round(if(d1.actualweightminus>0,d1.actualweightminus,0),2) actualWeight,'' DNAME,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11543. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11544. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11545. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11546. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11547. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11548. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11549. UNION ALL SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId and type = 0) LWEIGHT,
  11550. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11551. round((if(d1.ActualWeightMinus>0,d1.ActualWeightMinus,0)) * (ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and pastureId = d.pastureId and ftid = ftdd.ftid )),2) actualWeight,
  11552. '' DNAME ,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11553. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11554. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11555. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11556. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11557. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11558. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11559. WHERE DATE_FORMAT( dd.Mydate ,'%Y-%m-%d' ) = ? AND dd.Times = ? and d1.type = 0 and d1.feedcode = -1 `, myDate, times, myDate, times).Query().List()
  11560. appG.Response(http.StatusOK, e.SUCCESS, data)
  11561. return
  11562. } else if name == "getDeleteFeed" {
  11563. data, _ := tx.SQL(`SELECT if(d.HaveButton=1,1,0) isDo,date_format(d.mydate,'%Y-%m-%d') as dropDate,d.SORT as tmrNo,d.Times as Times, d2.Fname as penName,d2.cowcount as cowCount,d.tmrtname TNAME, d2.SORT as SORT, d2.LWEIGHT as expWeight,if(d2.ActualWeightMinus>0,d2.ActualWeightMinus,0) as actualWeight,
  11564. date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s') as startTime, date_format(d2.InTime,'%Y-%m-%d %H:%i:%s') as endTime,'' as DNAME ,
  11565. (select ProjName from downloadedplan dd where dd.pid=d.pid and dd.mydate=d.mydate and dd.lpplanType in (0,1) AND d.pastureId = dd.pastureId) ProjName
  11566. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11567. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11568. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11569. appG.Response(http.StatusOK, e.SUCCESS, data)
  11570. return
  11571. }
  11572. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11573. }