ops.go 460 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643
  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/gm"
  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. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  678. if err != nil {
  679. appG.Response(http.StatusOK, e.ERROR, err.Error())
  680. } else {
  681. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  682. }
  683. }
  684. // GetUpkeepPlan 保养计划
  685. func GetUpkeepPlan(c *gin.Context) {
  686. appG := app.Gin{C: c}
  687. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  688. fsion := gofasion.NewFasion(string(dataByte))
  689. sqlnamestr := fsion.Get("name").ValueStr()
  690. offset := fsion.Get("offset").ValueDefaultInt(0)
  691. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  692. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  693. month := fsion.Get("month").ValueDefaultStr("map")
  694. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  695. tx := restful.Engine.NewSession()
  696. err := tx.Begin()
  697. defer func() {
  698. switch {
  699. case err != nil:
  700. if tx != nil {
  701. tx.Rollback()
  702. }
  703. default:
  704. if tx != nil {
  705. err = tx.Commit()
  706. }
  707. }
  708. if tx != nil {
  709. tx.Close()
  710. }
  711. }()
  712. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  713. if sql != "" {
  714. s_params := make([]interface{}, 0)
  715. if fsion.HasKey("parammaps") {
  716. parammaps := fsion.Get("parammaps")
  717. paramslist := strings.Split(p, ",")
  718. if len(paramslist) > 0 && p != "" {
  719. for _, value := range paramslist {
  720. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  721. if tempv, exists := c.Get("jwt_username"); exists {
  722. s_params = append(s_params, tempv.(string))
  723. } else {
  724. s_params = append(s_params, "")
  725. }
  726. } else {
  727. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  728. }
  729. }
  730. }
  731. } else if fsion.HasKey("params") {
  732. params := fsion.Get("params").Array()
  733. for _, v_params := range params {
  734. s_params = append(s_params, v_params.ValueStr())
  735. }
  736. }
  737. if returntype == "xlsx" {
  738. var xlsxfile *xlsx.File
  739. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  740. //c.File("c:/dd.xlsx")
  741. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  742. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  743. c.Header("Content-Transfer-Encoding", "binary")
  744. _ = xlsxfile.Write(c.Writer)
  745. } else {
  746. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  747. if err != nil {
  748. appG.Response(http.StatusOK, e.ERROR, err.Error())
  749. } else {
  750. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  751. if v, ok := value["id"]; ok {
  752. //month = "2020-03"
  753. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  754. if seviceplans != nil {
  755. for _, va := range seviceplans { //根据保养计划获取保养单
  756. //day,_ :=strconv.Atoi(va["day"])
  757. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  758. //buk := make(map[string]map[string]string)
  759. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  760. jstr := ""
  761. if bu["plantime"][8:9] == "0" {
  762. jstr = "m" + bu["plantime"][9:]
  763. } else {
  764. jstr = "m" + bu["plantime"][8:]
  765. }
  766. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  767. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  768. } else {
  769. if bu["flowCompeleted"] >= "2" {
  770. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  771. } else {
  772. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  773. }
  774. }
  775. }
  776. }
  777. }
  778. }
  779. }
  780. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  781. }
  782. }
  783. } else {
  784. appG.Response(http.StatusOK, e.SUCCESS, nil)
  785. }
  786. }
  787. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  788. // todo 优化性能 children统一查询
  789. // @Tags PostDataByNameForm
  790. // @Accept json
  791. // @Produce json
  792. // @Param sqlname query string true "sqlname"
  793. // @Param offset query int true "offset"
  794. // @Param pagecount query int true "pagecount"
  795. // @Param returntype query string true "returntype"
  796. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  797. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  798. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  799. func GetArrList(c *gin.Context) {
  800. appG := app.Gin{C: c}
  801. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  802. fsion := gofasion.NewFasion(string(dataByte))
  803. sqlnamestr := fsion.Get("name").ValueStr()
  804. sqlnamestr1 := fsion.Get("name1").ValueStr()
  805. offset := fsion.Get("offset").ValueDefaultInt(0)
  806. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  807. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  808. month := fsion.Get("month").ValueDefaultStr("map")
  809. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  810. tx := restful.Engine.NewSession()
  811. err := tx.Begin()
  812. defer func() {
  813. switch {
  814. case err != nil:
  815. if tx != nil {
  816. tx.Rollback()
  817. }
  818. default:
  819. if tx != nil {
  820. err = tx.Commit()
  821. }
  822. }
  823. if tx != nil {
  824. tx.Close()
  825. }
  826. }()
  827. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  828. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  829. if sql != "" {
  830. s_params := make([]interface{}, 0)
  831. if fsion.HasKey("parammaps") {
  832. parammaps := fsion.Get("parammaps")
  833. paramslist := strings.Split(p, ",")
  834. if len(paramslist) > 0 && p != "" {
  835. for _, value := range paramslist {
  836. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  837. if tempv, exists := c.Get("jwt_username"); exists {
  838. s_params = append(s_params, tempv.(string))
  839. } else {
  840. s_params = append(s_params, "")
  841. }
  842. } else {
  843. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  844. }
  845. }
  846. }
  847. }
  848. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  849. if err != nil {
  850. appG.Response(http.StatusOK, e.ERROR, err.Error())
  851. } else {
  852. paramslist1 := strings.Split(p1, ",")
  853. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  854. s_params1 := make([]interface{}, 0)
  855. if len(paramslist1) > 0 && p1 != "" {
  856. for _, v := range paramslist1 {
  857. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  858. }
  859. }
  860. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  861. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  862. }
  863. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  864. }
  865. } else {
  866. appG.Response(http.StatusOK, e.SUCCESS, nil)
  867. }
  868. }
  869. func GetAccount(c *gin.Context) {
  870. appG := app.Gin{C: c}
  871. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  872. fsion := gofasion.NewFasion(string(dataByte))
  873. sqlnamestr := fsion.Get("name").ValueStr()
  874. offset := fsion.Get("offset").ValueDefaultInt(0)
  875. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  876. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  877. tx := restful.Engine.NewSession()
  878. err := tx.Begin()
  879. defer func() {
  880. switch {
  881. case err != nil:
  882. logging.Error("tx.Begin 事务启动失败__error:", err)
  883. if tx != nil {
  884. tx.Rollback()
  885. }
  886. default:
  887. if tx != nil {
  888. err = tx.Commit()
  889. }
  890. }
  891. if tx != nil {
  892. tx.Close()
  893. }
  894. }()
  895. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  896. if sql != "" {
  897. s_params := make([]interface{}, 0)
  898. if fsion.HasKey("parammaps") {
  899. parammaps := fsion.Get("parammaps")
  900. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  901. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  902. }
  903. paramslist := strings.Split(p, ",")
  904. if len(paramslist) > 0 && p != "" {
  905. for _, value := range paramslist {
  906. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  907. if tempv, exists := c.Get("jwt_username"); exists {
  908. s_params = append(s_params, tempv.(string))
  909. } else {
  910. s_params = append(s_params, "")
  911. }
  912. } else {
  913. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  914. }
  915. }
  916. }
  917. } else if fsion.HasKey("params") {
  918. params := fsion.Get("params").Array()
  919. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  920. for _, v_params := range params {
  921. s_params = append(s_params, v_params.ValueStr())
  922. }
  923. }
  924. if returntype == "xlsx" {
  925. var xlsxfile *xlsx.File
  926. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  927. //c.File("c:/dd.xlsx")
  928. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  929. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  930. c.Header("Content-Transfer-Encoding", "binary")
  931. _ = xlsxfile.Write(c.Writer)
  932. } else {
  933. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  934. if err != nil {
  935. logging.Error("GetDataByName err: ", err)
  936. msg := geterrmsg(err.Error())
  937. appG.Response(http.StatusOK, e.ERROR, msg)
  938. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  939. } else {
  940. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  941. }
  942. }
  943. } else {
  944. appG.Response(http.StatusOK, e.SUCCESS, nil)
  945. }
  946. }
  947. // PostDataByName 根据APISQL表中SQL执行得到数据集
  948. // @Accept json
  949. // @Produce json
  950. // @Param sqlname query string true "sqlname"
  951. // @Param offset query int true "offset"
  952. // @Param pagecount query int true "pagecount"
  953. // @Param returntype query string true "returntype"
  954. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  955. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  956. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  957. // @Router /data/PostDataByName [POST]
  958. func PostDataByName(c *gin.Context) {
  959. appG := app.Gin{C: c}
  960. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  961. fsion := gofasion.NewFasion(string(dataByte))
  962. var err error
  963. queryData, err := module.PostDataByName(c, fsion)
  964. if err != nil {
  965. appG.Response(http.StatusOK, e.ERROR, err.Error())
  966. return
  967. }
  968. var (
  969. keyWord string
  970. )
  971. switch fsion.Get("name").ValueStr() {
  972. case "insertFeedclass":
  973. keyWord = "feed"
  974. err = module.GroupCategorySync(keyWord, fsion)
  975. case "deleteFeedclass":
  976. keyWord = "feed_delete"
  977. err = module.GroupCategoryDelete(keyWord, fsion)
  978. case "insertCowclass":
  979. keyWord = "cow"
  980. err = module.GroupCategorySync(keyWord, fsion)
  981. case "deleteCowclass":
  982. keyWord = "cow_delete"
  983. err = module.GroupCategoryDelete(keyWord, fsion)
  984. // case "updateFT":
  985. // FtdetailSurplus(fsion)
  986. // case "updateFeed":
  987. // FeedSurplus(fsion)
  988. default:
  989. }
  990. if err != nil {
  991. logging.Error(keyWord, err)
  992. }
  993. if queryData != nil {
  994. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  995. return
  996. }
  997. appG.Response(http.StatusOK, e.SUCCESS, nil)
  998. }
  999. //人脸识别/格润富德接口
  1000. func GetRJSBData(c *gin.Context) {
  1001. appG := app.Gin{C: c}
  1002. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1003. fsion := gofasion.NewFasion(string(dataByte))
  1004. sqlnamestr := fsion.Get("name").ValueStr()
  1005. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1006. offset := fsion.Get("offset").ValueDefaultInt(0)
  1007. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1008. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1009. month := fsion.Get("month").ValueDefaultStr("map")
  1010. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1011. pagecount = 1
  1012. tx := restful.Engine.NewSession()
  1013. err := tx.Begin()
  1014. defer func() {
  1015. switch {
  1016. case err != nil:
  1017. if tx != nil {
  1018. tx.Rollback()
  1019. }
  1020. default:
  1021. if tx != nil {
  1022. err = tx.Commit()
  1023. }
  1024. }
  1025. if tx != nil {
  1026. tx.Close()
  1027. }
  1028. }()
  1029. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1030. _, 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 )
  1031. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1032. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1033. and lpplantype in(0,1)) `).Execute()
  1034. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1035. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1036. if sql != "" {
  1037. s_params := make([]interface{}, 0)
  1038. if fsion.HasKey("parammaps") {
  1039. parammaps := fsion.Get("parammaps")
  1040. paramslist := strings.Split(p, ",")
  1041. if len(paramslist) > 0 && p != "" {
  1042. for _, value := range paramslist {
  1043. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1044. if tempv, exists := c.Get("jwt_username"); exists {
  1045. s_params = append(s_params, tempv.(string))
  1046. } else {
  1047. s_params = append(s_params, "")
  1048. }
  1049. } else {
  1050. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1051. }
  1052. }
  1053. }
  1054. }
  1055. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1056. if err != nil {
  1057. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1058. } else {
  1059. paramslist1 := strings.Split(p1, ",")
  1060. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1061. s_params1 := make([]interface{}, 0)
  1062. if len(paramslist1) > 0 && p1 != "" {
  1063. for _, v := range paramslist1 {
  1064. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1065. }
  1066. }
  1067. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1068. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1069. }
  1070. var wg sync.WaitGroup
  1071. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1072. wg.Add(1)
  1073. go func(value map[string]interface{}) {
  1074. defer wg.Done()
  1075. // ,havebutton = 1
  1076. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1077. }(value)
  1078. }
  1079. wg.Wait()
  1080. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1081. }
  1082. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1083. } else {
  1084. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1085. }
  1086. }
  1087. func PostRJSBData(c *gin.Context) {
  1088. appG := app.Gin{C: c}
  1089. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1090. fsion := gofasion.NewFasion(string(dataByte))
  1091. logging.Info("PostRJSBData err: ", string(dataByte))
  1092. s_params := make([]interface{}, 0)
  1093. tx := restful.Engine.NewSession()
  1094. err := tx.Begin()
  1095. defer func() {
  1096. switch {
  1097. case err != nil:
  1098. if tx != nil {
  1099. tx.Rollback()
  1100. }
  1101. default:
  1102. if tx != nil {
  1103. err = tx.Commit()
  1104. }
  1105. }
  1106. if tx != nil {
  1107. tx.Close()
  1108. }
  1109. }()
  1110. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1111. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1112. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1113. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1114. if !fsion.HasKey("parammaps") {
  1115. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1116. return
  1117. }
  1118. parammaps := fsion.Get("parammaps")
  1119. paramslist := strings.Split(p, ",")
  1120. if len(paramslist) > 0 && p != "" {
  1121. for _, value := range paramslist {
  1122. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1123. }
  1124. }
  1125. projuctid := parammaps.Get("projuctid").ValueStr()
  1126. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1127. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1128. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1129. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1130. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1131. if err != nil {
  1132. logging.Error("PostRJSBData-0 err: ", err)
  1133. msg := geterrmsg(err.Error())
  1134. // appG.Response(http.StatusOK, e.ERROR, msg)
  1135. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1136. return
  1137. }
  1138. _, err = tx.SQL(sql, s_params...).Execute()
  1139. if err != nil {
  1140. logging.Error("PostRJSBData err: ", err)
  1141. msg := geterrmsg(err.Error())
  1142. // appG.Response(http.StatusOK, e.ERROR, msg)
  1143. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1144. return
  1145. }
  1146. s_params = make([]interface{}, 0)
  1147. paramslist = strings.Split(p1, ",")
  1148. if len(paramslist) > 0 && p1 != "" {
  1149. for _, value := range paramslist {
  1150. // if value == "ID" {
  1151. // id := parammaps.Get("ID").ValueStr()
  1152. // pastureid := parammaps.Get("pastureid").ValueStr()
  1153. // 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
  1154. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1155. // if err != nil {
  1156. // logging.Error("PostRJSBData err: ", err)
  1157. // msg := geterrmsg(err.Error())
  1158. // appG.Response(http.StatusOK, e.ERROR, msg)
  1159. // return
  1160. // }
  1161. // for _, item := range datalist {
  1162. // id = item["id"]
  1163. // }
  1164. // s_params = append(s_params, id)
  1165. // } else {
  1166. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1167. // }
  1168. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1169. }
  1170. }
  1171. _, err = tx.SQL(sql1, s_params...).Execute()
  1172. if err != nil {
  1173. logging.Error("PostRJSBData1 err: ", err)
  1174. msg := geterrmsg(err.Error())
  1175. appG.Response(http.StatusOK, e.ERROR, msg)
  1176. return
  1177. }
  1178. s_params = make([]interface{}, 0)
  1179. paramslist = strings.Split(p2, ",")
  1180. if len(paramslist) > 0 && p2 != "" {
  1181. for _, value := range paramslist {
  1182. if value == "ID" {
  1183. id := parammaps.Get("ID").ValueStr()
  1184. pastureid := parammaps.Get("pastureid").ValueStr()
  1185. 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
  1186. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1187. if err != nil {
  1188. logging.Error("PostRJSBData err: ", err)
  1189. msg := geterrmsg(err.Error())
  1190. appG.Response(http.StatusOK, e.ERROR, msg)
  1191. return
  1192. }
  1193. for _, item := range datalist {
  1194. id = item["id"]
  1195. }
  1196. s_params = append(s_params, id)
  1197. } else {
  1198. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1199. }
  1200. }
  1201. }
  1202. _, err = tx.SQL(sql2, s_params...).Execute()
  1203. if err != nil {
  1204. logging.Error("PostRJSBData2 err: ", err)
  1205. msg := geterrmsg(err.Error())
  1206. appG.Response(http.StatusOK, e.ERROR, msg)
  1207. return
  1208. }
  1209. s_params = make([]interface{}, 0)
  1210. paramslist = strings.Split(p3, ",")
  1211. if len(paramslist) > 0 && p3 != "" {
  1212. for _, value := range paramslist {
  1213. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1214. }
  1215. }
  1216. _, err = tx.SQL(sql3, s_params...).Execute()
  1217. if err != nil {
  1218. logging.Error("PostRJSBData3 err: ", err)
  1219. msg := geterrmsg(err.Error())
  1220. appG.Response(http.StatusOK, e.ERROR, msg)
  1221. return
  1222. }
  1223. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1224. }
  1225. func PostRJSBDatas(c *gin.Context) {
  1226. appG := app.Gin{C: c}
  1227. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1228. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1229. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1230. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1231. tx := restful.Engine.NewSession()
  1232. err := tx.Begin()
  1233. defer func() {
  1234. switch {
  1235. case err != nil:
  1236. if tx != nil {
  1237. tx.Rollback()
  1238. }
  1239. default:
  1240. if tx != nil {
  1241. err = tx.Commit()
  1242. }
  1243. }
  1244. if tx != nil {
  1245. tx.Close()
  1246. }
  1247. }()
  1248. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1249. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1250. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1251. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1252. for _, fsion := range fsions {
  1253. if !fsion.HasKey("parammaps") {
  1254. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1255. return
  1256. }
  1257. parammaps := fsion.Get("parammaps")
  1258. ID := parammaps.Get("ID").ValueStr()
  1259. if ID == "" {
  1260. continue
  1261. }
  1262. s_params := make([]interface{}, 0)
  1263. paramslist := strings.Split(p, ",")
  1264. if len(paramslist) > 0 && p != "" {
  1265. for _, value := range paramslist {
  1266. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1267. }
  1268. }
  1269. _, err := tx.SQL(sql, s_params...).Execute()
  1270. if err != nil {
  1271. logging.Error("PostRJSBData err: ", err)
  1272. msg := geterrmsg(err.Error())
  1273. // appG.Response(http.StatusOK, e.ERROR, msg)
  1274. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1275. return
  1276. }
  1277. s_params = make([]interface{}, 0)
  1278. paramslist = strings.Split(p1, ",")
  1279. if len(paramslist) > 0 && p1 != "" {
  1280. for _, value := range paramslist {
  1281. // if value == "ID" {
  1282. // id := parammaps.Get("ID").ValueStr()
  1283. // pastureid := parammaps.Get("pastureid").ValueStr()
  1284. // 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
  1285. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1286. // if err != nil {
  1287. // logging.Error("PostRJSBData err: ", err)
  1288. // msg := geterrmsg(err.Error())
  1289. // appG.Response(http.StatusOK, e.ERROR, msg)
  1290. // return
  1291. // }
  1292. // for _, item := range datalist {
  1293. // id = item["id"]
  1294. // }
  1295. // s_params = append(s_params, id)
  1296. // } else {
  1297. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1298. // }
  1299. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1300. }
  1301. }
  1302. _, err = tx.SQL(sql1, s_params...).Execute()
  1303. if err != nil {
  1304. logging.Error("PostRJSBData1 err: ", err)
  1305. msg := geterrmsg(err.Error())
  1306. appG.Response(http.StatusOK, e.ERROR, msg)
  1307. return
  1308. }
  1309. s_params = make([]interface{}, 0)
  1310. paramslist = strings.Split(p2, ",")
  1311. if len(paramslist) > 0 && p2 != "" {
  1312. for _, value := range paramslist {
  1313. if value == "ID" {
  1314. id := parammaps.Get("ID").ValueStr()
  1315. pastureid := parammaps.Get("pastureid").ValueStr()
  1316. 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
  1317. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1318. if err != nil {
  1319. logging.Error("PostRJSBData err: ", err)
  1320. msg := geterrmsg(err.Error())
  1321. appG.Response(http.StatusOK, e.ERROR, msg)
  1322. return
  1323. }
  1324. for _, item := range datalist {
  1325. id = item["id"]
  1326. }
  1327. s_params = append(s_params, id)
  1328. } else {
  1329. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1330. }
  1331. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1332. }
  1333. }
  1334. _, err = tx.SQL(sql2, s_params...).Execute()
  1335. if err != nil {
  1336. logging.Error("PostRJSBData2 err: ", err)
  1337. msg := geterrmsg(err.Error())
  1338. appG.Response(http.StatusOK, e.ERROR, msg)
  1339. return
  1340. }
  1341. s_params = make([]interface{}, 0)
  1342. paramslist = strings.Split(p3, ",")
  1343. if len(paramslist) > 0 && p3 != "" {
  1344. for _, value := range paramslist {
  1345. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1346. }
  1347. }
  1348. _, err = tx.SQL(sql3, s_params...).Execute()
  1349. if err != nil {
  1350. logging.Error("PostRJSBData3 err: ", err)
  1351. msg := geterrmsg(err.Error())
  1352. appG.Response(http.StatusOK, e.ERROR, msg)
  1353. return
  1354. }
  1355. // ALTER TABLE `tmr`
  1356. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1357. projuctid := parammaps.Get("projuctid").ValueStr()
  1358. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1359. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1360. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1361. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1362. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1363. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1364. if err != nil {
  1365. logging.Error("PostRJSBData-0 err: ", err)
  1366. msg := geterrmsg(err.Error())
  1367. // appG.Response(http.StatusOK, e.ERROR, msg)
  1368. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1369. return
  1370. }
  1371. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1372. if count == 0 {
  1373. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1374. }
  1375. }
  1376. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1377. }
  1378. // @Summary 根据APISQL表中SQL执行得到数据集
  1379. // @Tags ExecDataByConfig
  1380. // @Accept json
  1381. // @Produce json
  1382. // @Param sqlname query string true "sqlname"
  1383. // @Param offset query int true "offset"
  1384. // @Param pagecount query int true "pagecount"
  1385. // @Param returntype query string true "returntype"
  1386. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1387. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1388. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1389. // @Router /data/PostDataByName [POST]
  1390. func ExecDataByConfig(c *gin.Context) {
  1391. appG := app.Gin{C: c}
  1392. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1393. tempval_ := make(map[string]interface{})
  1394. tempCommon := make(map[string]interface{})
  1395. tempval := make([]map[string]interface{}, 0)
  1396. err := json.Unmarshal(dataByte, &tempval_)
  1397. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1398. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1399. if err != nil {
  1400. } else {
  1401. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1402. tempCommon = v
  1403. }
  1404. if v, ok := tempval_["data"].([]interface{}); ok {
  1405. for _, Tvalue := range v {
  1406. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1407. tempval = append(tempval, v1)
  1408. }
  1409. }
  1410. }
  1411. tx := restful.Engine.NewSession()
  1412. err := tx.Begin()
  1413. if err != nil {
  1414. logging.Error("tx.Begin 事务启动失败__error:", err)
  1415. }
  1416. defer func() {
  1417. switch {
  1418. case err != nil:
  1419. if tx != nil {
  1420. tx.Rollback()
  1421. }
  1422. default:
  1423. if tx != nil {
  1424. err = tx.Commit()
  1425. }
  1426. }
  1427. if tx != nil {
  1428. tx.Close()
  1429. }
  1430. }()
  1431. if err == nil {
  1432. if tempv, exists := c.Get("jwt_username"); exists {
  1433. tempCommon["jwt_username"] = tempv.(string)
  1434. }
  1435. for _, paramvalue := range tempval {
  1436. fmt.Println(paramvalue["name"])
  1437. if paramvalue["name"].(string) == "updateBigFP" {
  1438. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1439. if err != nil {
  1440. msg := geterrmsg(err.Error())
  1441. appG.Response(http.StatusOK, e.ERROR, msg)
  1442. return
  1443. }
  1444. }
  1445. }
  1446. for _, paramvalue := range tempval {
  1447. if _, ok := paramvalue["resultname"]; !ok {
  1448. paramvalue["resultname"] = paramvalue["name"]
  1449. }
  1450. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1451. if err != nil {
  1452. logging.Error("ExecDataParam error:", err)
  1453. break
  1454. }
  1455. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1456. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1457. // }
  1458. }
  1459. if err == nil {
  1460. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1461. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1462. } else {
  1463. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1464. }
  1465. } else {
  1466. msg := geterrmsg(err.Error())
  1467. appG.Response(http.StatusOK, e.ERROR, msg)
  1468. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1469. }
  1470. }
  1471. }
  1472. if err != nil {
  1473. msg := geterrmsg(err.Error())
  1474. appG.Response(http.StatusOK, e.ERROR, msg)
  1475. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1476. }
  1477. }
  1478. func interfacetostring(val interface{}) string {
  1479. switch val.(type) {
  1480. case string:
  1481. ss := val.(string)
  1482. return ss
  1483. break
  1484. case int:
  1485. ss := val.(int)
  1486. return strconv.Itoa(ss)
  1487. break
  1488. case int64:
  1489. ss := val.(int64)
  1490. return strconv.FormatInt(ss, 10)
  1491. break
  1492. case float64:
  1493. ss := val.(float64)
  1494. return strconv.FormatFloat(ss, 'E', -1, 32)
  1495. break
  1496. }
  1497. return ""
  1498. }
  1499. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1500. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1501. tempstrb := strings.IndexAny(valuestring, "@")
  1502. tempstre := strings.IndexAny(valuestring, ".")
  1503. if tempstrb > -1 && tempstre > -1 {
  1504. for _, ParamMapList := range ParamMap {
  1505. if v, ok := ParamMapList["resultname"]; ok {
  1506. if v == valuestring[tempstrb+1:tempstre] {
  1507. if v1, ok := ParamMapList["resultmaps"]; ok {
  1508. if newA, ok := v1.([]map[string]interface{}); ok {
  1509. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1510. } else if newA, ok := v1.(map[string]interface{}); ok {
  1511. return interfacetostring(newA[valuestring[tempstre+1:]])
  1512. }
  1513. }
  1514. }
  1515. }
  1516. }
  1517. } else {
  1518. return valuestring
  1519. }
  1520. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1521. return fmt.Sprintf("%f", valuestring)
  1522. }
  1523. return ""
  1524. }
  1525. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1526. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1527. tempstrb := strings.IndexAny(valuestring, "@")
  1528. tempstre := strings.IndexAny(valuestring, ".")
  1529. if tempstrb > -1 && tempstre > -1 {
  1530. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1531. if s, ok := v.(string); ok {
  1532. return s
  1533. } else if s, ok := v.(float64); ok {
  1534. return strconv.FormatFloat(s, 'f', -1, 64)
  1535. // return strconv.FormatInt(int64(s), 10)
  1536. }
  1537. }
  1538. }
  1539. }
  1540. return ""
  1541. }
  1542. 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) {
  1543. sqlname := fasion["name"].(string)
  1544. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1545. if v, ok := fasion["type"]; ok {
  1546. sqltype = v.(string)
  1547. }
  1548. sql := ""
  1549. p := ""
  1550. s_params := make([]interface{}, 0)
  1551. if sqltype != "" {
  1552. sql, p = restful.GetSqlByName(sqlname, tx)
  1553. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1554. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1555. paramslist := strings.Split(p, ",")
  1556. if len(paramslist) > 0 && p != "" {
  1557. for _, value := range paramslist {
  1558. ss := ""
  1559. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1560. ids, err := setting.SnowIds.NextId()
  1561. if err != nil {
  1562. ids = time.Now().UnixNano()
  1563. logging.Info("create SnowIds err", err)
  1564. }
  1565. s_params = append(s_params, ids)
  1566. } else {
  1567. if ss == "" && CommonParamMap != nil {
  1568. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1569. ss = valuestring
  1570. tempstrb := strings.IndexAny(valuestring, "@")
  1571. tempstre := strings.IndexAny(valuestring, ".")
  1572. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1573. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1574. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1575. }
  1576. } else {
  1577. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1578. ss = ""
  1579. }
  1580. }
  1581. }
  1582. }
  1583. if ss == "" && ParentParamMap != nil {
  1584. ss = getParamValue_(v, value, ParentParamMap)
  1585. }
  1586. if ss == "" && sameParamMap != nil {
  1587. ss = getParamValue(v, value, sameParamMap)
  1588. }
  1589. if ss == "" && ParamMap != nil {
  1590. ss = getParamValue(v, value, ParamMap)
  1591. }
  1592. s_params = append(s_params, ss)
  1593. }
  1594. }
  1595. }
  1596. }
  1597. }
  1598. if sql == "" {
  1599. sqltype = ""
  1600. }
  1601. if sqltype == "s1" {
  1602. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1603. if v, ok := tempValParam.(map[string]interface{}); ok {
  1604. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1605. }
  1606. if err != nil {
  1607. return nil, err
  1608. }
  1609. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1610. if err != nil {
  1611. return nil, err
  1612. }
  1613. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1614. } else if sqltype == "sm" {
  1615. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1616. if v, ok := tempValParam.(map[string]interface{}); ok {
  1617. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1618. } else {
  1619. }
  1620. if err != nil {
  1621. return nil, err
  1622. }
  1623. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1624. if err != nil {
  1625. return nil, err
  1626. }
  1627. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1628. } else if sqltype == "v" {
  1629. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1630. if v, ok := tempValParam.(map[string]interface{}); ok {
  1631. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1632. } else {
  1633. }
  1634. if err != nil {
  1635. return nil, err
  1636. }
  1637. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1638. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1639. }
  1640. } else if sqltype == "e" {
  1641. tempVal_arrary := make([]map[string]interface{}, 0)
  1642. tempVal_map := make(map[string]interface{})
  1643. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1644. if err == nil {
  1645. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1646. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1647. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1648. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1649. return tempVal_arrary, err
  1650. }
  1651. return nil, err
  1652. } else {
  1653. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1654. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1655. if err != nil {
  1656. return nil, err
  1657. }
  1658. return nil, err
  1659. }
  1660. }
  1661. return nil, nil
  1662. }
  1663. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1664. var err error
  1665. subarray, ok := fasion["children"]
  1666. if ok {
  1667. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1668. tempVal_arrary := make([]map[string]interface{}, 0)
  1669. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1670. tempVal_ := make(map[string]interface{})
  1671. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1672. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1673. } else {
  1674. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1675. }
  1676. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1677. if err != nil {
  1678. return err
  1679. }
  1680. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1681. }
  1682. v.(map[string]interface{})["children"] = tempVal_arrary
  1683. }
  1684. }
  1685. return nil
  1686. }
  1687. // @Summary 删除图片
  1688. // @Tags RemovePicByName
  1689. // @Accept json
  1690. // @Produce json
  1691. // @Param sqlname query string true "sqlname"
  1692. // @Param offset query int true "offset"
  1693. // @Param pagecount query int true "pagecount"
  1694. // @Param returntype query string true "returntype"
  1695. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1696. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1697. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1698. // @Router /data/PostDataByName [POST]
  1699. func RemovePicByName(c *gin.Context) {
  1700. logging.Info("RemovePicByName ", c.Keys)
  1701. appG := app.Gin{C: c}
  1702. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1703. fsion := gofasion.NewFasion(string(dataByte))
  1704. sqlnamestr := fsion.Get("name").ValueStr()
  1705. picname := fsion.Get("picname").ValueStr()
  1706. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1707. params := fsion.Get("params").Array()
  1708. s_params := make([]interface{}, 0)
  1709. for _, v_params := range params {
  1710. s_params = append(s_params, v_params.ValueStr())
  1711. }
  1712. if sql != "" {
  1713. queryData, err := execDataBySql(sql, s_params)
  1714. if picname != "" {
  1715. // Destination
  1716. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1717. err := os.Remove(distPath) //删除文件test.txt
  1718. if err != nil {
  1719. //如果删除失败则输出 file remove Error!
  1720. fmt.Println("file remove Error!")
  1721. //输出错误详细信息
  1722. fmt.Printf("%s", err)
  1723. } else {
  1724. //如果删除成功则输出 file remove OK!
  1725. fmt.Print("file remove OK!")
  1726. }
  1727. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1728. err = os.Remove(distPath) //删除文件test.txt
  1729. if err != nil {
  1730. //如果删除失败则输出 file remove Error!
  1731. fmt.Println("file remove Error!")
  1732. //输出错误详细信息
  1733. fmt.Printf("%s", err)
  1734. } else {
  1735. //如果删除成功则输出 file remove OK!
  1736. fmt.Print("file remove OK!")
  1737. }
  1738. }
  1739. if err != nil {
  1740. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1741. } else {
  1742. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1743. }
  1744. } else {
  1745. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1746. }
  1747. }
  1748. // @Summary 删除文件
  1749. // @Tags RemoveFileByName
  1750. // @Accept json
  1751. // @Produce json
  1752. // @Param sqlname query string true "sqlname"
  1753. // @Param offset query int true "offset"
  1754. // @Param pagecount query int true "pagecount"
  1755. // @Param returntype query string true "returntype"
  1756. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1757. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1758. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1759. // @Router /data/PostDataByName [POST]
  1760. func RemoveFileByName(c *gin.Context) {
  1761. appG := app.Gin{C: c}
  1762. id := c.Param("id")
  1763. logging.Info("DownloadFile ", c.Keys, id)
  1764. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1765. if eqdoc == nil {
  1766. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1767. return
  1768. }
  1769. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1770. err = os.Remove(distPath) //删除文件test.txt
  1771. if err != nil {
  1772. //如果删除失败则输出 file remove Error!
  1773. fmt.Println("file remove Error!")
  1774. //输出错误详细信息
  1775. fmt.Printf("%s", err)
  1776. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1777. return
  1778. }
  1779. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1780. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1781. }
  1782. // @Summary 根据APISQL表中SQL执行得到数据集
  1783. // @Tags PostDataByName
  1784. // @Accept json
  1785. // @Produce json
  1786. // @Param sqlname query string true "sqlname"
  1787. // @Param offset query int true "offset"
  1788. // @Param pagecount query int true "pagecount"
  1789. // @Param returntype query string true "returntype"
  1790. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1791. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1792. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1793. // @Router /data/PostDataByName [POST]
  1794. func UpdateDataRelation(c *gin.Context) {
  1795. appG := app.Gin{C: c}
  1796. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1797. fsion := gofasion.NewFasion(string(dataByte))
  1798. tablename := fsion.Get("name").ValueStr()
  1799. dataname := fsion.Get("dataname").ValueStr()
  1800. datavalue := fsion.Get("datavalue").ValueStr()
  1801. valuename := fsion.Get("valuename").ValueStr()
  1802. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1803. values := fsion.Get("values").Array()
  1804. tx := restful.Engine.NewSession()
  1805. err := tx.Begin()
  1806. defer func() {
  1807. switch {
  1808. case err != nil:
  1809. if tx != nil {
  1810. tx.Rollback()
  1811. }
  1812. default:
  1813. if tx != nil {
  1814. err = tx.Commit()
  1815. }
  1816. }
  1817. if tx != nil {
  1818. tx.Close()
  1819. }
  1820. }()
  1821. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1822. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1823. d_params := make([]interface{}, 4)
  1824. d_params[0] = datavalue
  1825. s_params := ""
  1826. for _, v_values := range values {
  1827. d_params[1] = v_values.ValueStr()
  1828. if s_params == "" {
  1829. s_params = v_values.ValueStr()
  1830. } else {
  1831. s_params = s_params + "," + v_values.ValueStr()
  1832. }
  1833. d_params[2] = d_params[1]
  1834. d_params[3] = d_params[0]
  1835. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1836. if err != nil {
  1837. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1838. break
  1839. }
  1840. }
  1841. if s_params != "" {
  1842. deleteSqlstr := "delete from " + tablename + " " +
  1843. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1844. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1845. if err != nil {
  1846. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1847. } else if err == nil {
  1848. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1849. }
  1850. } else {
  1851. deleteSqlstr := "delete from " + tablename + " " +
  1852. " where " + dataname + " = " + datavalue
  1853. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1854. if err != nil {
  1855. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1856. } else if err == nil {
  1857. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1858. }
  1859. }
  1860. }
  1861. // @Summary 根据APISQL表中SQL执行得到数据集
  1862. // @Tags PostDatasByName
  1863. // @Accept json
  1864. // @Produce json
  1865. // @Param sqlname query string true "sqlname"
  1866. // @Param offset query int true "offset"
  1867. // @Param pagecount query int true "pagecount"
  1868. // @Param returntype query string true "returntype"
  1869. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1870. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1871. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1872. // @Router /data/PostDatasByName [POST]
  1873. func PostDataByNames(c *gin.Context) {
  1874. appG := app.Gin{C: c}
  1875. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1876. fsion := gofasion.NewFasion(string(dataByte))
  1877. sqlParams := fsion.Get("array").Array()
  1878. queryData := make(map[string]interface{})
  1879. for _, v := range sqlParams {
  1880. fsion2 := gofasion.NewFasion(v.Json())
  1881. ss := fsion2.Get("name")
  1882. aa := fsion2.Get("params")
  1883. fmt.Println(ss, aa)
  1884. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1885. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1886. if sql == "" {
  1887. errorm := make(map[string]interface{})
  1888. errorm["code"] = e.ERROR
  1889. errorm["message"] = "sql没有找到"
  1890. errorm["param"] = ""
  1891. queryData[fsion2.Get("name").ValueStr()] = errorm
  1892. continue
  1893. } else if sql != "" {
  1894. s_params := make([]interface{}, 0)
  1895. if fsion2.HasKey("parammaps") {
  1896. parammaps := fsion2.Get("parammaps")
  1897. paramslist := strings.Split(p, ",")
  1898. if len(paramslist) > 0 && p != "" {
  1899. for _, value := range paramslist {
  1900. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1901. if tempv, exists := c.Get("jwt_username"); exists {
  1902. s_params = append(s_params, tempv.(string))
  1903. } else {
  1904. s_params = append(s_params, "")
  1905. }
  1906. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1907. ids, err := setting.SnowIds.NextId()
  1908. if err != nil {
  1909. ids = time.Now().UnixNano()
  1910. logging.Info("create SnowIds err", err)
  1911. }
  1912. s_params = append(s_params, ids)
  1913. } else {
  1914. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1915. }
  1916. }
  1917. }
  1918. } else if fsion2.HasKey("params") {
  1919. params := fsion2.Get("params").Array()
  1920. //ids,err := setting.SnowIds.NextId()
  1921. //if err !=nil{
  1922. // ids = time.Now().UnixNano()
  1923. // logging.Info("create SnowIds err",err)
  1924. //}
  1925. //s_params = append(s_params, ids)
  1926. for _, v_params := range params {
  1927. s_params = append(s_params, v_params.ValueStr())
  1928. }
  1929. }
  1930. _, err := execDataBySql(sql, s_params)
  1931. if err != nil {
  1932. logging.Error("PostDataByName err: ", err)
  1933. errorm := make(map[string]interface{})
  1934. errorm["code"] = e.ERROR
  1935. errorm["message"] = err.Error()
  1936. errorm["param"] = s_params
  1937. queryData[fsion2.Get("name").ValueStr()] = errorm
  1938. continue
  1939. } else {
  1940. errorm := make(map[string]interface{})
  1941. errorm["code"] = e.SUCCESS
  1942. errorm["message"] = "success"
  1943. queryData[fsion2.Get("name").ValueStr()] = errorm
  1944. continue
  1945. }
  1946. } else {
  1947. errorm := make(map[string]interface{})
  1948. errorm["code"] = e.ERROR
  1949. errorm["message"] = "NO SQL"
  1950. errorm["param"] = ""
  1951. queryData[fsion2.Get("name").ValueStr()] = errorm
  1952. }
  1953. }
  1954. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1955. }
  1956. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1957. if offset > 0 {
  1958. offset = offset - 1
  1959. }
  1960. //if pagecount == 0 {
  1961. // pagecount = setting.AppSetting.PageSize
  1962. //}else if pagecount>setting.AppSetting.PageSize{
  1963. // pagecount = setting.AppSetting.PageSize
  1964. //}
  1965. if returntype == "list" {
  1966. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1967. return queryData, err
  1968. } else if returntype == "listlist" {
  1969. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1970. return queryData, err
  1971. } else {
  1972. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1973. return queryData, err
  1974. }
  1975. }
  1976. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1977. if offset > 0 {
  1978. offset = offset - 1
  1979. }
  1980. //if pagecount == 0 {
  1981. // pagecount = setting.AppSetting.PageSize
  1982. //}else if pagecount>setting.AppSetting.PageSize{
  1983. // pagecount = setting.AppSetting.PageSize
  1984. //}
  1985. if returntype == "list" {
  1986. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1987. return queryData, err
  1988. } else if returntype == "listlist" {
  1989. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1990. return queryData, err
  1991. } else {
  1992. fmt.Println(params)
  1993. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1994. return queryData, err
  1995. }
  1996. }
  1997. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1998. paramslist := strings.Split(Params, ",")
  1999. s_params := make([]interface{}, 0)
  2000. if isList {
  2001. for _, v_params := range thisParams["params"].([]interface{}) {
  2002. s_params = append(s_params, v_params)
  2003. }
  2004. } else {
  2005. paramslist := strings.Split(Params, ",")
  2006. if len(paramslist) > 0 && Params != "" {
  2007. for _, value := range paramslist {
  2008. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2009. }
  2010. }
  2011. }
  2012. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2013. for _, queryData_ := range queryData {
  2014. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2015. if isList {
  2016. if queryData_[idname] != nil {
  2017. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2018. }
  2019. } else {
  2020. if queryData_[idname] != nil {
  2021. thisParams[idname] = queryData_[idname].(interface{})
  2022. }
  2023. if len(paramslist) > 0 && Params != "" {
  2024. s_params = make([]interface{}, 0)
  2025. for _, value := range paramslist {
  2026. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2027. }
  2028. }
  2029. }
  2030. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2031. } else {
  2032. }
  2033. }
  2034. return queryData, err
  2035. }
  2036. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2037. queryData, err := restful.ExecQuery(sqlstr, params)
  2038. return queryData, err
  2039. }
  2040. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2041. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2042. return queryData, err
  2043. }
  2044. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2045. queryData, err := restful.ExecQuery(sqlstr, params)
  2046. return queryData, err
  2047. }
  2048. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2049. // @Tags ImportExcel
  2050. // @Accept json
  2051. // @Produce json
  2052. // @Param file query string true "文件名"
  2053. // @Param name header string true "执行sql的名字"
  2054. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2055. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2056. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2057. // @Router /data/ImportExcel [POST]
  2058. func ImportExcel(c *gin.Context) {
  2059. appG := app.Gin{C: c}
  2060. inputdata := ""
  2061. c.Request.ParseForm()
  2062. params := c.Request.Form
  2063. file, _, err := c.Request.FormFile("file")
  2064. if err != nil {
  2065. appG.Response(http.StatusOK, e.ERROR, err)
  2066. return
  2067. }
  2068. sqlnamestrs := params.Get("name")
  2069. sheetname := params.Get("sheetname")
  2070. pastureid := params.Get("pastureid")
  2071. //importParams := params.Get("importParams")
  2072. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2073. // 必输项参数 (字符串格式 "field1,field2,field3")
  2074. requiredParams := params.Get("requiredParams")
  2075. // 日期参数
  2076. dateParams := params.Get("dateParams")
  2077. // 数字参数
  2078. numParams := params.Get("numParams")
  2079. //将字符串分割开
  2080. dateParamslist := strings.Split(dateParams, ",")
  2081. requiredParamslist := strings.Split(requiredParams, ",")
  2082. numParamslist := strings.Split(numParams, ",")
  2083. queryData := make([]interface{}, 0)
  2084. sqlslist := strings.Split(sqlnamestrs, ",")
  2085. xlsx1, err := excelize.OpenReader(file)
  2086. if err != nil {
  2087. fmt.Println(err)
  2088. return
  2089. }
  2090. ok := 0
  2091. error := 0
  2092. isdone := true
  2093. rows := xlsx1.GetRows(sheetname)
  2094. // 限制10000条,多余的截取掉
  2095. if len(rows) > 10000 {
  2096. rows = rows[:10000]
  2097. }
  2098. for i, row := range rows {
  2099. if i > 0 {
  2100. entry := make(map[string]interface{})
  2101. outentry := make(map[string]interface{})
  2102. for j, colCell := range rows[0] {
  2103. for k, colCell1 := range row {
  2104. if j == k {
  2105. outentry[colCell] = colCell1
  2106. entry[colCell] = colCell1
  2107. }
  2108. }
  2109. }
  2110. inputdata = ""
  2111. a := ""
  2112. fmt.Println(outentry, entry)
  2113. //校验日期格式
  2114. for _, v := range dateParamslist {
  2115. if v == "" {
  2116. continue
  2117. }
  2118. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2119. dtime, err := TransfTime(d.(string))
  2120. if err != nil {
  2121. a = strings.Trim(v, " ")
  2122. break
  2123. }
  2124. outentry[strings.Trim(v, " ")] = dtime
  2125. }
  2126. }
  2127. if a != "" {
  2128. outentry["error_msg"] = a + " 格式错误"
  2129. error++
  2130. queryData = append(queryData, outentry)
  2131. continue
  2132. }
  2133. a = ""
  2134. //校验必填格式
  2135. for _, v := range requiredParamslist {
  2136. if v == "" {
  2137. continue
  2138. }
  2139. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2140. a = strings.Trim(v, " ")
  2141. break
  2142. }
  2143. }
  2144. if a != "" {
  2145. outentry["error_msg"] = a + " 未填或格式错误"
  2146. error++
  2147. queryData = append(queryData, outentry)
  2148. continue
  2149. }
  2150. a = ""
  2151. //校验数字格式
  2152. for _, v := range numParamslist {
  2153. if v == "" {
  2154. continue
  2155. }
  2156. d, ok := outentry[strings.Trim(v, " ")]
  2157. if !ok || d == "" {
  2158. outentry[strings.Trim(v, " ")] = 0
  2159. } else {
  2160. var fl float64
  2161. switch d.(type) {
  2162. case string:
  2163. fl, err = strconv.ParseFloat(d.(string), 64)
  2164. }
  2165. if err != nil || fl < 0 {
  2166. a = strings.Trim(v, " ")
  2167. break
  2168. }
  2169. }
  2170. }
  2171. if a != "" {
  2172. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2173. error++
  2174. queryData = append(queryData, outentry)
  2175. continue
  2176. }
  2177. tx := restful.Engine.NewSession()
  2178. err := tx.Begin()
  2179. for _, sqlnamestr := range sqlslist {
  2180. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2181. paramslist := strings.Split(paramslists, ",")
  2182. if len(paramslist) > 0 {
  2183. s_params := make([]interface{}, 0)
  2184. for _, value := range paramslist {
  2185. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2186. if tempv, exists := c.Get("jwt_username"); exists {
  2187. s_params = append(s_params, tempv.(string))
  2188. } else {
  2189. s_params = append(s_params, "")
  2190. }
  2191. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2192. s_params = append(s_params, pastureid)
  2193. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2194. ids, err := setting.SnowIds.NextId()
  2195. if err != nil {
  2196. ids = time.Now().UnixNano()
  2197. logging.Info("create SnowIds err", err)
  2198. }
  2199. s_params = append(s_params, ids)
  2200. } else {
  2201. if outentry[strings.Trim(value, " ")] == nil {
  2202. s_params = append(s_params, "")
  2203. } else {
  2204. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2205. }
  2206. }
  2207. }
  2208. outentry["input"] = inputdata
  2209. fmt.Println(sql, s_params)
  2210. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2211. if err != nil {
  2212. if tx != nil {
  2213. tx.Rollback()
  2214. }
  2215. if tx != nil {
  2216. tx.Close()
  2217. }
  2218. msg := geterrmsg(err.Error())
  2219. outentry["error_msg"] = msg
  2220. error++
  2221. queryData = append(queryData, outentry)
  2222. isdone = true
  2223. break
  2224. } else {
  2225. if len(returnmsgmap1) > 0 {
  2226. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2227. if tx != nil {
  2228. tx.Rollback()
  2229. }
  2230. if tx != nil {
  2231. tx.Close()
  2232. }
  2233. msg := geterrmsg(va.(string))
  2234. outentry["error_msg"] = msg
  2235. error++
  2236. queryData = append(queryData, outentry)
  2237. isdone = true
  2238. break
  2239. }
  2240. }
  2241. isdone = false
  2242. }
  2243. }
  2244. }
  2245. switch {
  2246. case err != nil:
  2247. if tx != nil {
  2248. tx.Rollback()
  2249. }
  2250. default:
  2251. if tx != nil {
  2252. err = tx.Commit()
  2253. }
  2254. }
  2255. if tx != nil {
  2256. tx.Close()
  2257. }
  2258. }
  2259. if !isdone {
  2260. ok++
  2261. isdone = true
  2262. }
  2263. }
  2264. data := make(map[string]interface{})
  2265. data["result"] = queryData
  2266. data["success"] = ok
  2267. data["err_count"] = error
  2268. appG.Response(http.StatusOK, e.SUCCESS, data)
  2269. }
  2270. func TransfTime(timestr string) (string, error) {
  2271. if timestr == "" {
  2272. return time.Now().Format("2006-01-02"), nil
  2273. }
  2274. days, err := strconv.Atoi(timestr)
  2275. if err != nil {
  2276. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2277. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2278. }
  2279. _, err := time.Parse("2006-01-02", timestr)
  2280. if err != nil {
  2281. t, err := time.Parse("2006/01/02", timestr)
  2282. if err != nil {
  2283. t, err := time.Parse("2006.01.02", timestr)
  2284. if err != nil {
  2285. return "", err
  2286. } else {
  2287. return t.Format("2006-01-02"), nil
  2288. }
  2289. } else {
  2290. return t.Format("2006-01-02"), nil
  2291. }
  2292. } else {
  2293. return timestr, nil
  2294. }
  2295. }
  2296. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2297. times = times.AddDate(0, 0, days)
  2298. return times.Format("2006-01-02"), nil
  2299. }
  2300. func Createchart(c *gin.Context) {
  2301. appG := app.Gin{C: c}
  2302. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2303. fsion := gofasion.NewFasion(string(dataByte))
  2304. chart_name := fsion.Get("chart_name").ValueStr()
  2305. desc := fsion.Get("desc").ValueStr()
  2306. pastureid := fsion.Get("pastureid").ValueStr()
  2307. source_id := fsion.Get("source_id").ValueStr()
  2308. emp := fsion.Get("emp").ValueStr()
  2309. content := fsion.Get("content").Json()
  2310. var mapResult map[string]interface{}
  2311. err1 := json.Unmarshal([]byte(content), &mapResult)
  2312. if err1 != nil {
  2313. fmt.Println("JsonToMapDemo err: ", err1)
  2314. }
  2315. tx := restful.Engine.NewSession()
  2316. err := tx.Begin()
  2317. defer func() {
  2318. switch {
  2319. case err != nil:
  2320. logging.Error("tx.Begin 事务启动失败__error:", err)
  2321. if tx != nil {
  2322. tx.Rollback()
  2323. }
  2324. default:
  2325. if tx != nil {
  2326. err = tx.Commit()
  2327. }
  2328. }
  2329. if tx != nil {
  2330. tx.Close()
  2331. }
  2332. }()
  2333. ids, err := setting.SnowIds.NextId()
  2334. if err != nil {
  2335. ids = time.Now().UnixNano()
  2336. logging.Info("create SnowIds err", err)
  2337. }
  2338. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2339. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2340. if err != nil {
  2341. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2342. } else {
  2343. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2344. }
  2345. }
  2346. func Updatedashboard(c *gin.Context) {
  2347. appG := app.Gin{C: c}
  2348. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2349. fsion := gofasion.NewFasion(string(dataByte))
  2350. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2351. pastureid := fsion.Get("pastureid").ValueStr()
  2352. content := fsion.Get("content").Json()
  2353. var mapResult map[string]interface{}
  2354. err1 := json.Unmarshal([]byte(content), &mapResult)
  2355. if err1 != nil {
  2356. fmt.Println("JsonToMapDemo err: ", err1)
  2357. }
  2358. layout := mapResult["layout"]
  2359. tx := restful.Engine.NewSession()
  2360. err := tx.Begin()
  2361. defer func() {
  2362. switch {
  2363. case err != nil:
  2364. logging.Error("tx.Begin 事务启动失败__error:", err)
  2365. if tx != nil {
  2366. tx.Rollback()
  2367. }
  2368. default:
  2369. if tx != nil {
  2370. err = tx.Commit()
  2371. }
  2372. }
  2373. if tx != nil {
  2374. tx.Close()
  2375. }
  2376. }()
  2377. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2378. if err != nil {
  2379. println("2", err.Error())
  2380. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2381. } else {
  2382. if exec != nil {
  2383. if exec[0]["content"] == nil {
  2384. mapR := make(map[string]interface{})
  2385. mapR["layout"] = layout
  2386. mjson, _ := json.Marshal(mapR)
  2387. mString := string(mjson)
  2388. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2389. if err3 != nil {
  2390. println("3", err3.Error())
  2391. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2392. } else {
  2393. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2394. }
  2395. } else {
  2396. var mapR map[string]interface{}
  2397. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2398. if err1 != nil {
  2399. fmt.Println("JsonToMapDemo err: ", err2)
  2400. }
  2401. mapR["layout"] = layout
  2402. mjson, _ := json.Marshal(mapR)
  2403. mString := string(mjson)
  2404. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2405. if err3 != nil {
  2406. println("3", err3.Error())
  2407. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2408. } else {
  2409. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2410. }
  2411. }
  2412. } else {
  2413. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2414. }
  2415. }
  2416. }
  2417. func ExecSQL(c *gin.Context) {
  2418. appG := app.Gin{C: c}
  2419. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2420. fsion := gofasion.NewFasion(string(dataByte))
  2421. content := fsion.Get("content").Json()
  2422. pastureid := fsion.Get("pastureid").ValueStr()
  2423. var mapResult map[string]interface{}
  2424. err1 := json.Unmarshal([]byte(content), &mapResult)
  2425. if err1 != nil {
  2426. fmt.Println("JsonToMapDemo err: ", err1)
  2427. }
  2428. sqlstr := "select "
  2429. groupstr := " GROUP BY "
  2430. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2431. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2432. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2433. }
  2434. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2435. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2436. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2437. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2438. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2439. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2440. sqlstr = sqlstr + tem + ","
  2441. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2442. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2443. sqlstr = sqlstr + tem + ","
  2444. } else {
  2445. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2446. sqlstr = sqlstr + tem + ","
  2447. }
  2448. }
  2449. if _, ok := mapResult["selectedCalcul2"]; ok {
  2450. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2451. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2452. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2453. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2454. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2455. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2456. sqlstr = sqlstr + tem + ","
  2457. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2458. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2459. sqlstr = sqlstr + tem + ","
  2460. } else {
  2461. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2462. sqlstr = sqlstr + tem + ","
  2463. }
  2464. }
  2465. }
  2466. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2467. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2468. sqlstr = sqlstr + " where pastureid=" + pastureid
  2469. if len(mapResult["filters"].([]interface{})) > 0 {
  2470. sqlstr = sqlstr + " and "
  2471. }
  2472. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2473. for _, value := range mapResult["filters"].([]interface{}) {
  2474. switch value.(map[string]interface{})["filterOperator"].(string) {
  2475. case ">", "=", "<", ">=", "<=", "!=", "like":
  2476. 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 "
  2477. case "IN":
  2478. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2479. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2480. sqlstr = sqlstr + value1.(string) + ","
  2481. }
  2482. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2483. sqlstr = sqlstr + ")" + " AND "
  2484. case "BETWEEN":
  2485. 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 "
  2486. }
  2487. }
  2488. if len(mapResult["filters"].([]interface{})) > 0 {
  2489. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2490. }
  2491. //
  2492. groupstr = groupstr[0 : len(groupstr)-1]
  2493. sqlstr = sqlstr + groupstr + " "
  2494. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2495. sqlstr = sqlstr + " order by "
  2496. }
  2497. //
  2498. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2499. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2500. sqlstr = sqlstr + value.(string) + " "
  2501. } else {
  2502. sqlstr = sqlstr + value.(string) + ","
  2503. }
  2504. }
  2505. //
  2506. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2507. tx := restful.Engine.NewSession()
  2508. err := tx.Begin()
  2509. defer func() {
  2510. switch {
  2511. case err != nil:
  2512. logging.Error("tx.Begin 事务启动失败__error:", err)
  2513. if tx != nil {
  2514. tx.Rollback()
  2515. }
  2516. default:
  2517. if tx != nil {
  2518. err = tx.Commit()
  2519. }
  2520. }
  2521. if tx != nil {
  2522. tx.Close()
  2523. }
  2524. }()
  2525. exec, err := tx.SQL(sqlstr).Query().List()
  2526. if err != nil {
  2527. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2528. } else {
  2529. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2530. }
  2531. }
  2532. func Dashboards(c *gin.Context) {
  2533. appG := app.Gin{C: c}
  2534. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2535. fsion := gofasion.NewFasion(string(dataByte))
  2536. sqlnamestr := fsion.Get("name").ValueStr()
  2537. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2538. offset := fsion.Get("offset").ValueDefaultInt(0)
  2539. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2540. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2541. month := fsion.Get("month").ValueDefaultStr("map")
  2542. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2543. tx := restful.Engine.NewSession()
  2544. err := tx.Begin()
  2545. defer func() {
  2546. switch {
  2547. case err != nil:
  2548. if tx != nil {
  2549. tx.Rollback()
  2550. }
  2551. default:
  2552. if tx != nil {
  2553. err = tx.Commit()
  2554. }
  2555. }
  2556. if tx != nil {
  2557. tx.Close()
  2558. }
  2559. }()
  2560. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2561. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2562. if sql != "" {
  2563. s_params := make([]interface{}, 0)
  2564. if fsion.HasKey("parammaps") {
  2565. parammaps := fsion.Get("parammaps")
  2566. paramslist := strings.Split(p, ",")
  2567. if len(paramslist) > 0 && p != "" {
  2568. for _, value := range paramslist {
  2569. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2570. if tempv, exists := c.Get("jwt_username"); exists {
  2571. s_params = append(s_params, tempv.(string))
  2572. } else {
  2573. s_params = append(s_params, "")
  2574. }
  2575. } else {
  2576. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2577. }
  2578. }
  2579. }
  2580. }
  2581. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2582. if err != nil {
  2583. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2584. } else {
  2585. //paramslist1 := strings.Split(p1, ",")
  2586. dids := make([]interface{}, 0)
  2587. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2588. var mapResult map[string]interface{}
  2589. dids = append(dids, value["dashboard_id"])
  2590. if value["content"] != nil {
  2591. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2592. if err1 != nil {
  2593. println("JsonToMapDemo1 err: ", err1)
  2594. }
  2595. temap := make(map[string]interface{})
  2596. tem := mapResult["layout"].([]interface{})
  2597. if v, ok := value["chartids"]; ok {
  2598. chartids := strings.Split(v.(string), ",")
  2599. for _, va := range chartids {
  2600. a := false
  2601. for _, v2 := range tem {
  2602. if v2.(map[string]interface{})["id"].(string) == va {
  2603. a = true
  2604. //println("va1======",va)
  2605. }
  2606. }
  2607. if !a {
  2608. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2609. va + "\",\"id\":\"" + va +
  2610. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2611. var mapTem map[string]interface{}
  2612. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2613. if err1 != nil {
  2614. println("JsonToMapDemo err: ", err1)
  2615. }
  2616. tem = append(tem, mapTem)
  2617. }
  2618. }
  2619. temap["layout"] = tem
  2620. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2621. }
  2622. } else {
  2623. temap := make(map[string]interface{})
  2624. tem := make([]interface{}, 0)
  2625. if v, ok := value["chartids"]; ok {
  2626. chartids := strings.Split(v.(string), ",")
  2627. for _, va := range chartids {
  2628. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2629. va + "\",\"id\":\"" + va +
  2630. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2631. var mapTem map[string]interface{}
  2632. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2633. if err1 != nil {
  2634. println("JsonToMapDemo err: ", err1)
  2635. }
  2636. tem = append(tem, mapTem)
  2637. }
  2638. temap["layout"] = tem
  2639. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2640. }
  2641. }
  2642. }
  2643. queryData.(map[string]interface{})["order"] = dids
  2644. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2645. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2646. }
  2647. } else {
  2648. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2649. }
  2650. }
  2651. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2652. fsion := gofasion.NewFasion(parammaps)
  2653. sqlnamestr := fsion.Get("name").ValueStr()
  2654. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2655. offset := fsion.Get("offset").ValueDefaultInt(0)
  2656. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2657. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2658. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2659. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2660. body := []byte("")
  2661. if sql != "" {
  2662. s_params := make([]interface{}, 0)
  2663. if fsion.HasKey("parammaps") {
  2664. parammaps := fsion.Get("parammaps")
  2665. paramslist := strings.Split(p, ",")
  2666. if len(paramslist) > 0 && p != "" {
  2667. for _, value := range paramslist {
  2668. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2669. }
  2670. }
  2671. }
  2672. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2673. if err != nil {
  2674. } else {
  2675. paramslist1 := strings.Split(p1, ",")
  2676. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2677. s_params1 := make([]interface{}, 0)
  2678. if len(paramslist1) > 0 && p1 != "" {
  2679. for _, v := range paramslist1 {
  2680. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2681. }
  2682. }
  2683. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2684. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2685. body, _ = json.Marshal(queryData)
  2686. }
  2687. }
  2688. }
  2689. bs := bytes.NewBuffer(body)
  2690. client := &http.Client{}
  2691. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2692. req, err := http.NewRequest(RequestMethod,
  2693. url,
  2694. bs,
  2695. )
  2696. if err != nil {
  2697. }
  2698. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2699. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2700. if err != nil {
  2701. // handle error
  2702. }
  2703. resp, err := client.Do(req)
  2704. if err != nil {
  2705. return ""
  2706. }
  2707. defer resp.Body.Close()
  2708. result_body, err := ioutil.ReadAll(resp.Body)
  2709. if err != nil {
  2710. return ""
  2711. }
  2712. fmt.Println(string(result_body))
  2713. return ""
  2714. }
  2715. func GetSummary(c *gin.Context) {
  2716. appG := app.Gin{C: c}
  2717. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2718. fsion := gofasion.NewFasion(string(dataByte))
  2719. offset := fsion.Get("offset").ValueDefaultInt(0)
  2720. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2721. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2722. parammaps := fsion.Get("parammaps")
  2723. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2724. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2725. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2726. tx := restful.Engine.NewSession()
  2727. defer tx.Close()
  2728. sqlnamestr := ""
  2729. if genre == "0" {
  2730. if status == "0" {
  2731. sqlnamestr = "getAccuracyJSY"
  2732. } else if status == "1" {
  2733. sqlnamestr = "getAccuracyHFT"
  2734. } else if status == "2" {
  2735. sqlnamestr = "getAccuracyHNS"
  2736. } else if status == "3" {
  2737. sqlnamestr = "getAccuracyHSC"
  2738. } else if status == "4" {
  2739. sqlnamestr = "getAccuracyHCC"
  2740. } else if status == "5" {
  2741. sqlnamestr = "getAccuracyMC"
  2742. } else if status == "6" {
  2743. sqlnamestr = "getAccuracyFeedHL"
  2744. } else if status == "7" {
  2745. sqlnamestr = "getAccuracyRT"
  2746. }
  2747. } else {
  2748. if status == "0" {
  2749. sqlnamestr = "getAccuracySCCJSY"
  2750. } else if status == "1" {
  2751. sqlnamestr = "getAccuracySFT"
  2752. } else if status == "2" {
  2753. sqlnamestr = "getAccuracySNS"
  2754. } else if status == "3" {
  2755. sqlnamestr = "getAccuracySSC"
  2756. } else if status == "4" {
  2757. sqlnamestr = "getAccuracySCC"
  2758. } else if status == "5" {
  2759. sqlnamestr = "getAccuracySLCL"
  2760. } else if status == "7" {
  2761. sqlnamestr = "getAccuracySCCRT"
  2762. }
  2763. }
  2764. if isDate == "1" {
  2765. sqlnamestr += "Date"
  2766. }
  2767. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2768. // fmt.Println(sqlnamestr, sql)
  2769. if sql != "" {
  2770. s_params := make([]interface{}, 0)
  2771. // if fsion.HasKey("parammaps") {
  2772. fmt.Println(s_params, "222", p)
  2773. paramslist := strings.Split(p, ",")
  2774. if len(paramslist) > 0 && p != "" {
  2775. for _, value := range paramslist {
  2776. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2777. if tempv, exists := c.Get("jwt_username"); exists {
  2778. s_params = append(s_params, tempv.(string))
  2779. } else {
  2780. s_params = append(s_params, "")
  2781. }
  2782. } else {
  2783. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2784. }
  2785. }
  2786. }
  2787. if returntype == "xlsx" {
  2788. var xlsxfile *xlsx.File
  2789. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2790. //c.File("c:/dd.xlsx")
  2791. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2792. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2793. c.Header("Content-Transfer-Encoding", "binary")
  2794. _ = xlsxfile.Write(c.Writer)
  2795. } else {
  2796. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2797. if err != nil {
  2798. logging.Error("GetDataByName err: ", err)
  2799. msg := geterrmsg(err.Error())
  2800. appG.Response(http.StatusOK, e.ERROR, msg)
  2801. } else {
  2802. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2803. }
  2804. }
  2805. } else {
  2806. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2807. }
  2808. }
  2809. // type lpplanStruct struct {
  2810. // Id int64 `xorm:"id"`
  2811. // Tmrname string `xorm:"tmrname"`
  2812. // Tmrid int64 `xorm:"tmrid"`
  2813. // Sort int64 `xorm:"sort"`
  2814. // Sel int64 `xorm:"sel"`
  2815. // Times int64 `xorm:"times"`
  2816. // Ftname string `xorm:"ftname"`
  2817. // Ftid int64 `xorm:"ftid"`
  2818. // Maxweight float64 `xorm:"maxweight"`
  2819. // Sumweight float64 `xorm:"sumweight"`
  2820. // Sumcowcount int64 `xorm:"sumcowcount"`
  2821. // Pastureid string `xorm:"pastureid"`
  2822. // Display string `xorm:"display"`
  2823. // Issplit int64 `xorm:"issplit"`
  2824. // BeginTime string `xorm:"begintime"`
  2825. // }
  2826. func UpdateFTdetail(c *gin.Context) {
  2827. appG := app.Gin{C: c}
  2828. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2829. tempval_ := make(map[string]interface{})
  2830. tempCommon := make(map[string]interface{})
  2831. tempval := make([]map[string]interface{}, 0)
  2832. fTChange := make(map[string]interface{}, 0)
  2833. // fpdOldDataList := make([]map[string]interface{}, 0)
  2834. // fpdDataList := make([]map[string]interface{}, 0)
  2835. fsion := gofasion.NewFasion(string(dataByte))
  2836. // parammaps := fsion.Get("parammaps")
  2837. createdate := time.Now().Format("2006-01-02 15:04:05")
  2838. err := json.Unmarshal(dataByte, &tempval_)
  2839. if err != nil {
  2840. appG.Response(http.StatusOK, e.ERROR, false)
  2841. return
  2842. }
  2843. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2844. tx := restful.Engine.NewSession()
  2845. if v, ok := tempval_["data"].([]interface{}); ok {
  2846. for _, Tvalue := range v {
  2847. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2848. if v1["name"] == "updateFPbyFTChange" {
  2849. fTChange = v1
  2850. continue
  2851. }
  2852. tempval = append(tempval, v1)
  2853. }
  2854. }
  2855. }
  2856. parammaps := fTChange["parammaps"].(map[string]interface{})
  2857. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2858. // if err != nil {
  2859. // logs.Error(err)
  2860. // appG.Response(http.StatusOK, e.ERROR, false)
  2861. // return
  2862. // }
  2863. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2864. // if err != nil {
  2865. // logs.Error(err)
  2866. // appG.Response(http.StatusOK, e.ERROR, false)
  2867. // return
  2868. // }
  2869. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2870. // if err != nil {
  2871. // logs.Error(err)
  2872. // appG.Response(http.StatusOK, e.ERROR, false)
  2873. // return
  2874. // }
  2875. err = tx.Begin()
  2876. if err != nil {
  2877. logging.Error("tx.Begin 事务启动失败__error:", err)
  2878. }
  2879. defer func() {
  2880. if err != nil {
  2881. if tx != nil {
  2882. tx.Rollback()
  2883. }
  2884. }
  2885. if tx != nil {
  2886. tx.Close()
  2887. }
  2888. }()
  2889. if err != nil {
  2890. } else {
  2891. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2892. tempCommon = v
  2893. }
  2894. // 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 ,
  2895. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2896. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2897. // UNION
  2898. // 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 ,
  2899. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2900. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2901. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2902. if err == nil {
  2903. if tempv, exists := c.Get("jwt_username"); exists {
  2904. tempCommon["jwt_username"] = tempv.(string)
  2905. }
  2906. for _, paramvalue := range tempval {
  2907. if _, ok := paramvalue["resultname"]; !ok {
  2908. paramvalue["resultname"] = paramvalue["name"]
  2909. }
  2910. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2911. if err != nil {
  2912. logging.Error("ExecDataParam error:", err)
  2913. break
  2914. }
  2915. }
  2916. if err != nil {
  2917. msg := geterrmsg(err.Error())
  2918. appG.Response(http.StatusOK, e.ERROR, msg)
  2919. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2920. }
  2921. }
  2922. }
  2923. tx.Commit()
  2924. // go func() {
  2925. if fTChange != nil {
  2926. parammaps := fTChange["parammaps"].(map[string]interface{})
  2927. if parammaps["type"].(float64) == 1 {
  2928. _, err = tx.SQL(`UPDATE feedp fp
  2929. set
  2930. ccountratio = ccount *(ratio /100 ),
  2931. fp.ftweight= IFNULL(IF(
  2932. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2933. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2935. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2936. ),0),fp.feedweight = IFNULL(IF(
  2937. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2938. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2940. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2941. ),0) +ifnull(fp.supplyweight,0)
  2942. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2943. _, err = tx.SQL(`UPDATE fpdetail fpd
  2944. INNER JOIN feedp fp
  2945. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2946. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2947. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2948. } else {
  2949. _, err = tx.SQL(`UPDATE feedp fp
  2950. SET ccountratio = ccount *(ratio /100 ),
  2951. fp.supplyweight= IFNULL(IF(
  2952. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2953. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2954. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2955. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2956. ),0),fp.feedweight = IFNULL(IF(
  2957. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2958. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2959. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2960. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2961. ),0) +ifnull(fp.supplyweight,0)
  2962. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2963. _, err = tx.SQL(`UPDATE fpdetail fpd
  2964. INNER JOIN feedp fp
  2965. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2966. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2967. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2968. }
  2969. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2970. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2971. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2972. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2973. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2974. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2975. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2976. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2977. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2978. // fmt.Println(ftId)
  2979. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2980. // 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 ,
  2981. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2982. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2983. // UNION
  2984. // 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 ,
  2985. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2986. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2987. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2988. // lpplanList := make([]*lpplanStruct, 0)
  2989. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2990. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2991. // (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)
  2992. // if err != nil {
  2993. // logs.Error(err, 1)
  2994. // return
  2995. // }
  2996. // lppidlist := []string{}
  2997. // for _, lpp := range lpplanList {
  2998. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2999. // }
  3000. // if len(lppidlist) <= 0 {
  3001. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3002. // return
  3003. // }
  3004. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3005. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3006. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3007. // if err != nil {
  3008. // // tx.Rollback()
  3009. // logs.Error(err, 2, parammaps["pastureid"])
  3010. // return
  3011. // }
  3012. // for _, lpp := range lpplandtl1AllList {
  3013. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3014. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3015. // if err != nil {
  3016. // logs.Error(err)
  3017. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3018. // return
  3019. // }
  3020. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3021. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3022. // if err != nil {
  3023. // logs.Error(err)
  3024. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3025. // return
  3026. // }
  3027. // }
  3028. // var wg sync.WaitGroup
  3029. // for _, old := range fpdOldDataList {
  3030. // for _, fpd := range fpdDataList {
  3031. // wg.Add(1)
  3032. // go func(old, fpd map[string]interface{}) {
  3033. // updateLppandList := make([]*lpplandtl1, 0)
  3034. // defer wg.Done()
  3035. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3036. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3037. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3038. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3039. // // if weight > oldweight {
  3040. // // return
  3041. // // }
  3042. // var w float64
  3043. // var status int
  3044. // if weight < oldweight {
  3045. // if weight >= 0 {
  3046. // return
  3047. // }
  3048. // w = weight
  3049. // status = 0
  3050. // } else {
  3051. // if oldweight > 0 {
  3052. // return
  3053. // }
  3054. // w = weight
  3055. // status = 1
  3056. // }
  3057. // // fweight = w
  3058. // for _, lpp := range lpplanList {
  3059. // var fweight float64
  3060. // var lweight float64
  3061. // lpplandtl1List := make([]*lpplandtl1, 0)
  3062. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3063. // for _, lppland := range lpplandtl1AllList {
  3064. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3065. // lpplandtl1List = append(lpplandtl1List, lppland)
  3066. // }
  3067. // }
  3068. // if len(lpplandtl1List) == 0 {
  3069. // continue
  3070. // }
  3071. // for _, lppland := range lpplandtl1List {
  3072. // lweight += lppland.Lweight
  3073. // }
  3074. // if status == 0 {
  3075. // if lweight <= 0 {
  3076. // continue
  3077. // }
  3078. // } else {
  3079. // if lpp.Maxweight <= lweight {
  3080. // continue
  3081. // }
  3082. // }
  3083. // for _, lppland := range lpplandtl1List {
  3084. // if fpdid == lppland.Fpdid {
  3085. // if status == 1 {
  3086. // // if w <= lppland.Lweight {
  3087. // if lpp.Maxweight <= lweight {
  3088. // continue
  3089. // }
  3090. // if w+lweight <= lpp.Maxweight {
  3091. // lppland.Lweight += w
  3092. // lweight += w
  3093. // fweight += w
  3094. // w = 0
  3095. // } else {
  3096. // w = w - (lpp.Maxweight - lweight)
  3097. // n := (lpp.Maxweight - lweight)
  3098. // lppland.Lweight = lppland.Lweight + n
  3099. // lweight += n
  3100. // fweight += n
  3101. // }
  3102. // } else {
  3103. // if lppland.Lweight == 0 {
  3104. // continue
  3105. // }
  3106. // if w+lppland.Lweight >= 0 {
  3107. // lppland.Lweight = lppland.Lweight + w
  3108. // lweight = lweight + w
  3109. // fweight = fweight + w
  3110. // w = 0
  3111. // } else {
  3112. // w = w + lppland.Lweight
  3113. // lweight = lweight - lppland.Lweight
  3114. // fweight = fweight - lppland.Lweight
  3115. // lppland.Lweight = 0
  3116. // }
  3117. // }
  3118. // updateLppandList = append(updateLppandList, lppland)
  3119. // break
  3120. // }
  3121. // }
  3122. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3123. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3124. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3125. // if err != nil {
  3126. // // tx.Rollback()
  3127. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3128. // return
  3129. // }
  3130. // for _, lppland := range updateLppandList {
  3131. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3132. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3133. // if err != nil {
  3134. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3135. // // tx.Rollback()
  3136. // logs.Error(err, 3)
  3137. // return
  3138. // }
  3139. // // defer wg.Done()
  3140. // }
  3141. // updateLppandList = []*lpplandtl1{}
  3142. // if w == 0 {
  3143. // break
  3144. // }
  3145. // }
  3146. // }
  3147. // }(old, fpd)
  3148. // }
  3149. // }
  3150. // wg.Wait()
  3151. }
  3152. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3153. if err != nil {
  3154. logs.Error(err)
  3155. appG.Response(http.StatusOK, e.ERROR, false)
  3156. return
  3157. }
  3158. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3159. if err != nil {
  3160. logs.Error(err)
  3161. appG.Response(http.StatusOK, e.ERROR, false)
  3162. return
  3163. }
  3164. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3165. if err != nil {
  3166. logs.Error(err)
  3167. appG.Response(http.StatusOK, e.ERROR, false)
  3168. return
  3169. }
  3170. now := createdate
  3171. // for _, oldFpd := range oldFpdDataList {
  3172. for _, newFpd := range newFpdDataList {
  3173. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3174. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3175. // go func() {
  3176. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3177. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3178. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3179. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3180. if err != nil {
  3181. logs.Error(err)
  3182. appG.Response(http.StatusOK, e.ERROR, false)
  3183. return
  3184. }
  3185. // }()
  3186. }
  3187. // break
  3188. // }
  3189. // }
  3190. // }
  3191. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3192. for _, newLpplandtl1 := range newLpplandtl1List {
  3193. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3194. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3195. // go func() {
  3196. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3197. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3198. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3199. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3200. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3201. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3202. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3203. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3204. if err != nil {
  3205. logs.Error(err)
  3206. appG.Response(http.StatusOK, e.ERROR, false)
  3207. return
  3208. }
  3209. // }()
  3210. // }
  3211. // break
  3212. // }
  3213. // }
  3214. }
  3215. // for _, oldFeedp := range oldFeedpList {
  3216. for _, newFeedp := range newFeedpList {
  3217. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3218. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3219. // go func() {
  3220. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3221. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3222. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3223. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3224. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3225. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3226. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3227. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3228. if err != nil {
  3229. logs.Error(err)
  3230. appG.Response(http.StatusOK, e.ERROR, false)
  3231. return
  3232. }
  3233. }
  3234. // ,,parammaps["ftid"])
  3235. // surplus, surplusId, id, pastureId string
  3236. // FtdetailSurplusFt(parammaps["ftid"].)
  3237. ftList1, err := tx.SQL(` SELECT
  3238. f.id,
  3239. f.surplus surplusId,
  3240. f.pastureid,
  3241. s.surplus
  3242. FROM
  3243. feedtemplet f
  3244. JOIN surplus s ON s.id = f.surplus
  3245. WHERE
  3246. f.id = ?`, parammaps["ftid"]).QueryString()
  3247. for _, ft := range ftList1 {
  3248. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3249. }
  3250. appG.Response(http.StatusOK, e.SUCCESS, true)
  3251. }
  3252. type lpplandtlInfo struct {
  3253. Id int64 `xorm:"id"`
  3254. Pastureid int64 `xorm:"pastureid"`
  3255. Lppid int64 `xorm:"lppid"`
  3256. Barid int64 `xorm:"barid"`
  3257. Barname string `xorm:"barname"`
  3258. Fpdid int64 `xorm:"fpdid"`
  3259. Fttype int64 `xorm:"fttype"`
  3260. Lweight float64 `xorm:"lweight"`
  3261. Sort int64 `xorm:"sort"`
  3262. Tmrid int64 `xorm:"tmrid"`
  3263. Tmrname string `xorm:"tmrname"`
  3264. Cowcount int64 `xorm:"cowcount"`
  3265. Ccountradio float64 `xorm:"ccountradio"`
  3266. Background string `xorm:"background"`
  3267. Lweighthis float64 `xorm:"lweighthis"`
  3268. Maxweight float64 `xorm:"maxweight"`
  3269. }
  3270. func UpdateFpdetailBar(c *gin.Context) {
  3271. appG := app.Gin{C: c}
  3272. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3273. fsion := gofasion.NewFasion(string(dataByte))
  3274. pastureid := fsion.Get("pastureid").ValueStr()
  3275. id := fsion.Get("id").ValueStr()
  3276. tx := restful.Engine.NewSession()
  3277. tx.Begin()
  3278. 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 `,
  3279. pastureid, id).Query().List()
  3280. if err != nil {
  3281. logs.Error(err)
  3282. }
  3283. for _, fpd := range fpdList {
  3284. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3285. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3286. pastureid, fpd["id"]).Query().List()
  3287. if err != nil {
  3288. tx.Rollback()
  3289. logs.Error(err)
  3290. appG.Response(http.StatusOK, e.ERROR, false)
  3291. return
  3292. }
  3293. var lweight float64
  3294. for _, lppland := range lpplandList {
  3295. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3296. lweight += lweight1
  3297. }
  3298. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3299. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3300. if fpdweight >= ptuse && lweight == ptuse {
  3301. continue
  3302. } else {
  3303. if lweight <= fpdweight {
  3304. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3305. if err != nil {
  3306. tx.Rollback()
  3307. logs.Error(err)
  3308. appG.Response(http.StatusOK, e.ERROR, false)
  3309. return
  3310. }
  3311. } else {
  3312. weight := fpdweight - lweight
  3313. for _, lppland := range lpplandList {
  3314. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3315. if weight >= lpplandlweight {
  3316. weight = weight - lpplandlweight
  3317. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3318. if err != nil {
  3319. tx.Rollback()
  3320. logs.Error(err)
  3321. appG.Response(http.StatusOK, e.ERROR, false)
  3322. return
  3323. }
  3324. } else {
  3325. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3326. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3327. // if err != nil {
  3328. // tx.Rollback()
  3329. // logs.Error(err)
  3330. // appG.Response(http.StatusOK, e.ERROR, false)
  3331. // return
  3332. // }
  3333. weight = 0
  3334. break
  3335. }
  3336. }
  3337. }
  3338. }
  3339. }
  3340. fsionData := fsion.Get("data").Array()
  3341. for _, list := range fsionData {
  3342. ftmap := make(map[string]interface{})
  3343. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3344. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3345. ftmap["times"] = list.Get("times").ValueInt64()
  3346. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3347. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3348. // fmt.Println(ftmap)
  3349. // /*
  3350. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3351. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3352. if count == 1 {
  3353. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3354. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3355. if err != nil {
  3356. tx.Rollback()
  3357. logs.Error(err)
  3358. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3359. return
  3360. }
  3361. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3362. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3363. if err != nil {
  3364. tx.Rollback()
  3365. logs.Error(err)
  3366. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3367. return
  3368. }
  3369. }
  3370. // */
  3371. fpdDataList, err := tx.SQL(`
  3372. 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 ,
  3373. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3374. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3375. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3376. if err != nil {
  3377. tx.Rollback()
  3378. logs.Error(err)
  3379. }
  3380. for _, fpd := range fpdDataList {
  3381. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3382. fttype := -1
  3383. if fpd["fttype"].(string) == "1" {
  3384. fttype = 1
  3385. }
  3386. var fweight float64
  3387. var lweight float64
  3388. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3389. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3390. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3391. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3392. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3393. join tmr t on t.id = lpp.tmrid
  3394. where lppland.fpdid =?
  3395. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3396. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3397. if err != nil {
  3398. tx.Rollback()
  3399. logs.Error(err)
  3400. }
  3401. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3402. var w float64
  3403. var status int
  3404. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3405. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3406. if weight >= 0 {
  3407. continue
  3408. }
  3409. w = weight
  3410. status = 0
  3411. } else {
  3412. // continue
  3413. if weight <= 0 {
  3414. continue
  3415. }
  3416. w = weight
  3417. status = 1
  3418. }
  3419. // for _, lppland := range lpplandtl1List {
  3420. // lweight += lppland.Lweight
  3421. // }
  3422. for _, lppland := range lpplandtl1List {
  3423. lpplandInfo := new(lpplandtlInfo)
  3424. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3425. lweight = lpplandInfo.Lweight
  3426. if status == 1 {
  3427. // if w <= lppland.Lweight {
  3428. if lppland.Maxweight <= lweight {
  3429. continue
  3430. }
  3431. if w+lweight <= lppland.Maxweight {
  3432. lppland.Lweight += w
  3433. lweight += w
  3434. fweight += w
  3435. w = 0
  3436. } else {
  3437. w = w - (lppland.Maxweight - lweight)
  3438. n := (lppland.Maxweight - lweight)
  3439. lppland.Lweight = lppland.Lweight + n
  3440. lweight += n
  3441. fweight += n
  3442. }
  3443. } else {
  3444. if lppland.Lweight == 0 {
  3445. continue
  3446. }
  3447. if w+lppland.Lweight >= 0 {
  3448. lppland.Lweight = lppland.Lweight + w
  3449. lweight = lweight + w
  3450. fweight = fweight + w
  3451. w = 0
  3452. } else {
  3453. w = w + lppland.Lweight
  3454. lweight = lweight - lppland.Lweight
  3455. fweight = fweight - lppland.Lweight
  3456. lppland.Lweight = 0
  3457. }
  3458. }
  3459. if lppland.Lweight > 0 {
  3460. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3461. if err != nil {
  3462. tx.Rollback()
  3463. logs.Error(err)
  3464. return
  3465. }
  3466. } else {
  3467. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3468. if err != nil {
  3469. tx.Rollback()
  3470. logs.Error(err)
  3471. return
  3472. }
  3473. }
  3474. if w == 0 {
  3475. break
  3476. }
  3477. // break
  3478. }
  3479. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3480. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3481. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3482. if err != nil {
  3483. tx.Rollback()
  3484. logs.Error(err)
  3485. }
  3486. if w == 0 {
  3487. break
  3488. }
  3489. }
  3490. }
  3491. }
  3492. tx.Commit()
  3493. now := time.Now()
  3494. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3495. if err != nil {
  3496. logs.Error(err)
  3497. appG.Response(http.StatusOK, e.ERROR, false)
  3498. return
  3499. }
  3500. for _, newLpplandtl1 := range newLpplandtl1List {
  3501. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3502. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3503. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3504. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3505. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3506. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3507. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3508. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3509. if err != nil {
  3510. logs.Error(err)
  3511. appG.Response(http.StatusOK, e.ERROR, false)
  3512. return
  3513. }
  3514. }
  3515. appG.Response(http.StatusOK, e.SUCCESS, true)
  3516. }
  3517. func GetProcessAnalysis(c *gin.Context) {
  3518. appG := app.Gin{C: c}
  3519. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3520. fsion := gofasion.NewFasion(string(dataByte))
  3521. sqlnamestr := fsion.Get("name").ValueStr()
  3522. offset := fsion.Get("offset").ValueDefaultInt(0)
  3523. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3524. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3525. parammaps := fsion.Get("parammaps")
  3526. tx := restful.Engine.NewSession()
  3527. err := tx.Begin()
  3528. defer func() {
  3529. switch {
  3530. case err != nil:
  3531. logging.Error("tx.Begin 事务启动失败__error:", err)
  3532. if tx != nil {
  3533. tx.Rollback()
  3534. }
  3535. default:
  3536. if tx != nil {
  3537. err = tx.Commit()
  3538. }
  3539. }
  3540. if tx != nil {
  3541. tx.Close()
  3542. }
  3543. }()
  3544. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3545. s_params := make([]interface{}, 0)
  3546. paramslist := strings.Split(p, ",")
  3547. if len(paramslist) > 0 && p != "" {
  3548. for _, value := range paramslist {
  3549. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3550. if tempv, exists := c.Get("jwt_username"); exists {
  3551. s_params = append(s_params, tempv.(string))
  3552. } else {
  3553. s_params = append(s_params, "")
  3554. }
  3555. } else {
  3556. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3557. }
  3558. }
  3559. }
  3560. tmrtnameStr := ""
  3561. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3562. if len(tmrtnameStr) == 0 {
  3563. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3564. } else {
  3565. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3566. }
  3567. }
  3568. if len(tmrtnameStr) > 0 {
  3569. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3570. }
  3571. sql += " ORDER BY d.intime"
  3572. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3573. if err != nil {
  3574. logging.Error("GetDataByName err: ", err)
  3575. msg := geterrmsg(err.Error())
  3576. appG.Response(http.StatusOK, e.ERROR, msg)
  3577. } else {
  3578. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3579. }
  3580. }
  3581. func UpdateFeedtempletStatus(c *gin.Context) {
  3582. appG := app.Gin{C: c}
  3583. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3584. fsion := gofasion.NewFasion(string(dataByte))
  3585. parammaps := fsion.Get("parammaps")
  3586. tx := restful.Engine.NewSession()
  3587. tx.Begin()
  3588. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3589. if err != nil {
  3590. tx.Rollback()
  3591. logs.Error(err)
  3592. appG.Response(http.StatusOK, e.ERROR, err)
  3593. return
  3594. }
  3595. tx.Commit()
  3596. appG.Response(http.StatusOK, e.SUCCESS, true)
  3597. }
  3598. func AddFtdry(c *gin.Context) {
  3599. appG := app.Gin{C: c}
  3600. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3601. fsion := gofasion.NewFasion(string(dataByte))
  3602. sqlnamestr := fsion.Get("name").ValueStr()
  3603. s_params := make([]interface{}, 0)
  3604. tx := restful.Engine.NewSession()
  3605. err := tx.Begin()
  3606. defer func() {
  3607. switch {
  3608. case err != nil:
  3609. if tx != nil {
  3610. tx.Rollback()
  3611. }
  3612. default:
  3613. if tx != nil {
  3614. err = tx.Commit()
  3615. }
  3616. }
  3617. if tx != nil {
  3618. tx.Close()
  3619. }
  3620. }()
  3621. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3622. if sql != "" {
  3623. parammaps := fsion.Get("parammaps")
  3624. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3625. paramslist := strings.Split(p, ",")
  3626. if len(paramslist) > 0 && p != "" {
  3627. for _, value := range paramslist {
  3628. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3629. if tempv, exists := c.Get("jwt_username"); exists {
  3630. s_params = append(s_params, tempv.(string))
  3631. } else {
  3632. s_params = append(s_params, "")
  3633. }
  3634. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3635. ids, err := setting.SnowIds.NextId()
  3636. if err != nil {
  3637. ids = time.Now().UnixNano()
  3638. logging.Info("create SnowIds err", err)
  3639. }
  3640. s_params = append(s_params, ids)
  3641. } else {
  3642. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3643. }
  3644. }
  3645. }
  3646. var actweight float64
  3647. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3648. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3649. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3650. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3651. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3652. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3653. 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()
  3654. if err != nil {
  3655. logging.Error("AddFtdry err: ", err)
  3656. msg := geterrmsg(err.Error())
  3657. appG.Response(http.StatusOK, e.ERROR, msg)
  3658. }
  3659. if len(actweightList) > 0 {
  3660. for _, item := range actweightList {
  3661. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3662. if err != nil {
  3663. logging.Error("AddFtdry err: ", err)
  3664. msg := geterrmsg(err.Error())
  3665. appG.Response(http.StatusOK, e.ERROR, msg)
  3666. }
  3667. actweight = fl
  3668. }
  3669. } else {
  3670. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3671. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3672. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3673. if err != nil {
  3674. logging.Error("AddFtdry err: ", err)
  3675. msg := geterrmsg(err.Error())
  3676. appG.Response(http.StatusOK, e.ERROR, msg)
  3677. }
  3678. for _, item := range dryList {
  3679. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3680. if err != nil {
  3681. logging.Error("AddFtdry err: ", err)
  3682. msg := geterrmsg(err.Error())
  3683. appG.Response(http.StatusOK, e.ERROR, msg)
  3684. }
  3685. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3686. }
  3687. }
  3688. if sqlnamestr == "insertFtdry" {
  3689. s_params = append(s_params, actweight)
  3690. } else if sqlnamestr == "updateFtdry" {
  3691. sql = fmt.Sprintf(sql, actweight)
  3692. }
  3693. queryData, err := execDataBySqlT(sql, s_params, tx)
  3694. if err != nil {
  3695. logging.Error("AddFtdry err: ", err)
  3696. msg := geterrmsg(err.Error())
  3697. appG.Response(http.StatusOK, e.ERROR, msg)
  3698. } else {
  3699. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3700. }
  3701. } else {
  3702. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3703. }
  3704. }
  3705. func CheckDates(c *gin.Context) {
  3706. tx := restful.Engine.NewSession()
  3707. defer tx.Close()
  3708. appG := app.Gin{C: c}
  3709. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3710. tempval_ := make(map[string]interface{})
  3711. tempCommon := make(map[string]interface{})
  3712. tempval := make([]map[string]interface{}, 0)
  3713. err := json.Unmarshal(dataByte, &tempval_)
  3714. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3715. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3716. if err != nil {
  3717. } else {
  3718. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3719. tempCommon = v
  3720. }
  3721. if v, ok := tempval_["data"].([]interface{}); ok {
  3722. for _, Tvalue := range v {
  3723. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3724. tempval = append(tempval, v1)
  3725. }
  3726. }
  3727. }
  3728. if err == nil {
  3729. if tempv, exists := c.Get("jwt_username"); exists {
  3730. tempCommon["jwt_username"] = tempv.(string)
  3731. }
  3732. for _, paramvalue := range tempval {
  3733. if _, ok := paramvalue["resultname"]; !ok {
  3734. paramvalue["resultname"] = paramvalue["name"]
  3735. }
  3736. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3737. if err != nil {
  3738. logging.Error("ExecDataParam error:", err)
  3739. }
  3740. }
  3741. if err == nil {
  3742. vmsg := ""
  3743. for _, item := range tempval {
  3744. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3745. for _, childrenList := range list.([]interface{}) {
  3746. for k, children := range childrenList.(map[string]interface{}) {
  3747. if k != "children" {
  3748. continue
  3749. }
  3750. for _, v := range children.([]map[string]interface{}) {
  3751. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3752. if k1 == "list" {
  3753. for _, v2 := range v1.([]map[string]interface{}) {
  3754. if v2["vmsg"].(string) != "1" {
  3755. if len(vmsg) == 0 {
  3756. vmsg = v2["vmsg"].(string)
  3757. } else {
  3758. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3759. }
  3760. }
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. if len(vmsg) > 0 {
  3770. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3771. } else {
  3772. appG.Response(http.StatusOK, e.SUCCESS, true)
  3773. }
  3774. } else {
  3775. msg := geterrmsg(err.Error())
  3776. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3777. }
  3778. }
  3779. }
  3780. if err != nil {
  3781. msg := geterrmsg(err.Error())
  3782. appG.Response(http.StatusOK, e.ERROR, msg)
  3783. }
  3784. }
  3785. 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) {
  3786. sqlname := fasion["name"].(string)
  3787. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3788. if v, ok := fasion["type"]; ok {
  3789. sqltype = v.(string)
  3790. }
  3791. sql := ""
  3792. p := ""
  3793. s_params := make([]interface{}, 0)
  3794. if sqltype != "" {
  3795. sql, p = restful.GetSqlByName(sqlname, tx)
  3796. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3797. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3798. paramslist := strings.Split(p, ",")
  3799. if len(paramslist) > 0 && p != "" {
  3800. for _, value := range paramslist {
  3801. ss := ""
  3802. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3803. ids, err := setting.SnowIds.NextId()
  3804. if err != nil {
  3805. ids = time.Now().UnixNano()
  3806. logging.Info("create SnowIds err", err)
  3807. }
  3808. s_params = append(s_params, ids)
  3809. } else {
  3810. if ss == "" && CommonParamMap != nil {
  3811. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3812. ss = valuestring
  3813. tempstrb := strings.IndexAny(valuestring, "@")
  3814. tempstre := strings.IndexAny(valuestring, ".")
  3815. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3816. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3817. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3818. }
  3819. } else {
  3820. ss = ""
  3821. }
  3822. }
  3823. }
  3824. if ss == "" && ParentParamMap != nil {
  3825. ss = getParamValue_(v, value, ParentParamMap)
  3826. }
  3827. if ss == "" && sameParamMap != nil {
  3828. ss = getParamValue(v, value, sameParamMap)
  3829. }
  3830. if ss == "" && ParamMap != nil {
  3831. ss = getParamValue(v, value, ParamMap)
  3832. }
  3833. s_params = append(s_params, ss)
  3834. }
  3835. }
  3836. }
  3837. }
  3838. }
  3839. if sql == "" {
  3840. sqltype = ""
  3841. }
  3842. if sql != "" {
  3843. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3844. if err != nil {
  3845. return nil, err
  3846. }
  3847. // fmt.Println(tempValParam)
  3848. return tempValParam.(map[string]interface{}), nil
  3849. } else {
  3850. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3851. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3852. if err != nil {
  3853. return nil, err
  3854. }
  3855. return nil, err
  3856. }
  3857. }
  3858. return nil, nil
  3859. }
  3860. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3861. var err error
  3862. subarray, ok := fasion["children"]
  3863. if ok {
  3864. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3865. tempVal_arrary := make([]map[string]interface{}, 0)
  3866. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3867. tempVal_ := make(map[string]interface{})
  3868. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3869. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3870. } else {
  3871. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3872. }
  3873. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3874. if err != nil {
  3875. return err
  3876. }
  3877. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3878. }
  3879. v.(map[string]interface{})["children"] = tempVal_arrary
  3880. }
  3881. }
  3882. return nil
  3883. }
  3884. func FpdImportExcel(c *gin.Context) {
  3885. appG := app.Gin{C: c}
  3886. inputdata := ""
  3887. c.Request.ParseForm()
  3888. params := c.Request.Form
  3889. file, _, err := c.Request.FormFile("file")
  3890. if err != nil {
  3891. appG.Response(http.StatusOK, e.ERROR, err)
  3892. return
  3893. }
  3894. sqlnamestrs := params.Get("name")
  3895. sheetname := params.Get("sheetname")
  3896. pastureid := params.Get("pastureid")
  3897. // importParams := params.Get("importParams")
  3898. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3899. // 必输项参数 (字符串格式 "field1,field2,field3")
  3900. requiredParams := params.Get("requiredParams")
  3901. // 日期参数
  3902. dateParams := params.Get("dateParams")
  3903. // 数字参数
  3904. numParams := params.Get("numParams")
  3905. //将字符串分割开
  3906. dateParamslist := strings.Split(dateParams, ",")
  3907. requiredParamslist := strings.Split(requiredParams, ",")
  3908. numParamslist := strings.Split(numParams, ",")
  3909. queryData := make([]interface{}, 0)
  3910. sqlslist := strings.Split(sqlnamestrs, ",")
  3911. xlsx1, err := excelize.OpenReader(file)
  3912. if err != nil {
  3913. fmt.Println(err)
  3914. return
  3915. }
  3916. ok := 0
  3917. error := 0
  3918. isdone := true
  3919. tx := restful.Engine.NewSession()
  3920. defer tx.Close()
  3921. languageStatus := GetLanguageStatus()
  3922. if languageStatus == "0" {
  3923. 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
  3924. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3925. if err != nil {
  3926. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3927. return
  3928. }
  3929. rows := xlsx1.GetRows(sheetname)
  3930. // 限制10000条,多余的截取掉
  3931. if len(rows) > 10000 {
  3932. rows = rows[:10000]
  3933. }
  3934. dataList := make(map[string][]*upFpdetail, 0)
  3935. for i, row := range rows {
  3936. if i > 0 {
  3937. entry := make(map[string]interface{})
  3938. outentry := make(map[string]interface{})
  3939. for j, colCell := range rows[0] {
  3940. for k, colCell1 := range row {
  3941. if j == k {
  3942. outentry[colCell] = colCell1
  3943. entry[colCell] = colCell1
  3944. }
  3945. }
  3946. }
  3947. inputdata = ""
  3948. a := ""
  3949. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3950. //校验日期格式
  3951. for _, v := range dateParamslist {
  3952. if v == "" {
  3953. continue
  3954. }
  3955. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3956. dtime, err := TransfTime(d.(string))
  3957. if err != nil {
  3958. a = strings.Trim(v, " ")
  3959. break
  3960. }
  3961. outentry[strings.Trim(v, " ")] = dtime
  3962. }
  3963. }
  3964. if a != "" {
  3965. outentry["error_msg"] = a + " 格式错误"
  3966. error++
  3967. queryData = append(queryData, outentry)
  3968. continue
  3969. }
  3970. a = ""
  3971. //校验必填格式
  3972. for _, v := range requiredParamslist {
  3973. if v == "" {
  3974. continue
  3975. }
  3976. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3977. a = strings.Trim(v, " ")
  3978. break
  3979. }
  3980. }
  3981. if a != "" {
  3982. outentry["error_msg"] = a + " 未填或格式错误"
  3983. error++
  3984. queryData = append(queryData, outentry)
  3985. continue
  3986. }
  3987. a = ""
  3988. //校验数字格式
  3989. for _, v := range numParamslist {
  3990. if v == "" {
  3991. continue
  3992. }
  3993. d, ok := outentry[strings.Trim(v, " ")]
  3994. if !ok || d == "" {
  3995. outentry[strings.Trim(v, " ")] = 0
  3996. } else {
  3997. var fl float64
  3998. switch d.(type) {
  3999. case string:
  4000. fl, err = strconv.ParseFloat(d.(string), 64)
  4001. }
  4002. if err != nil || fl < 0 {
  4003. a = strings.Trim(v, " ")
  4004. break
  4005. }
  4006. }
  4007. }
  4008. if a != "" {
  4009. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4010. error++
  4011. queryData = append(queryData, outentry)
  4012. continue
  4013. }
  4014. errExist := false
  4015. for _, sqlnamestr := range sqlslist {
  4016. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4017. paramslist := strings.Split(paramslists, ",")
  4018. if len(paramslist) > 0 {
  4019. s_params := make([]interface{}, 0)
  4020. for _, value := range paramslist {
  4021. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4022. if tempv, exists := c.Get("jwt_username"); exists {
  4023. s_params = append(s_params, tempv.(string))
  4024. } else {
  4025. s_params = append(s_params, "")
  4026. }
  4027. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4028. s_params = append(s_params, pastureid)
  4029. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4030. ids, err := setting.SnowIds.NextId()
  4031. if err != nil {
  4032. ids = time.Now().UnixNano()
  4033. logging.Info("create SnowIds err", err)
  4034. }
  4035. s_params = append(s_params, ids)
  4036. } else {
  4037. if outentry[strings.Trim(value, " ")] == nil {
  4038. s_params = append(s_params, "")
  4039. } else {
  4040. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4041. }
  4042. }
  4043. }
  4044. outentry["input"] = inputdata
  4045. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4046. if err != nil {
  4047. errExist = true
  4048. // if tx != nil {
  4049. // tx.Rollback()
  4050. // }
  4051. // if tx != nil {
  4052. // tx.Close()
  4053. // }
  4054. msg := geterrmsg(err.Error())
  4055. outentry["error_msg"] = msg
  4056. error++
  4057. queryData = append(queryData, outentry)
  4058. isdone = true
  4059. break
  4060. } else {
  4061. if len(returnmsgmap1) > 0 {
  4062. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4063. // if tx != nil {
  4064. // tx.Rollback()
  4065. // }
  4066. // if tx != nil {
  4067. // tx.Close()
  4068. // }
  4069. msg := geterrmsg(va.(string))
  4070. outentry["error_msg"] = msg
  4071. error++
  4072. queryData = append(queryData, outentry)
  4073. isdone = true
  4074. break
  4075. }
  4076. }
  4077. isdone = false
  4078. }
  4079. }
  4080. }
  4081. fmt.Println(outentry["栏舍名称"])
  4082. if !errExist {
  4083. dataexcel := make(map[string]interface{}, 0)
  4084. if _, ok := outentry["栏舍名称"]; ok {
  4085. dataexcel["barname"] = outentry["栏舍名称"]
  4086. }
  4087. if _, ok := outentry["实际牛头数"]; ok {
  4088. dataexcel["ccount"] = outentry["实际牛头数"]
  4089. }
  4090. // if _, ok := outentry["实际羊只数"]; ok {
  4091. // dataexcel["ccount"] = outentry["实际羊只数"]
  4092. // }
  4093. if _, ok := outentry["系数(%)"]; ok {
  4094. dataexcel["ratio"] = outentry["系数(%)"]
  4095. }
  4096. if _, ok := outentry["配方模板"]; ok {
  4097. dataexcel["ftname"] = outentry["配方模板"]
  4098. }
  4099. if _, ok := outentry["补料配方"]; ok {
  4100. dataexcel["ptsfname"] = outentry["补料配方"]
  4101. }
  4102. if _, ok := outentry["第一班比例(%)"]; ok {
  4103. dataexcel["1"] = outentry["第一班比例(%)"]
  4104. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4105. dataexcel["1"] = 0
  4106. }
  4107. } else {
  4108. dataexcel["1"] = 0
  4109. }
  4110. if _, ok := outentry["第二班比例(%)"]; ok {
  4111. dataexcel["2"] = outentry["第二班比例(%)"]
  4112. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4113. dataexcel["2"] = 0
  4114. }
  4115. } else {
  4116. dataexcel["2"] = 0
  4117. }
  4118. if _, ok := outentry["第三班比例(%)"]; ok {
  4119. dataexcel["3"] = outentry["第三班比例(%)"]
  4120. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4121. dataexcel["3"] = 0
  4122. }
  4123. } else {
  4124. dataexcel["3"] = 0
  4125. }
  4126. if _, ok := outentry["第四班比例(%)"]; ok {
  4127. dataexcel["4"] = outentry["第四班比例(%)"]
  4128. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4129. dataexcel["4"] = 0
  4130. }
  4131. } else {
  4132. dataexcel["4"] = 0
  4133. }
  4134. if _, ok := outentry["第五班比例(%)"]; ok {
  4135. dataexcel["5"] = outentry["第五班比例(%)"]
  4136. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4137. dataexcel["5"] = 0
  4138. }
  4139. } else {
  4140. dataexcel["5"] = 0
  4141. }
  4142. if _, ok := outentry["第六班比例(%)"]; ok {
  4143. dataexcel["6"] = outentry["第六班比例(%)"]
  4144. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4145. dataexcel["6"] = 0
  4146. }
  4147. } else {
  4148. dataexcel["6"] = 0
  4149. }
  4150. dataWeight := new(models.FpdetailEdit)
  4151. // dataWeightMap := make(map[string]interface{}, 0)
  4152. if _, ok := outentry["第一班重量"]; ok {
  4153. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4154. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4155. }
  4156. if _, ok := outentry["第二班重量"]; ok {
  4157. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4158. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4159. }
  4160. if _, ok := outentry["第三班重量"]; ok {
  4161. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4162. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4163. }
  4164. if _, ok := outentry["第四班重量"]; ok {
  4165. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4166. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4167. }
  4168. if _, ok := outentry["第五班重量"]; ok {
  4169. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4170. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4171. }
  4172. if _, ok := outentry["第六班重量"]; ok {
  4173. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4174. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4175. }
  4176. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4177. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4178. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4179. // fmt.Println(err)
  4180. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4181. dataWeight.Weight1 = 0
  4182. dataWeight.Weight2 = 0
  4183. dataWeight.Weight3 = 0
  4184. dataWeight.Weight4 = 0
  4185. dataWeight.Weight5 = 0
  4186. dataWeight.Weight6 = 0
  4187. }
  4188. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4189. if weight > 0 {
  4190. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4191. if err != nil {
  4192. logs.Error(err)
  4193. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4194. return
  4195. }
  4196. if !existbar {
  4197. continue
  4198. }
  4199. _, 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()
  4200. if err != nil {
  4201. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4202. return
  4203. }
  4204. _, 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()
  4205. if err != nil {
  4206. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4207. return
  4208. }
  4209. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4210. if err != nil {
  4211. logs.Error(err)
  4212. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4213. return
  4214. }
  4215. if !existft {
  4216. continue
  4217. }
  4218. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4219. if err != nil {
  4220. logs.Error(err)
  4221. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4222. return
  4223. }
  4224. if !ftexist {
  4225. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4226. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4227. if err != nil {
  4228. logs.Error(err)
  4229. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4230. return
  4231. }
  4232. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4233. if err != nil {
  4234. logs.Error(err)
  4235. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4236. return
  4237. }
  4238. }
  4239. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4240. if err != nil {
  4241. logs.Error(err)
  4242. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4243. return
  4244. }
  4245. if !exist {
  4246. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4247. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4248. if err != nil {
  4249. logs.Error(err)
  4250. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4251. return
  4252. }
  4253. }
  4254. var feedpargs []interface{}
  4255. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4256. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4257. if _, ok := dataexcel["ftname"]; ok {
  4258. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4259. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4260. // upFeedpSql += `,ftweight = ? `
  4261. // feedpargs = append(feedpargs, weight)
  4262. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4263. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4264. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4265. } else {
  4266. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4267. }
  4268. if _, ok := dataexcel["ptsfname"]; ok {
  4269. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4270. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4271. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4272. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4273. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4274. } else {
  4275. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4276. }
  4277. upFeedpSql += " where barname = ? and pastureid = ? "
  4278. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4279. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4280. if err != nil {
  4281. logs.Error(err)
  4282. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4283. return
  4284. }
  4285. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4286. if err != nil {
  4287. logs.Error(err)
  4288. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4289. return
  4290. }
  4291. if !exist1 {
  4292. _, 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) `,
  4293. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4294. if err != nil {
  4295. logs.Error(err)
  4296. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4297. return
  4298. }
  4299. }
  4300. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4301. if err != nil {
  4302. logs.Error(err)
  4303. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4304. return
  4305. }
  4306. if !exist2 {
  4307. _, 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) `,
  4308. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4309. if err != nil {
  4310. logs.Error(err)
  4311. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4312. return
  4313. }
  4314. }
  4315. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4316. if err != nil {
  4317. logs.Error(err)
  4318. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4319. return
  4320. }
  4321. if !exist3 {
  4322. _, 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) `,
  4323. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4324. if err != nil {
  4325. logs.Error(err)
  4326. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4327. return
  4328. }
  4329. }
  4330. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4331. if err != nil {
  4332. logs.Error(err)
  4333. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4334. return
  4335. }
  4336. if !exist4 {
  4337. _, 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) `,
  4338. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4339. if err != nil {
  4340. logs.Error(err)
  4341. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4342. return
  4343. }
  4344. }
  4345. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4346. if err != nil {
  4347. logs.Error(err)
  4348. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4349. return
  4350. }
  4351. if !exist5 {
  4352. _, 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) `,
  4353. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4354. if err != nil {
  4355. logs.Error(err)
  4356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4357. return
  4358. }
  4359. }
  4360. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4361. if err != nil {
  4362. logs.Error(err)
  4363. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4364. return
  4365. }
  4366. if !exist6 {
  4367. _, 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) `,
  4368. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4369. if err != nil {
  4370. logs.Error(err)
  4371. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4372. return
  4373. }
  4374. }
  4375. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4376. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4377. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4378. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4379. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4380. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4381. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4382. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4383. and pastureid = ? and times = ?`
  4384. var fpdargs1 []interface{}
  4385. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4386. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4387. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4388. if err != nil {
  4389. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4390. return
  4391. }
  4392. var fpdargs2 []interface{}
  4393. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4394. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4395. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4396. if err != nil {
  4397. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4398. return
  4399. }
  4400. var fpdargs3 []interface{}
  4401. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4402. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4403. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4404. if err != nil {
  4405. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4406. return
  4407. }
  4408. var fpdargs4 []interface{}
  4409. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4410. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4411. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4412. if err != nil {
  4413. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4414. return
  4415. }
  4416. var fpdargs5 []interface{}
  4417. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4418. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4419. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4420. if err != nil {
  4421. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4422. return
  4423. }
  4424. var fpdargs6 []interface{}
  4425. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4426. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4427. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4428. if err != nil {
  4429. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4430. return
  4431. }
  4432. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4433. 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()
  4434. if err != nil {
  4435. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4436. return
  4437. }
  4438. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4439. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4440. upFpdetailList := make([]*upFpdetail, 0)
  4441. for _, newfpd := range newList {
  4442. for _, oldfpd := range oldFpdList {
  4443. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4444. var oldweight, newweight float64
  4445. if oldfpd["weight"] != nil {
  4446. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4447. }
  4448. if newfpd["weight"] != nil {
  4449. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4450. }
  4451. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4452. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4453. Old: oldweight,
  4454. New: newweight,
  4455. Times: newfpd["times"].(int64),
  4456. Ptid: newfpd["ptid"].(int64),
  4457. Fweight: fweight,
  4458. Id: oldfpd["id"].(int64),
  4459. })
  4460. break
  4461. }
  4462. }
  4463. }
  4464. // fmt.Println(dataexcel["barname"])
  4465. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4466. } else {
  4467. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4468. if err != nil {
  4469. logs.Error(err)
  4470. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4471. return
  4472. }
  4473. if !existbar {
  4474. continue
  4475. }
  4476. _, 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()
  4477. if err != nil {
  4478. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4479. return
  4480. }
  4481. _, 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()
  4482. if err != nil {
  4483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4484. return
  4485. }
  4486. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4487. if err != nil {
  4488. logs.Error(err)
  4489. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4490. return
  4491. }
  4492. if !existft {
  4493. continue
  4494. }
  4495. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4496. if err != nil {
  4497. logs.Error(err)
  4498. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4499. return
  4500. }
  4501. if !ftexist {
  4502. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4503. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4504. if err != nil {
  4505. logs.Error(err)
  4506. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4507. return
  4508. }
  4509. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4510. if err != nil {
  4511. logs.Error(err)
  4512. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4513. return
  4514. }
  4515. }
  4516. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4517. if err != nil {
  4518. logs.Error(err)
  4519. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4520. return
  4521. }
  4522. if !exist {
  4523. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4524. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4525. if err != nil {
  4526. logs.Error(err)
  4527. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4528. return
  4529. }
  4530. }
  4531. var feedpargs []interface{}
  4532. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4533. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4534. if _, ok := dataexcel["ftname"]; ok {
  4535. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4536. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4537. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4538. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4539. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4540. } else {
  4541. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4542. }
  4543. if _, ok := dataexcel["ptsfname"]; ok {
  4544. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4545. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4546. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4547. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4548. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4549. } else {
  4550. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4551. }
  4552. upFeedpSql += " where barname = ? and pastureid = ? "
  4553. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4554. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4555. if err != nil {
  4556. logs.Error(err)
  4557. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4558. return
  4559. }
  4560. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4561. if err != nil {
  4562. logs.Error(err)
  4563. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4564. return
  4565. }
  4566. if !exist1 {
  4567. _, 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) `,
  4568. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4569. if err != nil {
  4570. logs.Error(err)
  4571. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4572. return
  4573. }
  4574. }
  4575. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4576. if err != nil {
  4577. logs.Error(err)
  4578. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4579. return
  4580. }
  4581. if !exist2 {
  4582. _, 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) `,
  4583. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4584. if err != nil {
  4585. logs.Error(err)
  4586. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4587. return
  4588. }
  4589. }
  4590. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4591. if err != nil {
  4592. logs.Error(err)
  4593. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4594. return
  4595. }
  4596. if !exist3 {
  4597. _, 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) `,
  4598. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4599. if err != nil {
  4600. logs.Error(err)
  4601. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4602. return
  4603. }
  4604. }
  4605. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4606. if err != nil {
  4607. logs.Error(err)
  4608. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4609. return
  4610. }
  4611. if !exist4 {
  4612. _, 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) `,
  4613. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4614. if err != nil {
  4615. logs.Error(err)
  4616. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4617. return
  4618. }
  4619. }
  4620. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4621. if err != nil {
  4622. logs.Error(err)
  4623. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4624. return
  4625. }
  4626. if !exist5 {
  4627. _, 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) `,
  4628. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4629. if err != nil {
  4630. logs.Error(err)
  4631. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4632. return
  4633. }
  4634. }
  4635. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4636. if err != nil {
  4637. logs.Error(err)
  4638. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4639. return
  4640. }
  4641. if !exist6 {
  4642. _, 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) `,
  4643. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4644. if err != nil {
  4645. logs.Error(err)
  4646. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4647. return
  4648. }
  4649. }
  4650. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4651. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4652. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4653. and pastureid = ? and times = ?`
  4654. var fpdargs1 []interface{}
  4655. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4656. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4657. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4658. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4659. if err != nil {
  4660. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4661. return
  4662. }
  4663. var fpdargs2 []interface{}
  4664. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4665. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4666. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4667. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4668. if err != nil {
  4669. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4670. return
  4671. }
  4672. var fpdargs3 []interface{}
  4673. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4674. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4675. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4676. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4677. if err != nil {
  4678. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4679. return
  4680. }
  4681. var fpdargs4 []interface{}
  4682. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4683. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4684. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4685. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4686. if err != nil {
  4687. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4688. return
  4689. }
  4690. var fpdargs5 []interface{}
  4691. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4692. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4693. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4694. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4695. if err != nil {
  4696. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4697. return
  4698. }
  4699. var fpdargs6 []interface{}
  4700. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4701. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4702. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4703. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4704. if err != nil {
  4705. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4706. return
  4707. }
  4708. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4709. 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()
  4710. if err != nil {
  4711. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4712. return
  4713. }
  4714. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4715. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4716. upFpdetailList := make([]*upFpdetail, 0)
  4717. for _, newfpd := range newList {
  4718. for _, oldfpd := range oldFpdList {
  4719. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4720. var oldweight, newweight float64
  4721. if oldfpd["weight"] != nil {
  4722. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4723. }
  4724. if newfpd["weight"] != nil {
  4725. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4726. }
  4727. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4728. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4729. Old: oldweight,
  4730. New: newweight,
  4731. Times: newfpd["times"].(int64),
  4732. Ptid: newfpd["ptid"].(int64),
  4733. Fweight: fweight,
  4734. Id: oldfpd["id"].(int64),
  4735. })
  4736. break
  4737. }
  4738. }
  4739. }
  4740. // fmt.Println(dataexcel["barname"])
  4741. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4742. }
  4743. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4744. }
  4745. }
  4746. if !isdone {
  4747. ok++
  4748. isdone = true
  4749. }
  4750. }
  4751. for barname, v := range dataList {
  4752. // for _, v1 := range v {
  4753. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4754. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4755. // if count == 1 {
  4756. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4757. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4758. // if err != nil {
  4759. // logs.Error(err)
  4760. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4761. // return
  4762. // }
  4763. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4764. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4765. // if err != nil {
  4766. // logs.Error(err)
  4767. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4768. // return
  4769. // }
  4770. // }
  4771. // }
  4772. // /*
  4773. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4774. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4775. if err != nil {
  4776. logs.Error(err)
  4777. return
  4778. }
  4779. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4780. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4781. if err != nil {
  4782. logs.Error(err)
  4783. return
  4784. }
  4785. // */
  4786. updateFpdetailByBar(pastureid, barname, v)
  4787. }
  4788. } else {
  4789. 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
  4790. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4791. if err != nil {
  4792. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4793. return
  4794. }
  4795. rows := xlsx1.GetRows(sheetname)
  4796. // 限制10000条,多余的截取掉
  4797. if len(rows) > 10000 {
  4798. rows = rows[:10000]
  4799. }
  4800. dataList := make(map[string][]*upFpdetail, 0)
  4801. for i, row := range rows {
  4802. if i > 0 {
  4803. entry := make(map[string]interface{})
  4804. outentry := make(map[string]interface{})
  4805. for j, colCell := range rows[0] {
  4806. for k, colCell1 := range row {
  4807. if j == k {
  4808. outentry[colCell] = colCell1
  4809. entry[colCell] = colCell1
  4810. }
  4811. }
  4812. }
  4813. inputdata = ""
  4814. a := ""
  4815. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4816. //校验日期格式
  4817. for _, v := range dateParamslist {
  4818. if v == "" {
  4819. continue
  4820. }
  4821. if d, ok := outentry[v]; ok {
  4822. dtime, err := TransfTime(d.(string))
  4823. if err != nil {
  4824. a = v
  4825. break
  4826. }
  4827. outentry[v] = dtime
  4828. }
  4829. }
  4830. if a != "" {
  4831. outentry["error_msg"] = a + " format error"
  4832. error++
  4833. queryData = append(queryData, outentry)
  4834. continue
  4835. }
  4836. a = ""
  4837. //校验必填格式
  4838. for _, v := range requiredParamslist {
  4839. if v == "" {
  4840. continue
  4841. }
  4842. if d, ok := outentry[v]; !ok || d == "" {
  4843. a = v
  4844. break
  4845. }
  4846. }
  4847. if a != "" {
  4848. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4849. error++
  4850. queryData = append(queryData, outentry)
  4851. continue
  4852. }
  4853. a = ""
  4854. //校验数字格式
  4855. for _, v := range numParamslist {
  4856. if v == "" {
  4857. continue
  4858. }
  4859. d, ok := outentry[v]
  4860. if !ok || d == "" {
  4861. outentry[v] = 0
  4862. } else {
  4863. var fl float64
  4864. switch d.(type) {
  4865. case string:
  4866. fl, err = strconv.ParseFloat(d.(string), 64)
  4867. }
  4868. if err != nil || fl < 0 {
  4869. a = v
  4870. break
  4871. }
  4872. }
  4873. }
  4874. if a != "" {
  4875. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4876. error++
  4877. queryData = append(queryData, outentry)
  4878. continue
  4879. }
  4880. errExist := false
  4881. for _, sqlnamestr := range sqlslist {
  4882. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4883. paramslist := strings.Split(paramslists, ",")
  4884. if len(paramslist) > 0 {
  4885. s_params := make([]interface{}, 0)
  4886. for _, value := range paramslist {
  4887. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4888. if tempv, exists := c.Get("jwt_username"); exists {
  4889. s_params = append(s_params, tempv.(string))
  4890. } else {
  4891. s_params = append(s_params, "")
  4892. }
  4893. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4894. s_params = append(s_params, pastureid)
  4895. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4896. ids, err := setting.SnowIds.NextId()
  4897. if err != nil {
  4898. ids = time.Now().UnixNano()
  4899. logging.Info("create SnowIds err", err)
  4900. }
  4901. s_params = append(s_params, ids)
  4902. } else {
  4903. if outentry[strings.Trim(value, " ")] == nil {
  4904. s_params = append(s_params, "")
  4905. } else {
  4906. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4907. }
  4908. }
  4909. }
  4910. outentry["input"] = inputdata
  4911. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4912. if err != nil {
  4913. errExist = true
  4914. // if tx != nil {
  4915. // tx.Rollback()
  4916. // }
  4917. // if tx != nil {
  4918. // tx.Close()
  4919. // }
  4920. msg := geterrmsg(err.Error())
  4921. outentry["error_msg"] = msg
  4922. error++
  4923. queryData = append(queryData, outentry)
  4924. isdone = true
  4925. break
  4926. } else {
  4927. if len(returnmsgmap1) > 0 {
  4928. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4929. // if tx != nil {
  4930. // tx.Rollback()
  4931. // }
  4932. // if tx != nil {
  4933. // tx.Close()
  4934. // }
  4935. msg := geterrmsg(va.(string))
  4936. outentry["error_msg"] = msg
  4937. error++
  4938. queryData = append(queryData, outentry)
  4939. isdone = true
  4940. break
  4941. }
  4942. }
  4943. isdone = false
  4944. }
  4945. }
  4946. }
  4947. if !errExist {
  4948. dataexcel := make(map[string]interface{}, 0)
  4949. if _, ok := outentry["Pen Name"]; ok {
  4950. dataexcel["barname"] = outentry["Pen Name"]
  4951. }
  4952. if _, ok := outentry["Actual Cattle Number"]; ok {
  4953. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4954. }
  4955. if _, ok := outentry["Coefficient(%)"]; ok {
  4956. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4957. }
  4958. if _, ok := outentry["Formula Template"]; ok {
  4959. dataexcel["ftname"] = outentry["Formula Template"]
  4960. }
  4961. if _, ok := outentry["Supplement Formula"]; ok {
  4962. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4963. }
  4964. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4965. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4966. }
  4967. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4968. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4969. }
  4970. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4971. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4972. }
  4973. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4974. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4975. }
  4976. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4977. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4978. }
  4979. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4980. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4981. }
  4982. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4983. if err != nil {
  4984. logs.Error(err)
  4985. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4986. return
  4987. }
  4988. if !existbar {
  4989. continue
  4990. }
  4991. _, 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()
  4992. if err != nil {
  4993. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4994. return
  4995. }
  4996. _, 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()
  4997. if err != nil {
  4998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4999. return
  5000. }
  5001. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5002. if err != nil {
  5003. logs.Error(err)
  5004. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5005. return
  5006. }
  5007. if !existft {
  5008. continue
  5009. }
  5010. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5011. if err != nil {
  5012. logs.Error(err)
  5013. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5014. return
  5015. }
  5016. if !ftexist {
  5017. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5018. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5019. if err != nil {
  5020. logs.Error(err)
  5021. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5022. return
  5023. }
  5024. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5025. if err != nil {
  5026. logs.Error(err)
  5027. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5028. return
  5029. }
  5030. }
  5031. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5032. if err != nil {
  5033. logs.Error(err)
  5034. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5035. return
  5036. }
  5037. if !exist {
  5038. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5039. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5040. if err != nil {
  5041. logs.Error(err)
  5042. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5043. return
  5044. }
  5045. }
  5046. var feedpargs []interface{}
  5047. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5048. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5049. if _, ok := dataexcel["ftname"]; ok {
  5050. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5051. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5052. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5053. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5054. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5055. } else {
  5056. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5057. }
  5058. if _, ok := dataexcel["ptsfname"]; ok {
  5059. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5060. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5061. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5062. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5063. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5064. } else {
  5065. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5066. }
  5067. upFeedpSql += " where barname = ? and pastureid = ? "
  5068. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5069. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5070. if err != nil {
  5071. logs.Error(err)
  5072. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5073. return
  5074. }
  5075. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5076. if err != nil {
  5077. logs.Error(err)
  5078. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5079. return
  5080. }
  5081. if !exist1 {
  5082. _, 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) `,
  5083. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5084. if err != nil {
  5085. logs.Error(err)
  5086. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5087. return
  5088. }
  5089. }
  5090. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5091. if err != nil {
  5092. logs.Error(err)
  5093. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5094. return
  5095. }
  5096. if !exist2 {
  5097. _, 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) `,
  5098. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5099. if err != nil {
  5100. logs.Error(err)
  5101. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5102. return
  5103. }
  5104. }
  5105. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5106. if err != nil {
  5107. logs.Error(err)
  5108. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5109. return
  5110. }
  5111. if !exist3 {
  5112. _, 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) `,
  5113. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5114. if err != nil {
  5115. logs.Error(err)
  5116. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5117. return
  5118. }
  5119. }
  5120. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5121. if err != nil {
  5122. logs.Error(err)
  5123. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5124. return
  5125. }
  5126. if !exist4 {
  5127. _, 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) `,
  5128. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5129. if err != nil {
  5130. logs.Error(err)
  5131. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5132. return
  5133. }
  5134. }
  5135. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5136. if err != nil {
  5137. logs.Error(err)
  5138. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5139. return
  5140. }
  5141. if !exist5 {
  5142. _, 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) `,
  5143. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5144. if err != nil {
  5145. logs.Error(err)
  5146. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5147. return
  5148. }
  5149. }
  5150. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5151. if err != nil {
  5152. logs.Error(err)
  5153. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5154. return
  5155. }
  5156. if !exist6 {
  5157. _, 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) `,
  5158. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5159. if err != nil {
  5160. logs.Error(err)
  5161. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5162. return
  5163. }
  5164. }
  5165. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5166. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5167. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5168. and pastureid = ? and times = ?`
  5169. var fpdargs1 []interface{}
  5170. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5171. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5172. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5173. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5174. if err != nil {
  5175. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5176. return
  5177. }
  5178. var fpdargs2 []interface{}
  5179. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5180. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5181. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5182. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5183. if err != nil {
  5184. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5185. return
  5186. }
  5187. var fpdargs3 []interface{}
  5188. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5189. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5190. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5191. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5192. if err != nil {
  5193. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5194. return
  5195. }
  5196. var fpdargs4 []interface{}
  5197. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5198. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5199. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5200. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5201. if err != nil {
  5202. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5203. return
  5204. }
  5205. var fpdargs5 []interface{}
  5206. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5207. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5208. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5209. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5210. if err != nil {
  5211. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5212. return
  5213. }
  5214. var fpdargs6 []interface{}
  5215. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5216. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5217. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5218. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5219. if err != nil {
  5220. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5221. return
  5222. }
  5223. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5224. 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()
  5225. if err != nil {
  5226. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5227. return
  5228. }
  5229. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5230. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5231. upFpdetailList := make([]*upFpdetail, 0)
  5232. for _, newfpd := range newList {
  5233. for _, oldfpd := range oldFpdList {
  5234. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5235. var oldweight, newweight float64
  5236. if oldfpd["weight"] != nil {
  5237. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5238. }
  5239. if newfpd["weight"] != nil {
  5240. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5241. }
  5242. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5243. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5244. Old: oldweight,
  5245. New: newweight,
  5246. Times: newfpd["times"].(int64),
  5247. Ptid: newfpd["ptid"].(int64),
  5248. Fweight: fweight,
  5249. Id: oldfpd["id"].(int64),
  5250. })
  5251. break
  5252. }
  5253. }
  5254. }
  5255. // fmt.Println(dataexcel["barname"])
  5256. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5257. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5258. }
  5259. }
  5260. if !isdone {
  5261. ok++
  5262. isdone = true
  5263. }
  5264. }
  5265. for barname, v := range dataList {
  5266. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5267. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5268. if err != nil {
  5269. logs.Error(err)
  5270. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5271. return
  5272. }
  5273. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5274. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5275. if err != nil {
  5276. logs.Error(err)
  5277. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5278. return
  5279. }
  5280. updateFpdetailByBar(pastureid, barname, v)
  5281. }
  5282. }
  5283. data := make(map[string]interface{})
  5284. data["result"] = queryData
  5285. data["success"] = ok
  5286. data["err_count"] = error
  5287. appG.Response(http.StatusOK, e.SUCCESS, data)
  5288. }
  5289. type upFpdetail struct {
  5290. Old float64
  5291. New float64
  5292. Times int64
  5293. Ptid int64
  5294. Fweight float64
  5295. Id int64
  5296. // Ptsid string
  5297. }
  5298. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5299. tx := restful.Engine.NewSession()
  5300. defer tx.Close()
  5301. tx.Begin()
  5302. 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 `,
  5303. pastureid, barname).Query().List()
  5304. if err != nil {
  5305. logs.Error(err)
  5306. }
  5307. for _, fpd := range fpdList {
  5308. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5309. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5310. pastureid, fpd["id"], fpd["times"]).Query().List()
  5311. if err != nil {
  5312. tx.Rollback()
  5313. logs.Error(err)
  5314. return err
  5315. }
  5316. var lweight float64
  5317. for _, lppland := range lpplandList {
  5318. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5319. lweight += lweight1
  5320. }
  5321. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5322. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5323. if fpdweight >= ptuse && lweight == ptuse {
  5324. continue
  5325. } else {
  5326. if lweight <= fpdweight {
  5327. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5328. if err != nil {
  5329. tx.Rollback()
  5330. logs.Error(err)
  5331. return err
  5332. }
  5333. } else {
  5334. weight := lweight - fpdweight
  5335. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5336. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5337. if err != nil {
  5338. tx.Rollback()
  5339. logs.Error(err)
  5340. return err
  5341. }
  5342. for _, lppland := range lpplandList {
  5343. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5344. if weight >= lpplandlweight {
  5345. weight = weight - lpplandlweight
  5346. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5347. if err != nil {
  5348. tx.Rollback()
  5349. logs.Error(err)
  5350. return err
  5351. }
  5352. } else {
  5353. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5354. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5355. if err != nil {
  5356. tx.Rollback()
  5357. logs.Error(err)
  5358. return err
  5359. }
  5360. weight = 0
  5361. break
  5362. }
  5363. }
  5364. }
  5365. }
  5366. }
  5367. for _, list := range dataList {
  5368. ftmap := make(map[string]interface{})
  5369. ftmap["old"] = list.Old
  5370. ftmap["new"] = list.New
  5371. ftmap["times"] = list.Times
  5372. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5373. ftmap["ptsid"] = ""
  5374. // fmt.Println(ftmap)
  5375. // 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 ,
  5376. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5377. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5378. // UNION
  5379. fpdDataList, err := tx.SQL(`
  5380. 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 ,
  5381. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5382. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5383. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5384. if err != nil {
  5385. tx.Rollback()
  5386. logs.Error(err)
  5387. }
  5388. for _, fpd := range fpdDataList {
  5389. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5390. // fttype := -1
  5391. // if fpd["fttype"].(string) == "1" {
  5392. fttype := 1
  5393. // }
  5394. var fweight float64
  5395. var lweight float64
  5396. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5397. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5398. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5399. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5400. join tmr t on t.id = lpp.tmrid
  5401. where lppland.fpdid =?
  5402. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5403. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5404. if err != nil {
  5405. tx.Rollback()
  5406. logs.Error(err)
  5407. }
  5408. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5409. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5410. // 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
  5411. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5412. var w float64
  5413. var status int
  5414. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5415. if weight >= 0 {
  5416. continue
  5417. }
  5418. w = weight
  5419. status = 0
  5420. } else {
  5421. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5422. // continue
  5423. // }
  5424. w = weight
  5425. status = 1
  5426. }
  5427. // for _, lppland := range lpplandtl1List {
  5428. // lweight += lppland.Lweight
  5429. // }
  5430. for _, lppland := range lpplandtl1List {
  5431. lpplandInfo := new(lpplandtlInfo)
  5432. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5433. lweight = lpplandInfo.Lweight
  5434. if status == 1 {
  5435. // if w <= lppland.Lweight {
  5436. if lppland.Maxweight <= lweight {
  5437. continue
  5438. }
  5439. if w+lweight <= lppland.Maxweight {
  5440. lppland.Lweight += w
  5441. lweight += w
  5442. fweight += w
  5443. w = 0
  5444. } else {
  5445. w = w - (lppland.Maxweight - lweight)
  5446. n := (lppland.Maxweight - lweight)
  5447. lppland.Lweight = lppland.Lweight + n
  5448. lweight += n
  5449. fweight += n
  5450. }
  5451. } else {
  5452. if lppland.Lweight == 0 {
  5453. continue
  5454. }
  5455. if w+lppland.Lweight >= 0 {
  5456. lppland.Lweight = lppland.Lweight + w
  5457. lweight = lweight + w
  5458. fweight = fweight + w
  5459. w = 0
  5460. } else {
  5461. w = w + lppland.Lweight
  5462. lweight = lweight - lppland.Lweight
  5463. fweight = fweight - lppland.Lweight
  5464. lppland.Lweight = 0
  5465. }
  5466. }
  5467. if lppland.Lweight > 0 {
  5468. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5469. if err != nil {
  5470. tx.Rollback()
  5471. logs.Error(err)
  5472. return err
  5473. }
  5474. } else {
  5475. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5476. if err != nil {
  5477. tx.Rollback()
  5478. logs.Error(err)
  5479. return err
  5480. }
  5481. }
  5482. if w == 0 {
  5483. break
  5484. }
  5485. }
  5486. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5487. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5488. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5489. if err != nil {
  5490. tx.Rollback()
  5491. logs.Error(err)
  5492. }
  5493. if w == 0 {
  5494. break
  5495. }
  5496. }
  5497. }
  5498. }
  5499. err = tx.Commit()
  5500. if err != nil {
  5501. logs.Error(err)
  5502. tx.Rollback()
  5503. return err
  5504. }
  5505. now := time.Now()
  5506. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5507. if err != nil {
  5508. logs.Error(err)
  5509. return nil
  5510. }
  5511. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5512. if err != nil {
  5513. logs.Error(err)
  5514. return nil
  5515. }
  5516. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5517. if err != nil {
  5518. logs.Error(err)
  5519. return nil
  5520. }
  5521. for _, newLpplandtl1 := range newLpplandtl1List {
  5522. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5523. background,cowcount,ccountradio,lweighthis,createdate)
  5524. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5525. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5526. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5527. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5528. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5529. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5530. if err != nil {
  5531. logs.Error(err)
  5532. // appG.Response(http.StatusOK, e.ERROR, false)
  5533. return err
  5534. }
  5535. }
  5536. for _, newFpd := range newFpdDataList {
  5537. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5538. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5539. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5540. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5541. if err != nil {
  5542. logs.Error(err)
  5543. // appG.Response(http.StatusOK, e.ERROR, false)
  5544. return err
  5545. }
  5546. }
  5547. for _, newFeedp := range newFeedpList {
  5548. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5549. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5550. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5551. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5552. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5553. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5554. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5555. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5556. if err != nil {
  5557. logs.Error(err)
  5558. // appG.Response(http.StatusOK, e.ERROR, false)
  5559. return err
  5560. }
  5561. }
  5562. return nil
  5563. }
  5564. func DeleteFTdetail(c *gin.Context) {
  5565. appG := app.Gin{C: c}
  5566. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5567. fsion := gofasion.NewFasion(string(dataByte))
  5568. parammaps := fsion.Get("parammaps")
  5569. pastureid := parammaps.Get("pastureid").ValueStr()
  5570. ftid := parammaps.Get("ftid").ValueStr()
  5571. tx := restful.Engine.NewSession()
  5572. defer tx.Close()
  5573. tx.Begin()
  5574. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5575. if err != nil {
  5576. tx.Rollback()
  5577. logs.Error(err)
  5578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5579. return
  5580. }
  5581. if parammaps.Get("type").ValueStr() == "1" {
  5582. _, err := tx.SQL(`UPDATE feedp fp
  5583. set
  5584. fp.ftweight= IFNULL(IF(
  5585. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5586. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5587. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5588. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5589. ),0),fp.feedweight = 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) +ifnull(fp.supplyweight,0)
  5595. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5596. if err != nil {
  5597. tx.Rollback()
  5598. logs.Error(err)
  5599. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5600. return
  5601. }
  5602. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5603. _, err = tx.SQL(`
  5604. UPDATE fpdetail fpd
  5605. INNER JOIN feedp fp
  5606. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5607. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5608. ptuse= 0
  5609. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5610. if err != nil {
  5611. tx.Rollback()
  5612. logs.Error(err)
  5613. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5614. return
  5615. }
  5616. } else {
  5617. _, err := tx.SQL(`UPDATE feedp fp
  5618. SET
  5619. fp.supplyweight= IFNULL(IF(
  5620. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5621. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5622. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5623. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5624. ),0),fp.feedweight = 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) + ifnull(fp.supplyweight,0)
  5630. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5631. if err != nil {
  5632. tx.Rollback()
  5633. logs.Error(err)
  5634. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5635. return
  5636. }
  5637. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5638. _, err = tx.SQL(`
  5639. UPDATE fpdetail fpd
  5640. INNER JOIN feedp fp
  5641. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5642. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5643. ptsrate = 0
  5644. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5645. if err != nil {
  5646. tx.Rollback()
  5647. logs.Error(err)
  5648. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5649. return
  5650. }
  5651. }
  5652. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5653. if err != nil {
  5654. tx.Rollback()
  5655. logs.Error(err)
  5656. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5657. return
  5658. }
  5659. err = tx.Commit()
  5660. if err != nil {
  5661. tx.Rollback()
  5662. logs.Error(err)
  5663. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5664. return
  5665. }
  5666. appG.Response(http.StatusOK, e.SUCCESS, true)
  5667. }
  5668. func DeleteSpillageAll(c *gin.Context) {
  5669. appG := app.Gin{C: c}
  5670. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5671. fsion := gofasion.NewFasion(string(dataByte))
  5672. parammaps := fsion.Get("parammaps")
  5673. pastureid := parammaps.Get("pastureid").ValueStr()
  5674. times := parammaps.Get("times").ValueStr()
  5675. barid := parammaps.Get("barid").ValueStr()
  5676. tx := restful.Engine.NewSession()
  5677. defer tx.Close()
  5678. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5679. if err != nil {
  5680. logs.Error(err)
  5681. appG.Response(http.StatusOK, e.ERROR, false)
  5682. return
  5683. }
  5684. now := time.Now()
  5685. for _, item := range lpplandtl1List {
  5686. go func(item map[string]interface{}) {
  5687. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5688. background,cowcount,ccountradio,lweighthis,createdate)
  5689. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5690. item["pastureid"], item["lppid"], item["barid"],
  5691. item["barname"], item["fpdid"], item["fttype"],
  5692. item["lweight"], item["sort"], item["tmrid"],
  5693. item["tmrname"], item["background"], item["cowcount"],
  5694. item["ccountradio"], item["lweighthis"], now).Execute()
  5695. if err != nil {
  5696. logs.Error(err)
  5697. appG.Response(http.StatusOK, e.ERROR, false)
  5698. return
  5699. }
  5700. }(item)
  5701. }
  5702. tx.Begin()
  5703. _, 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()
  5704. if err != nil {
  5705. tx.Rollback()
  5706. logs.Error(err)
  5707. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5708. return
  5709. }
  5710. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5711. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5712. if err != nil {
  5713. tx.Rollback()
  5714. logs.Error(err)
  5715. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5716. return
  5717. }
  5718. err = tx.Commit()
  5719. if err != nil {
  5720. tx.Rollback()
  5721. logs.Error(err)
  5722. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5723. return
  5724. }
  5725. appG.Response(http.StatusOK, e.SUCCESS, true)
  5726. }
  5727. func GetTMRListEnableTypeAll(c *gin.Context) {
  5728. appG := app.Gin{C: c}
  5729. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5730. fsion := gofasion.NewFasion(string(dataByte))
  5731. parammaps := fsion.Get("parammaps")
  5732. pastureid := parammaps.Get("pastureid").ValueStr()
  5733. tx := restful.Engine.NewSession()
  5734. defer tx.Close()
  5735. dataList, err := tx.SQL(`SELECT
  5736. eqcode,
  5737. tname,
  5738. datacaptureno,
  5739. trim(tclassid) tclassid,
  5740. concat(tname,' / ',eqcode) tmrmix,
  5741. d.label tclassname,
  5742. maxstirfeed,
  5743. remark,
  5744. tmr.enable,
  5745. TRIM(tmr.id) id,
  5746. TRIM(tmr.pastureid)pastureid
  5747. FROM
  5748. tmr
  5749. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5750. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5751. ORDER BY id DESC`, pastureid).Query().List()
  5752. if err != nil {
  5753. logs.Error(err)
  5754. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5755. return
  5756. }
  5757. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5758. if err != nil {
  5759. logs.Error(err)
  5760. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5761. return
  5762. }
  5763. var carNum int64
  5764. for _, sysopt := range sysoptData {
  5765. if sysopt["inforvalue"] == nil {
  5766. carNum = 1
  5767. } else {
  5768. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5769. }
  5770. }
  5771. id := 200
  5772. n := 0
  5773. for i := carNum; i > 0; i-- {
  5774. id++
  5775. n++
  5776. // data := make(map[string]interface{}, 0)
  5777. // data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5778. // data["tname"] = fmt.Sprintf("任意车%d", n)
  5779. // data["datacaptureno"] = -2
  5780. // data["tclassid"] = -2
  5781. // data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5782. // data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5783. // data["maxstirfeed"] = 100000
  5784. // data["remark"] = fmt.Sprintf("任意车%d", n)
  5785. // data["enable"] = 1
  5786. // data["id"] = fmt.Sprintf("%d", id)
  5787. // data["pastureid"] = pastureid
  5788. data := make(map[string]interface{}, 0)
  5789. data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5790. data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5791. data["datacaptureno"] = -2
  5792. data["tclassid"] = -2
  5793. data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5794. data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5795. data["maxstirfeed"] = 100000
  5796. data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5797. data["enable"] = 1
  5798. data["id"] = fmt.Sprintf("%d", id)
  5799. data["pastureid"] = pastureid
  5800. dataList = append(dataList, data)
  5801. }
  5802. // UNION ALL
  5803. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5804. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5805. }
  5806. func GetFeedpHistory(c *gin.Context) {
  5807. appG := app.Gin{C: c}
  5808. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5809. fsion := gofasion.NewFasion(string(dataByte))
  5810. // parammaps := fsion.Get("parammaps")
  5811. bar := fsion.Get("barname").ValueStr()
  5812. startDate := fsion.Get("startDate").ValueStr()
  5813. endDate := fsion.Get("endDate").ValueStr()
  5814. tx := restful.Engine.NewSession()
  5815. defer tx.Close()
  5816. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5817. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5818. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5819. if err != nil {
  5820. logs.Error(err)
  5821. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5822. return
  5823. }
  5824. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5825. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5826. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5827. if err != nil {
  5828. logs.Error(err)
  5829. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5830. return
  5831. }
  5832. for _, feedp := range feedpList {
  5833. // LastftList, err := tx.SQL(` select tname ,id
  5834. // from feedtemplethistory where id = ?
  5835. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5836. // if err != nil {
  5837. // logs.Error(err)
  5838. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5839. // return
  5840. // }
  5841. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5842. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5843. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5844. if err != nil {
  5845. logs.Error(err)
  5846. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5847. return
  5848. }
  5849. var ftname interface{}
  5850. ftnamestatus := 0
  5851. ftname = feedp["ftname"]
  5852. var lastftid int64
  5853. if len(nextfeedpList) > 0 {
  5854. for _, ft := range nextfeedpList {
  5855. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5856. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5857. lastftid = ft["ftid"].(int64)
  5858. ftnamestatus = 1
  5859. break
  5860. }
  5861. }
  5862. }
  5863. for i, fpd := range fpdList {
  5864. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5865. fpd["weightstatus"] = 0
  5866. fpd["tratiostatus"] = 0
  5867. fpd["ftnamestatus"] = ftnamestatus
  5868. for k, fpd2 := range fpdList {
  5869. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5870. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5871. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5872. fpd["weightstatus"] = 1
  5873. }
  5874. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5875. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5876. fpd["tratiostatus"] = 1
  5877. }
  5878. break
  5879. }
  5880. }
  5881. fpd["barid"] = feedp["barid"]
  5882. fpd["barname"] = feedp["barname"]
  5883. fpd["ccount"] = feedp["ccount"]
  5884. fpd["ratio"] = feedp["ratio"]
  5885. fpd["ccountratio"] = feedp["ccountratio"]
  5886. fpd["ftid"] = feedp["ftid"]
  5887. fpd["ftname"] = ftname
  5888. fpd["ccountstatus"] = 0
  5889. fpd["ccountratiostatus"] = 0
  5890. fpd["ratiostatus"] = 0
  5891. fpd["ftnamestatus"] = 0
  5892. fpd["lastftid"] = lastftid
  5893. for _, next := range nextfeedpList {
  5894. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5895. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5896. fpd["ccountstatus"] = 1
  5897. }
  5898. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5899. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5900. fpd["ccountratiostatus"] = 1
  5901. }
  5902. if next["ratio"].(string) != fpd["ratio"].(string) {
  5903. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5904. fpd["ratiostatus"] = 1
  5905. }
  5906. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5907. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5908. // fpd["ftnamestatus"] = 1
  5909. // }
  5910. }
  5911. }
  5912. }
  5913. }
  5914. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5915. }
  5916. // func GetLpplandtl1History(c *gin.Context) {
  5917. // appG := app.Gin{C: c}
  5918. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5919. // fsion := gofasion.NewFasion(string(dataByte))
  5920. // // parammaps := fsion.Get("parammaps")
  5921. // barid := fsion.Get("barid").ValueStr()
  5922. // startDate := fsion.Get("startDate").ValueStr()
  5923. // endDate := fsion.Get("endDate").ValueStr()
  5924. // tx := restful.Engine.NewSession()
  5925. // defer tx.Close()
  5926. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5927. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5928. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5929. // // if err != nil {
  5930. // // logs.Error(err)
  5931. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5932. // // return
  5933. // // }
  5934. // // for _, feedp := range feedpList {
  5935. // // fmt.Println(feedp)
  5936. // // for i, fpd := range fpdList {
  5937. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5938. // // for k, fpd2 := range fpdList {
  5939. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5940. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5941. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5942. // // }
  5943. // // break
  5944. // // }
  5945. // // }
  5946. // // fpd["barid"] = feedp["barid"]
  5947. // // fpd["barname"] = feedp["barname"]
  5948. // // fpd["ccount"] = feedp["ccount"]
  5949. // // fpd["ratio"] = feedp["ratio"]
  5950. // // fpd["ccountratio"] = feedp["ccountratio"]
  5951. // // fpd["ftid"] = feedp["ftid"]
  5952. // // fpd["ftname"] = feedp["ftname"]
  5953. // // }
  5954. // // }
  5955. // // }
  5956. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5957. // }
  5958. func GetRemind(c *gin.Context) {
  5959. appG := app.Gin{C: c}
  5960. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5961. fsion := gofasion.NewFasion(string(dataByte))
  5962. parammaps := fsion.Get("parammaps")
  5963. pastureid := parammaps.Get("pastureid").ValueStr()
  5964. tx := restful.Engine.NewSession()
  5965. defer tx.Close()
  5966. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5967. if err != nil {
  5968. logs.Error(err)
  5969. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5970. return
  5971. }
  5972. // pastureid = "3"
  5973. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5974. if err != nil {
  5975. logs.Error(err)
  5976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5977. return
  5978. }
  5979. defer resp.Body.Close()
  5980. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5981. buf.ReadFrom(resp.Body)
  5982. fmt.Println(string(buf.Bytes()))
  5983. respMap := make(map[string]interface{}, 0)
  5984. err = json.Unmarshal(buf.Bytes(), &respMap)
  5985. if err != nil {
  5986. logs.Error(err)
  5987. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5988. return
  5989. }
  5990. for _, data := range dataList {
  5991. r := make(map[string]interface{}, 0)
  5992. r["sys_name"] = ""
  5993. r["service_id"] = ""
  5994. r["pasture_id"] = ""
  5995. r["type_name"] = ""
  5996. r["remind_type_id"] = ""
  5997. r["remind_type"] = ""
  5998. r["push_date"] = ""
  5999. r["push_time"] = ""
  6000. r["interval_time"] = ""
  6001. r["push_limit"] = ""
  6002. r["template_id"] = ""
  6003. r["roles_id"] = ""
  6004. r["users_id"] = ""
  6005. r["date_type"] = ""
  6006. r["cycle_type"] = ""
  6007. data["data"] = r
  6008. for _, resp := range respMap["data"].([]interface{}) {
  6009. resp1 := resp.(map[string]interface{})
  6010. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6011. if resp1["push_time"] == nil {
  6012. resp1["push_time"] = ""
  6013. }
  6014. data["data"] = resp1
  6015. break
  6016. }
  6017. }
  6018. }
  6019. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6020. }
  6021. type NoticeMsgtype struct {
  6022. SysName string `json:"sys_name"`
  6023. PastureId int64 `json:"pasture_id"`
  6024. ServiceId int64 `json:"service_id"`
  6025. TypeName string `json:"type_name"`
  6026. RemindType int64 `json:"remind_type"`
  6027. PushDate int64 `json:"push_date"`
  6028. PushTime string `json:"push_time"`
  6029. IntervalTime int64 `json:"interval_time"`
  6030. PushLimit int64 `json:"push_limit"`
  6031. TemplateId string `json:"template_id"`
  6032. UsersId string `json:"users_id"`
  6033. DateType int64 `json:"date_type"`
  6034. CycleType int64 `json:"cycle_type"`
  6035. DelayTime int64 `json:"delay_time"`
  6036. Status int64 `json:"status"`
  6037. }
  6038. func UpdateRemind(c *gin.Context) {
  6039. appG := app.Gin{C: c}
  6040. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6041. parammaps := gofasion.NewFasion(string(dataByte))
  6042. // parammaps := fsion.Get("parammaps")
  6043. // user := parammaps.Get("user").ValueStr()
  6044. id := parammaps.Get("id").ValueInt64()
  6045. noticeMsgtype := new(NoticeMsgtype)
  6046. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6047. noticeMsgtype.ServiceId = id
  6048. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6049. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6050. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6051. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6052. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6053. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6054. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6055. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6056. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6057. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6058. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6059. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6060. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6061. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6062. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6063. //TODO
  6064. noticeMsgtype.SysName = "tmrWatch"
  6065. userList := parammaps.Get("user").Array()
  6066. var userstr []string
  6067. for _, user := range userList {
  6068. userstr = append(userstr, user.ValueStr())
  6069. }
  6070. tx := restful.Engine.NewSession()
  6071. defer tx.Close()
  6072. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6073. if err != nil {
  6074. logs.Error(err)
  6075. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6076. return
  6077. }
  6078. // var jsonStr = []byte(noticeMsgtype
  6079. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6080. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6081. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6082. req.Header.Set("Content-Type", "application/json")
  6083. client := &http.Client{}
  6084. resp, err := client.Do(req)
  6085. if err != nil {
  6086. logs.Error(err)
  6087. }
  6088. defer resp.Body.Close()
  6089. body, _ := ioutil.ReadAll(resp.Body)
  6090. fmt.Println("response Body:", string(body))
  6091. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6092. if err != nil {
  6093. logs.Error(err)
  6094. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6095. return
  6096. }
  6097. defer getresp.Body.Close()
  6098. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6099. buf.ReadFrom(getresp.Body)
  6100. // fmt.Println(string(buf.Bytes()))
  6101. respMap := make(map[string]interface{}, 0)
  6102. err = json.Unmarshal(buf.Bytes(), &respMap)
  6103. if err != nil {
  6104. logs.Error(err)
  6105. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6106. return
  6107. }
  6108. for _, resp := range respMap["data"].([]interface{}) {
  6109. resp1 := resp.(map[string]interface{})
  6110. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6111. if err != nil {
  6112. logs.Error(err)
  6113. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6114. return
  6115. }
  6116. }
  6117. appG.Response(http.StatusOK, e.SUCCESS, true)
  6118. }
  6119. func GetSpillageallHistory(c *gin.Context) {
  6120. appG := app.Gin{C: c}
  6121. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6122. parammaps := gofasion.NewFasion(string(dataByte))
  6123. barname := parammaps.Get("barname").ValueStr()
  6124. pastureid := parammaps.Get("pastureid").ValueStr()
  6125. startdate := parammaps.Get("startDate").ValueStr()
  6126. enddate := parammaps.Get("endDate").ValueStr()
  6127. tx := restful.Engine.NewSession()
  6128. defer tx.Close()
  6129. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate from lpplandtl1history lppland
  6130. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6131. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6132. if err != nil {
  6133. logs.Error(err)
  6134. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6135. return
  6136. }
  6137. respMap := make([]map[string]interface{}, 0)
  6138. data := make(map[interface{}]interface{})
  6139. for _, history := range historyList {
  6140. data[history["createdate"]] = history["createdate"]
  6141. }
  6142. createList := []string{}
  6143. for _, v := range data {
  6144. createList = append(createList, v.(string))
  6145. }
  6146. // sort.Sort()
  6147. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6148. sort.Slice(createList, func(i, j int) bool {
  6149. return createList[i] > createList[j]
  6150. })
  6151. for _, v := range createList {
  6152. a := make(map[string]interface{})
  6153. a["createdate"] = data[v]
  6154. // createList = append(createList, v.(string))
  6155. respMap = append(respMap, a)
  6156. }
  6157. number := 0
  6158. dataMap := make([]interface{}, 0)
  6159. for k, resp := range respMap {
  6160. createdate := resp["createdate"].(string)
  6161. var nextcreatedate string
  6162. if len(respMap) > k+1 {
  6163. nextcreatedate = respMap[k+1]["createdate"].(string)
  6164. }
  6165. // dataList := make(map[string][]interface{})
  6166. // list := make(map[string]interface{})
  6167. times := make(map[interface{}]int)
  6168. for _, history := range historyList {
  6169. // List := make(map[interface{}][]interface{})
  6170. i := 0
  6171. if history["createdate"].(string) == createdate {
  6172. times[history["times"]]++
  6173. data := make(map[string]interface{})
  6174. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6175. // exist := false
  6176. if nextcreatedate != "" {
  6177. for _, history1 := range historyList {
  6178. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6179. history1["times"].(int64) == history["times"].(int64) {
  6180. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6181. break
  6182. // exist = true
  6183. }
  6184. }
  6185. }
  6186. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6187. i++
  6188. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6189. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6190. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6191. // resp["times"] = history["times"]
  6192. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6193. data1 := make(map[string]interface{})
  6194. data1["times"] = history["times"]
  6195. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6196. data1["createdate"] = resp["createdate"]
  6197. // fmt.Println(dataList)
  6198. dataMap = append(dataMap, data1)
  6199. }
  6200. if i > number {
  6201. number = i
  6202. }
  6203. // respMap = append(respMap, dataList)
  6204. }
  6205. // for k, data := range dataList {
  6206. // resp[k] = data
  6207. // }
  6208. // resp["data"] = dataList
  6209. }
  6210. // resp := make(map[string]interface{})
  6211. // sort.Strings(createList)
  6212. //
  6213. // for _, create := range createList {
  6214. // for _, r := range respMap {
  6215. // if create == r["createdate"].(string) {
  6216. // resp[create] = r
  6217. // break
  6218. // }
  6219. // }
  6220. // }
  6221. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6222. var trainsList []interface{}
  6223. for i := 0; i < number; i++ {
  6224. trains := make(map[string]interface{})
  6225. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6226. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6227. trainsList = append(trainsList, trains)
  6228. }
  6229. respdata := make(map[string]interface{})
  6230. respdata["data"] = dataMap
  6231. respdata["trains"] = trainsList
  6232. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6233. }
  6234. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6235. appG := app.Gin{C: c}
  6236. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6237. parammaps := gofasion.NewFasion(string(dataByte))
  6238. ftid := parammaps.Get("ftid").ValueInt64()
  6239. lastftid := parammaps.Get("lastftid").ValueInt64()
  6240. pastureid := parammaps.Get("pastureid").ValueInt64()
  6241. // createdate := parammaps.Get("createdate").ValueStr()
  6242. tx := restful.Engine.NewSession()
  6243. defer tx.Close()
  6244. data := make(map[string]interface{})
  6245. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6246. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6247. if err != nil {
  6248. logs.Error(err)
  6249. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6250. return
  6251. }
  6252. feedtemplet := make(map[string]interface{})
  6253. for _, f := range feedtempletList {
  6254. feedtemplet = f
  6255. }
  6256. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.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["fit"] = fitList
  6263. data["current"] = feedtemplet
  6264. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6265. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6266. if err != nil {
  6267. logs.Error(err)
  6268. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6269. return
  6270. }
  6271. lastfeedtemplet := make(map[string]interface{})
  6272. for _, f := range lastfeedtempletList {
  6273. lastfeedtemplet = f
  6274. }
  6275. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.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["fit"] = lastfitList
  6282. data["last"] = lastfeedtemplet
  6283. appG.Response(http.StatusOK, e.SUCCESS, data)
  6284. }
  6285. func GetFeedtempletHistory(c *gin.Context) {
  6286. appG := app.Gin{C: c}
  6287. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6288. parammaps := gofasion.NewFasion(string(dataByte))
  6289. ftid := parammaps.Get("ftid").ValueStr()
  6290. pastureid := parammaps.Get("pastureid").ValueInt64()
  6291. start := parammaps.Get("startdate").ValueStr()
  6292. end := parammaps.Get("enddate").ValueStr()
  6293. tx := restful.Engine.NewSession()
  6294. defer tx.Close()
  6295. 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 ?
  6296. and id = ? and pastureid = ? order by createdate desc `,
  6297. start, end, ftid, pastureid).Query().List()
  6298. if err != nil {
  6299. logs.Error(err)
  6300. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6301. return
  6302. }
  6303. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6304. ftid, pastureid).Query().List()
  6305. if err != nil {
  6306. logs.Error(err)
  6307. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6308. return
  6309. }
  6310. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6311. for i, ft := range ftList {
  6312. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6313. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6314. (select empname from user where id = fit.userId) empname,
  6315. 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
  6316. where fit.fitid = ?
  6317. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6318. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6319. if err != nil {
  6320. logs.Error(err)
  6321. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6322. return
  6323. }
  6324. ft["createdate"] = ft["createdate1"]
  6325. // data["tname"] = ft["tname"]
  6326. // data["tcode"] = ft["tcode"]
  6327. // data["tcolor"] = ft["tcolor"]
  6328. // data["fttype"] = ft["fttype"]
  6329. // data["ccname"] = ft["ccname"]
  6330. // data["source"] = ft["source"]
  6331. // data["version"] = ft["version"]
  6332. // data["remark"] = ft["remark"]
  6333. for n, ft2 := range ftList {
  6334. if i < n {
  6335. if ft["tname"].(string) != ft2["tname"].(string) {
  6336. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6337. }
  6338. if _, ok := ft["tcode"]; ok {
  6339. if _, ok := ft2["tcode"]; ok {
  6340. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6341. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6342. }
  6343. }
  6344. }
  6345. if _, ok := ft["tcolor"]; ok {
  6346. if _, ok := ft2["tcolor"]; ok {
  6347. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6348. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6349. }
  6350. }
  6351. }
  6352. if _, ok := ft["fttype"]; ok {
  6353. if _, ok := ft2["fttype"]; ok {
  6354. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6355. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6356. }
  6357. }
  6358. }
  6359. if _, ok := ft["ccname"]; ok {
  6360. if _, ok := ft2["ccname"]; ok {
  6361. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6362. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6363. }
  6364. }
  6365. }
  6366. if _, ok := ft["source"]; ok {
  6367. if _, ok := ft2["source"]; ok {
  6368. if ft["source"].(string) != ft2["source"].(string) {
  6369. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6370. }
  6371. }
  6372. }
  6373. if _, ok := ft["version"]; ok {
  6374. if _, ok := ft2["version"]; ok {
  6375. if ft["version"].(int64) != ft2["version"].(int64) {
  6376. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6377. }
  6378. }
  6379. }
  6380. if _, ok := ft["remark"]; ok {
  6381. if _, ok := ft2["remark"]; ok {
  6382. if ft["remark"].(string) != ft2["remark"].(string) {
  6383. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6384. }
  6385. }
  6386. }
  6387. break
  6388. }
  6389. }
  6390. dataList := make([]map[string]interface{}, 0)
  6391. if len(fithisList) > 0 {
  6392. for _, fit := range fithisList {
  6393. data := make(map[string]interface{})
  6394. data["feedgroup"] = fit["feedgroup"]
  6395. data["fname"] = fit["fname"]
  6396. data["empname"] = fit["empname"]
  6397. if fit["Eweight"] != nil {
  6398. if fit["Eweight"].(string) != fit["weight"].(string) {
  6399. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6400. } else {
  6401. data["fweight"] = fit["Eweight"]
  6402. }
  6403. data["fweightstatus"] = 1
  6404. } else {
  6405. data["fweight"] = fit["weight"]
  6406. data["fweightstatus"] = 0
  6407. }
  6408. data["autosecond"] = fit["autosecond"]
  6409. // data["tname"] = ft["tname"]
  6410. // data["tcode"] = ft["tcode"]
  6411. // data["tcolor"] = ft["tcolor"]
  6412. // data["fttype"] = ft["fttype"]
  6413. // data["ccname"] = ft["ccname"]
  6414. // data["source"] = ft["source"]
  6415. // data["version"] = ft["version"]
  6416. // data["remark"] = ft["remark"]
  6417. // data["createdate"] = ft["createdate1"]
  6418. // ft["fit"] = data
  6419. dataList = append(dataList, data)
  6420. }
  6421. } else {
  6422. for _, fit := range ftdetailList {
  6423. data := make(map[string]interface{})
  6424. data["feedgroup"] = fit["feedgroup"]
  6425. data["fname"] = fit["fname"]
  6426. // if fit["Eweight"] != nil {
  6427. // data["weight"] = fit["Eweight"]
  6428. // } else {
  6429. data["fweight"] = fit["fweight"]
  6430. // }
  6431. data["autosecond"] = fit["autosecond"]
  6432. // ft["fit"] = data
  6433. dataList = append(dataList, data)
  6434. }
  6435. }
  6436. ft["fit"] = dataList
  6437. }
  6438. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6439. }
  6440. func UpdateMaterialTMR(c *gin.Context) {
  6441. appG := app.Gin{C: c}
  6442. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6443. parammaps := gofasion.NewFasion(string(dataByte))
  6444. tmrid := parammaps.Get("tmrid").ValueStr()
  6445. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6446. lppid := parammaps.Get("lppid").ValueStr()
  6447. times := parammaps.Get("times").ValueStr()
  6448. pastureid := parammaps.Get("pastureid").ValueStr()
  6449. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6450. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6451. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6452. tx := restful.Engine.NewSession()
  6453. defer tx.Close()
  6454. tx.Begin()
  6455. if tmrid != "1000" {
  6456. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6457. if err != nil {
  6458. logs.Error(err)
  6459. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6460. return
  6461. }
  6462. var maxstirfeed float64
  6463. for _, tmr := range tmrList {
  6464. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6465. }
  6466. if status == 0 {
  6467. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6468. if err != nil {
  6469. tx.Rollback()
  6470. logs.Error(err)
  6471. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6472. return
  6473. }
  6474. var lweight float64
  6475. for _, item := range lpplandtl1List {
  6476. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6477. lweight += fl
  6478. }
  6479. if lweight > maxstirfeed {
  6480. lweight = lweight - maxstirfeed
  6481. } else {
  6482. lweight = 0
  6483. }
  6484. if lweight > 0 {
  6485. lweight1 := lweight / float64(len(lpplandtl1List))
  6486. number := 0
  6487. for _, item := range lpplandtl1List {
  6488. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6489. if lweight1 >= fl {
  6490. number++
  6491. }
  6492. }
  6493. lweight := lweight / float64((len(lpplandtl1List) - number))
  6494. for _, item := range lpplandtl1List {
  6495. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6496. if lweight1 >= fl {
  6497. continue
  6498. }
  6499. if tmrtype == "1" {
  6500. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6501. if err != nil {
  6502. tx.Rollback()
  6503. logs.Error(err)
  6504. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6505. return
  6506. }
  6507. } else if tmrtype == "2" {
  6508. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6509. if err != nil {
  6510. tx.Rollback()
  6511. logs.Error(err)
  6512. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6513. return
  6514. }
  6515. }
  6516. if item["fttype"].(int64) == 0 {
  6517. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6518. if err != nil {
  6519. tx.Rollback()
  6520. logs.Error(err)
  6521. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6522. return
  6523. }
  6524. } else {
  6525. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6526. if err != nil {
  6527. tx.Rollback()
  6528. logs.Error(err)
  6529. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6530. return
  6531. }
  6532. }
  6533. }
  6534. } else {
  6535. for _, item := range lpplandtl1List {
  6536. // 自走式
  6537. if tmrtype == "1" {
  6538. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6539. if err != nil {
  6540. logs.Error(err)
  6541. tx.Rollback()
  6542. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6543. return
  6544. }
  6545. } else if tmrtype == "2" {
  6546. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6547. if err != nil {
  6548. logs.Error(err)
  6549. tx.Rollback()
  6550. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6551. return
  6552. }
  6553. }
  6554. }
  6555. }
  6556. } else if status == 1 {
  6557. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6558. if err != nil {
  6559. logs.Error(err)
  6560. tx.Rollback()
  6561. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6562. return
  6563. }
  6564. var lweight float64
  6565. for _, item := range lpplandtl1List {
  6566. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6567. lweight += fl
  6568. }
  6569. if lweight > maxstirfeed {
  6570. lweight = lweight - maxstirfeed
  6571. } else {
  6572. lweight = 0
  6573. }
  6574. for _, item := range lpplandtl1List {
  6575. if lweight > 0 {
  6576. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6577. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6578. if fl >= lweight {
  6579. item["lweight"] = fl - lweight
  6580. lweight = 0
  6581. if tmrtype == "1" {
  6582. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6583. if err != nil {
  6584. logs.Error(err)
  6585. tx.Rollback()
  6586. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6587. return
  6588. }
  6589. } else if tmrtype == "2" {
  6590. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6591. if err != nil {
  6592. logs.Error(err)
  6593. tx.Rollback()
  6594. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6595. return
  6596. }
  6597. }
  6598. if item["fttype"].(int64) == 0 {
  6599. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6600. if err != nil {
  6601. logs.Error(err)
  6602. tx.Rollback()
  6603. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6604. return
  6605. }
  6606. } else {
  6607. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6608. if err != nil {
  6609. logs.Error(err)
  6610. tx.Rollback()
  6611. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6612. return
  6613. }
  6614. }
  6615. } else {
  6616. lweight = lweight - fl
  6617. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6618. if err != nil {
  6619. logs.Error(err)
  6620. tx.Rollback()
  6621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6622. return
  6623. }
  6624. if item["fttype"].(int64) == 0 {
  6625. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6626. if err != nil {
  6627. logs.Error(err)
  6628. tx.Rollback()
  6629. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6630. return
  6631. }
  6632. } else {
  6633. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6634. if err != nil {
  6635. logs.Error(err)
  6636. tx.Rollback()
  6637. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6638. return
  6639. }
  6640. }
  6641. }
  6642. } else {
  6643. // 自走式
  6644. if tmrtype == "1" {
  6645. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6646. if err != nil {
  6647. logs.Error(err)
  6648. tx.Rollback()
  6649. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6650. return
  6651. }
  6652. } else if tmrtype == "2" {
  6653. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6654. if err != nil {
  6655. logs.Error(err)
  6656. tx.Rollback()
  6657. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6658. return
  6659. }
  6660. }
  6661. }
  6662. }
  6663. } else {
  6664. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6665. if err != nil {
  6666. logs.Error(err)
  6667. tx.Rollback()
  6668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6669. return
  6670. }
  6671. for _, item := range lpplandtl1List {
  6672. if item["fttype"].(int64) == 0 {
  6673. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6674. if err != nil {
  6675. logs.Error(err)
  6676. tx.Rollback()
  6677. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6678. return
  6679. }
  6680. } else {
  6681. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6682. if err != nil {
  6683. logs.Error(err)
  6684. tx.Rollback()
  6685. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6686. return
  6687. }
  6688. }
  6689. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6690. if err != nil {
  6691. logs.Error(err)
  6692. tx.Rollback()
  6693. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6694. return
  6695. }
  6696. }
  6697. }
  6698. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6699. if err != nil {
  6700. logs.Error(err)
  6701. tx.Rollback()
  6702. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6703. return
  6704. }
  6705. } else {
  6706. if status == 2 {
  6707. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6708. if err != nil {
  6709. logs.Error(err)
  6710. tx.Rollback()
  6711. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6712. return
  6713. }
  6714. for _, item := range lpplandtl1List {
  6715. if item["fttype"].(int64) == 0 {
  6716. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6717. if err != nil {
  6718. logs.Error(err)
  6719. tx.Rollback()
  6720. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6721. return
  6722. }
  6723. } else {
  6724. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6725. if err != nil {
  6726. logs.Error(err)
  6727. tx.Rollback()
  6728. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6729. return
  6730. }
  6731. }
  6732. }
  6733. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6734. if err != nil {
  6735. logs.Error(err)
  6736. tx.Rollback()
  6737. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6738. return
  6739. }
  6740. } else {
  6741. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6742. if err != nil {
  6743. logs.Error(err)
  6744. tx.Rollback()
  6745. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6746. return
  6747. }
  6748. }
  6749. }
  6750. err := tx.Commit()
  6751. if err != nil {
  6752. logs.Error(err)
  6753. tx.Rollback()
  6754. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6755. return
  6756. }
  6757. appG.Response(http.StatusOK, e.SUCCESS, true)
  6758. }
  6759. func UpdateMaterialTMRDate(c *gin.Context) {
  6760. appG := app.Gin{C: c}
  6761. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6762. parammaps := gofasion.NewFasion(string(dataByte))
  6763. tmrid := parammaps.Get("tmrid").ValueStr()
  6764. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6765. lppid := parammaps.Get("lppid").ValueStr()
  6766. times := parammaps.Get("times").ValueStr()
  6767. pastureid := parammaps.Get("pastureid").ValueStr()
  6768. date := parammaps.Get("date").ValueStr()
  6769. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6770. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6771. tx := restful.Engine.NewSession()
  6772. defer tx.Close()
  6773. tx.Begin()
  6774. if tmrid != "1000" {
  6775. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6776. if err != nil {
  6777. logs.Error(err)
  6778. tx.Rollback()
  6779. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6780. return
  6781. }
  6782. var maxstirfeed float64
  6783. for _, tmr := range tmrList {
  6784. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6785. }
  6786. if status == 0 {
  6787. 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()
  6788. if err != nil {
  6789. logs.Error(err)
  6790. tx.Rollback()
  6791. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6792. return
  6793. }
  6794. var lweight float64
  6795. for _, item := range lpplandtl1List {
  6796. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6797. lweight += fl
  6798. }
  6799. if lweight > maxstirfeed {
  6800. lweight = lweight - maxstirfeed
  6801. } else {
  6802. lweight = 0
  6803. }
  6804. if lweight > 0 {
  6805. lweight1 := lweight / float64(len(lpplandtl1List))
  6806. number := 0
  6807. for _, item := range lpplandtl1List {
  6808. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6809. if lweight1 >= fl {
  6810. number++
  6811. }
  6812. }
  6813. lweight := lweight / float64((len(lpplandtl1List) - number))
  6814. for _, item := range lpplandtl1List {
  6815. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6816. if lweight1 >= fl {
  6817. continue
  6818. }
  6819. if tmrtype == "1" {
  6820. _, 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()
  6821. if err != nil {
  6822. logs.Error(err)
  6823. tx.Rollback()
  6824. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6825. return
  6826. }
  6827. } else if tmrtype == "2" {
  6828. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6829. if err != nil {
  6830. logs.Error(err)
  6831. tx.Rollback()
  6832. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6833. return
  6834. }
  6835. }
  6836. if item["fttype"].(int64) == 0 {
  6837. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6838. if err != nil {
  6839. logs.Error(err)
  6840. tx.Rollback()
  6841. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6842. return
  6843. }
  6844. } else {
  6845. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6846. if err != nil {
  6847. logs.Error(err)
  6848. tx.Rollback()
  6849. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6850. return
  6851. }
  6852. }
  6853. }
  6854. } else {
  6855. for _, item := range lpplandtl1List {
  6856. // 自走式
  6857. if tmrtype == "1" {
  6858. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6859. if err != nil {
  6860. logs.Error(err)
  6861. tx.Rollback()
  6862. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6863. return
  6864. }
  6865. } else if tmrtype == "2" {
  6866. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6867. if err != nil {
  6868. logs.Error(err)
  6869. tx.Rollback()
  6870. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6871. return
  6872. }
  6873. }
  6874. }
  6875. }
  6876. } else if status == 1 {
  6877. 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()
  6878. if err != nil {
  6879. logs.Error(err)
  6880. tx.Rollback()
  6881. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6882. return
  6883. }
  6884. var lweight float64
  6885. for _, item := range lpplandtl1List {
  6886. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6887. lweight += fl
  6888. }
  6889. if lweight > maxstirfeed {
  6890. lweight = lweight - maxstirfeed
  6891. } else {
  6892. lweight = 0
  6893. }
  6894. for _, item := range lpplandtl1List {
  6895. if lweight > 0 {
  6896. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6897. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6898. if fl >= lweight {
  6899. item["lweight"] = fl - lweight
  6900. lweight = 0
  6901. if tmrtype == "1" {
  6902. _, 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()
  6903. if err != nil {
  6904. logs.Error(err)
  6905. tx.Rollback()
  6906. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6907. return
  6908. }
  6909. } else if tmrtype == "2" {
  6910. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6911. if err != nil {
  6912. logs.Error(err)
  6913. tx.Rollback()
  6914. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6915. return
  6916. }
  6917. }
  6918. if item["fttype"].(int64) == 0 {
  6919. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6920. if err != nil {
  6921. logs.Error(err)
  6922. tx.Rollback()
  6923. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6924. return
  6925. }
  6926. } else {
  6927. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6928. if err != nil {
  6929. logs.Error(err)
  6930. tx.Rollback()
  6931. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6932. return
  6933. }
  6934. }
  6935. } else {
  6936. lweight = lweight - fl
  6937. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], 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. if item["fttype"].(int64) == 0 {
  6945. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6946. if err != nil {
  6947. logs.Error(err)
  6948. tx.Rollback()
  6949. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6950. return
  6951. }
  6952. } else {
  6953. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6954. if err != nil {
  6955. logs.Error(err)
  6956. tx.Rollback()
  6957. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6958. return
  6959. }
  6960. }
  6961. }
  6962. } else {
  6963. // 自走式
  6964. if tmrtype == "1" {
  6965. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6966. if err != nil {
  6967. logs.Error(err)
  6968. tx.Rollback()
  6969. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6970. return
  6971. }
  6972. } else if tmrtype == "2" {
  6973. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6974. if err != nil {
  6975. logs.Error(err)
  6976. tx.Rollback()
  6977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6978. return
  6979. }
  6980. }
  6981. }
  6982. }
  6983. } else {
  6984. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6985. if err != nil {
  6986. logs.Error(err)
  6987. tx.Rollback()
  6988. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6989. return
  6990. }
  6991. for _, item := range lpplandtl1List {
  6992. if item["fttype"].(int64) == 0 {
  6993. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6994. if err != nil {
  6995. logs.Error(err)
  6996. tx.Rollback()
  6997. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6998. return
  6999. }
  7000. } else {
  7001. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7002. if err != nil {
  7003. logs.Error(err)
  7004. tx.Rollback()
  7005. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7006. return
  7007. }
  7008. }
  7009. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7010. if err != nil {
  7011. logs.Error(err)
  7012. tx.Rollback()
  7013. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7014. return
  7015. }
  7016. }
  7017. }
  7018. _, 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()
  7019. if err != nil {
  7020. logs.Error(err)
  7021. tx.Rollback()
  7022. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7023. return
  7024. }
  7025. } else {
  7026. if status == 2 {
  7027. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7028. if err != nil {
  7029. logs.Error(err)
  7030. tx.Rollback()
  7031. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7032. return
  7033. }
  7034. for _, item := range lpplandtl1List {
  7035. if item["fttype"].(int64) == 0 {
  7036. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7037. if err != nil {
  7038. logs.Error(err)
  7039. tx.Rollback()
  7040. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7041. return
  7042. }
  7043. } else {
  7044. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7045. if err != nil {
  7046. logs.Error(err)
  7047. tx.Rollback()
  7048. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7049. return
  7050. }
  7051. }
  7052. }
  7053. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7054. if err != nil {
  7055. logs.Error(err)
  7056. tx.Rollback()
  7057. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7058. return
  7059. }
  7060. } else {
  7061. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7062. if err != nil {
  7063. logs.Error(err)
  7064. tx.Rollback()
  7065. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7066. return
  7067. }
  7068. }
  7069. }
  7070. err := tx.Commit()
  7071. if err != nil {
  7072. logs.Error(err)
  7073. tx.Rollback()
  7074. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7075. return
  7076. }
  7077. appG.Response(http.StatusOK, e.SUCCESS, true)
  7078. }
  7079. func Decimal(value float64) float64 {
  7080. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7081. return value
  7082. }
  7083. func UpdateDailyData(c *gin.Context) {
  7084. appG := app.Gin{C: c}
  7085. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7086. parammaps := gofasion.NewFasion(string(dataByte))
  7087. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7088. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7089. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7090. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7091. date := parammaps.Get("date").ValueStr()
  7092. tx := restful.Engine.NewSession()
  7093. defer tx.Close()
  7094. 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()
  7095. if err != nil {
  7096. logs.Error("UpdateDailyData-error-0:", err)
  7097. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7098. return
  7099. }
  7100. if count > 0 {
  7101. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7102. return
  7103. }
  7104. tx.Begin()
  7105. if location == 0 {
  7106. fid := parammaps.Get("fid").ValueStr()
  7107. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7108. if err != nil {
  7109. logs.Error("UpdateDailyData-error-1:", err)
  7110. tx.Rollback()
  7111. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7112. return
  7113. }
  7114. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7115. if err != nil {
  7116. logs.Error("UpdateDailyData-error-1:", err)
  7117. tx.Rollback()
  7118. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7119. return
  7120. }
  7121. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7122. if err != nil {
  7123. fmt.Println("Error:", err)
  7124. return
  7125. }
  7126. actualWeight := weight - num
  7127. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7128. if err != nil {
  7129. logs.Error("UpdateDailyData-error-2:", err)
  7130. tx.Rollback()
  7131. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7132. return
  7133. }
  7134. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7135. if err != nil {
  7136. logs.Error("UpdateDailyData-error-3:", err)
  7137. tx.Rollback()
  7138. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7139. return
  7140. }
  7141. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7142. if err != nil {
  7143. logs.Error("UpdateDailyData-error-4:", err)
  7144. tx.Rollback()
  7145. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7146. return
  7147. }
  7148. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7149. if err != nil {
  7150. logs.Error("UpdateDailyData-error-5:", err)
  7151. tx.Rollback()
  7152. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7153. return
  7154. }
  7155. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7156. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7157. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7158. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7159. if err != nil {
  7160. fmt.Println("Error:", err)
  7161. return
  7162. }
  7163. // actual := actualWeight / float64(len(downloadedplanList))
  7164. for _, item := range downloadedplanList {
  7165. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7166. if err != nil {
  7167. fmt.Println("Error:", err)
  7168. return
  7169. }
  7170. actual := itemLweight / lweight * actualWeight
  7171. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7172. if err != nil {
  7173. logs.Error("UpdateDailyData-error-6:", err)
  7174. tx.Rollback()
  7175. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7176. return
  7177. }
  7178. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7179. if err != nil {
  7180. logs.Error("UpdateDailyData-error-7:", err)
  7181. tx.Rollback()
  7182. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7183. return
  7184. }
  7185. _, 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()
  7186. if err != nil {
  7187. logs.Error("UpdateDailyData-error-8:", err)
  7188. tx.Rollback()
  7189. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7190. return
  7191. }
  7192. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7193. if err != nil {
  7194. logs.Error("UpdateDailyData-error-9:", err)
  7195. tx.Rollback()
  7196. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7197. return
  7198. }
  7199. }
  7200. } else {
  7201. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7202. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7203. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7204. // if err != nil {
  7205. // fmt.Println("Error:", err)
  7206. // return
  7207. // }
  7208. for _, item := range downloadedplanList {
  7209. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7210. if err != nil {
  7211. logs.Error("UpdateDailyData-error-6:", err)
  7212. tx.Rollback()
  7213. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7214. return
  7215. }
  7216. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7217. item["lweight"], actualWeight, item["id"]).Execute()
  7218. if err != nil {
  7219. logs.Error("UpdateDailyData-error-7:", err)
  7220. tx.Rollback()
  7221. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7222. return
  7223. }
  7224. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7225. where pid = ?`, item["id"]).Execute()
  7226. if err != nil {
  7227. logs.Error("UpdateDailyData-error-8:", err)
  7228. tx.Rollback()
  7229. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7230. return
  7231. }
  7232. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7233. if err != nil {
  7234. logs.Error("UpdateDailyData-error-9:", err)
  7235. tx.Rollback()
  7236. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7237. return
  7238. }
  7239. }
  7240. }
  7241. } else {
  7242. fbarid := parammaps.Get("fbarid").ValueStr()
  7243. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7244. if err != nil {
  7245. logs.Error("UpdateDailyData-error-10:", err)
  7246. tx.Rollback()
  7247. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7248. return
  7249. }
  7250. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7251. if err != nil {
  7252. logs.Error("UpdateDailyData-error-1:", err)
  7253. tx.Rollback()
  7254. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7255. return
  7256. }
  7257. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7258. if err != nil {
  7259. fmt.Println("Error:", err)
  7260. return
  7261. }
  7262. actualWeight := weight - num
  7263. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7264. if err != nil {
  7265. logs.Error("UpdateDailyData-error-11:", err)
  7266. tx.Rollback()
  7267. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7268. return
  7269. }
  7270. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7271. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7272. if err != nil {
  7273. logs.Error("UpdateDailyData-error-12:", err)
  7274. tx.Rollback()
  7275. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7276. return
  7277. }
  7278. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7279. where pid = ? `, pid).Execute()
  7280. if err != nil {
  7281. logs.Error("UpdateDailyData-error-13:", err)
  7282. tx.Rollback()
  7283. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7284. return
  7285. }
  7286. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7287. if err != nil {
  7288. logs.Error("UpdateDailyData-error-14:", err)
  7289. tx.Rollback()
  7290. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7291. return
  7292. }
  7293. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7294. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7295. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7296. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7297. if err != nil {
  7298. fmt.Println("Error:", err)
  7299. return
  7300. }
  7301. for _, item := range downloadedplanList {
  7302. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7303. if err != nil {
  7304. fmt.Println("Error:", err)
  7305. return
  7306. }
  7307. actual := itemLweight / lweight * actualWeight
  7308. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7309. if err != nil {
  7310. logs.Error("UpdateDailyData-error-6:", err)
  7311. tx.Rollback()
  7312. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7313. return
  7314. }
  7315. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7316. if err != nil {
  7317. logs.Error("UpdateDailyData-error-7:", err)
  7318. tx.Rollback()
  7319. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7320. return
  7321. }
  7322. _, 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()
  7323. if err != nil {
  7324. logs.Error("UpdateDailyData-error-8:", err)
  7325. tx.Rollback()
  7326. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7327. return
  7328. }
  7329. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7330. if err != nil {
  7331. logs.Error("UpdateDailyData-error-9:", err)
  7332. tx.Rollback()
  7333. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7334. return
  7335. }
  7336. }
  7337. } else {
  7338. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7339. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7340. for _, item := range downloadedplanList {
  7341. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7342. // if err != nil {
  7343. // fmt.Println("Error:", err)
  7344. // return
  7345. // }
  7346. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7347. if err != nil {
  7348. logs.Error("UpdateDailyData-error-6:", err)
  7349. tx.Rollback()
  7350. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7351. return
  7352. }
  7353. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7354. item["lweight"], actualWeight, item["id"]).Execute()
  7355. if err != nil {
  7356. logs.Error("UpdateDailyData-error-7:", err)
  7357. tx.Rollback()
  7358. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7359. return
  7360. }
  7361. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7362. where pid = ?`, item["id"]).Execute()
  7363. if err != nil {
  7364. logs.Error("UpdateDailyData-error-8:", err)
  7365. tx.Rollback()
  7366. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7367. return
  7368. }
  7369. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7370. if err != nil {
  7371. logs.Error("UpdateDailyData-error-9:", err)
  7372. tx.Rollback()
  7373. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7374. return
  7375. }
  7376. }
  7377. }
  7378. }
  7379. err = tx.Commit()
  7380. if err != nil {
  7381. logs.Error("UpdateDailyData-error-20:", err)
  7382. tx.Rollback()
  7383. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7384. return
  7385. }
  7386. appG.Response(http.StatusOK, e.SUCCESS, true)
  7387. }
  7388. func GetFormulaStatistics(c *gin.Context) {
  7389. appG := app.Gin{C: c}
  7390. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7391. parammaps := gofasion.NewFasion(string(dataByte))
  7392. startTime := parammaps.Get("startTime").ValueStr()
  7393. endTime := parammaps.Get("endTime").ValueStr()
  7394. pastureId := parammaps.Get("pastureId").ValueStr()
  7395. tx := restful.Engine.NewSession()
  7396. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7397. if err != nil {
  7398. logs.Error("GetFormulaStatistics-error-1:", err)
  7399. tx.Rollback()
  7400. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7401. return
  7402. }
  7403. var feedtemplet, dateList []string
  7404. for _, f := range feedtempletList {
  7405. feedtemplet = append(feedtemplet, f["tname"].(string))
  7406. }
  7407. layout := "2006-01-02"
  7408. // s := "2023-05-01"
  7409. // e := "2023-05-23"
  7410. start, err := time.Parse(layout, startTime)
  7411. if err != nil {
  7412. fmt.Println(err)
  7413. return
  7414. }
  7415. end, err := time.Parse(layout, endTime)
  7416. if err != nil {
  7417. fmt.Println(err)
  7418. return
  7419. }
  7420. end = end.AddDate(0, 0, 1)
  7421. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7422. dateList = append(dateList, d.Format("2006-01-02"))
  7423. }
  7424. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7425. 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= ?
  7426. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7427. if err != nil {
  7428. logs.Error("GetFormulaStatistics-error-2:", err)
  7429. tx.Rollback()
  7430. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7431. return
  7432. }
  7433. var data2 [][]interface{}
  7434. for _, f := range feedtemplet {
  7435. var data1 []interface{}
  7436. for _, date := range dateList {
  7437. exist := false
  7438. for _, item := range downloadedplanList {
  7439. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7440. data1 = append(data1, item["total"])
  7441. exist = true
  7442. break
  7443. }
  7444. }
  7445. if !exist {
  7446. data1 = append(data1, 0)
  7447. }
  7448. }
  7449. data2 = append(data2, data1)
  7450. }
  7451. //前端让加的
  7452. feedtemplet = append(feedtemplet, "")
  7453. {
  7454. var data1 []interface{}
  7455. for _, f := range dateList {
  7456. // f = f + "\n"
  7457. fmt.Println(f)
  7458. data1 = append(data1, 0)
  7459. }
  7460. data2 = append(data2, data1)
  7461. }
  7462. resp := make(map[string]interface{}, 0)
  7463. resp["xdata"] = dateList
  7464. resp["data1"] = feedtemplet
  7465. resp["data2"] = data2
  7466. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7467. }
  7468. func GetPlanData(c *gin.Context) {
  7469. appG := app.Gin{C: c}
  7470. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7471. fsion := gofasion.NewFasion(string(dataByte))
  7472. sqlnamestr := fsion.Get("name").ValueStr()
  7473. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7474. offset := fsion.Get("offset").ValueDefaultInt(0)
  7475. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7476. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7477. month := fsion.Get("month").ValueDefaultStr("map")
  7478. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7479. tx := restful.Engine.NewSession()
  7480. err := tx.Begin()
  7481. defer func() {
  7482. switch {
  7483. case err != nil:
  7484. if tx != nil {
  7485. tx.Rollback()
  7486. }
  7487. default:
  7488. if tx != nil {
  7489. err = tx.Commit()
  7490. }
  7491. }
  7492. if tx != nil {
  7493. tx.Close()
  7494. }
  7495. }()
  7496. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7497. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7498. if sql != "" {
  7499. s_params := make([]interface{}, 0)
  7500. if fsion.HasKey("parammaps") {
  7501. parammaps := fsion.Get("parammaps")
  7502. paramslist := strings.Split(p, ",")
  7503. if len(paramslist) > 0 && p != "" {
  7504. for _, value := range paramslist {
  7505. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7506. if tempv, exists := c.Get("jwt_username"); exists {
  7507. s_params = append(s_params, tempv.(string))
  7508. } else {
  7509. s_params = append(s_params, "")
  7510. }
  7511. } else {
  7512. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7513. }
  7514. }
  7515. }
  7516. }
  7517. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7518. if err != nil {
  7519. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7520. } else {
  7521. paramslist1 := strings.Split(p1, ",")
  7522. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7523. s_params1 := make([]interface{}, 0)
  7524. if len(paramslist1) > 0 && p1 != "" {
  7525. for _, v := range paramslist1 {
  7526. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7527. }
  7528. }
  7529. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7530. for _, item := range arr {
  7531. trgaddressList := []string{}
  7532. if _, ok := item["trgaddress"]; ok {
  7533. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7534. for _, str := range trgaddressList1 {
  7535. if str != "" {
  7536. trgaddressList = append(trgaddressList, str)
  7537. }
  7538. }
  7539. }
  7540. item["trgaddressList"] = trgaddressList
  7541. }
  7542. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7543. }
  7544. // var wg sync.WaitGroup
  7545. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7546. // wg.Add(1)
  7547. // go func(value map[string]interface{}) {
  7548. // defer wg.Done()
  7549. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7550. // }(value)
  7551. // }
  7552. // wg.Wait()
  7553. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7554. }
  7555. } else {
  7556. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7557. }
  7558. }
  7559. func PostPlanData(c *gin.Context) {
  7560. appG := app.Gin{C: c}
  7561. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7562. fsion := gofasion.NewFasion(string(dataByte))
  7563. logging.Info("PostRJSBData err: ", string(dataByte))
  7564. s_params := make([]interface{}, 0)
  7565. tx := restful.Engine.NewSession()
  7566. err := tx.Begin()
  7567. defer func() {
  7568. switch {
  7569. case err != nil:
  7570. if tx != nil {
  7571. tx.Rollback()
  7572. }
  7573. default:
  7574. if tx != nil {
  7575. err = tx.Commit()
  7576. }
  7577. }
  7578. if tx != nil {
  7579. tx.Close()
  7580. }
  7581. }()
  7582. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7583. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7584. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7585. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7586. if !fsion.HasKey("parammaps") {
  7587. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7588. return
  7589. }
  7590. parammaps := fsion.Get("parammaps")
  7591. // paramslist := strings.Split(p, ",")
  7592. // if len(paramslist) > 0 && p != "" {
  7593. // for _, value := range paramslist {
  7594. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7595. // }
  7596. // }
  7597. // _, err = tx.SQL(sql, s_params...).Execute()
  7598. // if err != nil {
  7599. // logging.Error("PostRJSBData err: ", err)
  7600. // msg := geterrmsg(err.Error())
  7601. // appG.Response(http.StatusOK, e.ERROR, msg)
  7602. // return
  7603. // }
  7604. s_params = make([]interface{}, 0)
  7605. paramslist := strings.Split(p1, ",")
  7606. if len(paramslist) > 0 && p1 != "" {
  7607. for _, value := range paramslist {
  7608. // if value == "ID" {
  7609. // id := parammaps.Get("ID").ValueStr()
  7610. // pastureid := parammaps.Get("pastureid").ValueStr()
  7611. // 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
  7612. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7613. // if err != nil {
  7614. // logging.Error("PostRJSBData err: ", err)
  7615. // msg := geterrmsg(err.Error())
  7616. // appG.Response(http.StatusOK, e.ERROR, msg)
  7617. // return
  7618. // }
  7619. // for _, item := range datalist {
  7620. // id = item["id"]
  7621. // }
  7622. // s_params = append(s_params, id)
  7623. // } else {
  7624. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7625. // }
  7626. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7627. }
  7628. }
  7629. _, err = tx.SQL(sql1, s_params...).Execute()
  7630. if err != nil {
  7631. logging.Error("PostRJSBData1 err: ", err)
  7632. msg := geterrmsg(err.Error())
  7633. appG.Response(http.StatusOK, e.ERROR, msg)
  7634. return
  7635. }
  7636. s_params = make([]interface{}, 0)
  7637. paramslist = strings.Split(p2, ",")
  7638. if len(paramslist) > 0 && p2 != "" {
  7639. for _, value := range paramslist {
  7640. if value == "ID" {
  7641. id := parammaps.Get("ID").ValueStr()
  7642. pastureid := parammaps.Get("pastureid").ValueStr()
  7643. 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
  7644. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7645. if err != nil {
  7646. logging.Error("PostRJSBData err: ", err)
  7647. msg := geterrmsg(err.Error())
  7648. appG.Response(http.StatusOK, e.ERROR, msg)
  7649. return
  7650. }
  7651. for _, item := range datalist {
  7652. id = item["id"]
  7653. }
  7654. s_params = append(s_params, id)
  7655. } else {
  7656. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7657. }
  7658. }
  7659. }
  7660. _, err = tx.SQL(sql2, s_params...).Execute()
  7661. if err != nil {
  7662. logging.Error("PostRJSBData2 err: ", err)
  7663. msg := geterrmsg(err.Error())
  7664. appG.Response(http.StatusOK, e.ERROR, msg)
  7665. return
  7666. }
  7667. s_params = make([]interface{}, 0)
  7668. paramslist = strings.Split(p3, ",")
  7669. if len(paramslist) > 0 && p3 != "" {
  7670. for _, value := range paramslist {
  7671. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7672. }
  7673. }
  7674. _, err = tx.SQL(sql3, s_params...).Execute()
  7675. if err != nil {
  7676. logging.Error("PostRJSBData3 err: ", err)
  7677. msg := geterrmsg(err.Error())
  7678. appG.Response(http.StatusOK, e.ERROR, msg)
  7679. return
  7680. }
  7681. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7682. }
  7683. func CheckFeedTrgaddress(c *gin.Context) {
  7684. appG := app.Gin{C: c}
  7685. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7686. fsion := gofasion.NewFasion(string(dataByte))
  7687. fclassid := fsion.Get("fclassid").ValueStr()
  7688. feedId := fsion.Get("feedId").ValueStr()
  7689. backup1 := fsion.Get("backup1").ValueStr()
  7690. backup1List := strings.Split(backup1, ",")
  7691. tx := restful.Engine.NewSession()
  7692. defer tx.Close()
  7693. // if backup1 != "" {
  7694. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7695. for _, feed := range feedList {
  7696. if feed["backup1"] == "" {
  7697. continue
  7698. }
  7699. feedbackupList := strings.Split(feed["backup1"], ",")
  7700. for _, feedbackup := range feedbackupList {
  7701. for _, backup := range backup1List {
  7702. if feedbackup == backup {
  7703. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7704. return
  7705. }
  7706. }
  7707. }
  7708. }
  7709. // }
  7710. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7711. }
  7712. func ThiGetDataByName(c *gin.Context) {
  7713. appG := app.Gin{C: c}
  7714. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7715. fsion := gofasion.NewFasion(string(dataByte))
  7716. sqlnamestr := fsion.Get("name").ValueStr()
  7717. offset := fsion.Get("offset").ValueDefaultInt(0)
  7718. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7719. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7720. tx := restful.Engine.NewSession()
  7721. err := tx.Begin()
  7722. defer func() {
  7723. switch {
  7724. case err != nil:
  7725. logging.Error("tx.Begin 事务启动失败__error:", err)
  7726. if tx != nil {
  7727. tx.Rollback()
  7728. }
  7729. default:
  7730. if tx != nil {
  7731. err = tx.Commit()
  7732. }
  7733. }
  7734. if tx != nil {
  7735. tx.Close()
  7736. }
  7737. }()
  7738. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7739. if sql != "" {
  7740. s_params := make([]interface{}, 0)
  7741. if fsion.HasKey("parammaps") {
  7742. parammaps := fsion.Get("parammaps")
  7743. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7744. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7745. }
  7746. paramslist := strings.Split(p, ",")
  7747. if len(paramslist) > 0 && p != "" {
  7748. for _, value := range paramslist {
  7749. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7750. if tempv, exists := c.Get("jwt_username"); exists {
  7751. s_params = append(s_params, tempv.(string))
  7752. } else {
  7753. s_params = append(s_params, "")
  7754. }
  7755. } else {
  7756. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7757. }
  7758. }
  7759. }
  7760. } else if fsion.HasKey("params") {
  7761. params := fsion.Get("params").Array()
  7762. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7763. for _, v_params := range params {
  7764. s_params = append(s_params, v_params.ValueStr())
  7765. }
  7766. }
  7767. if returntype == "xlsx" {
  7768. var xlsxfile *xlsx.File
  7769. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7770. //c.File("c:/dd.xlsx")
  7771. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7772. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7773. c.Header("Content-Transfer-Encoding", "binary")
  7774. _ = xlsxfile.Write(c.Writer)
  7775. } else {
  7776. if sqlnamestr == "getHomepageStr" {
  7777. parammaps := fsion.Get("parammaps")
  7778. pastureid := parammaps.Get("pastureid").ValueStr()
  7779. var montimeList []float64
  7780. var montime float64
  7781. var wg sync.WaitGroup
  7782. now := time.Now()
  7783. for i := 0; i < 30; i++ {
  7784. wg.Add(1)
  7785. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7786. go func(nowstr string) {
  7787. defer wg.Done()
  7788. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7789. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7790. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7791. montimeList = append(montimeList, m)
  7792. }(nowstr)
  7793. }
  7794. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7795. if err != nil {
  7796. logging.Error("GetDataByName err: ", err)
  7797. msg := geterrmsg(err.Error())
  7798. appG.Response(http.StatusOK, e.ERROR, msg)
  7799. }
  7800. wg.Wait()
  7801. for _, m := range montimeList {
  7802. montime += m
  7803. }
  7804. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7805. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7806. return
  7807. }
  7808. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7809. if err != nil {
  7810. logging.Error("GetDataByName err: ", err)
  7811. msg := geterrmsg(err.Error())
  7812. appG.Response(http.StatusOK, e.ERROR, msg)
  7813. } else {
  7814. if sqlnamestr == "getFeedTrgaddressList" {
  7815. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7816. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7817. trgaddressList := []string{}
  7818. for _, str := range trgaddressList1 {
  7819. if str != "" {
  7820. trgaddressList = append(trgaddressList, str)
  7821. }
  7822. }
  7823. item["trgaddressList"] = trgaddressList
  7824. }
  7825. }
  7826. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7827. }
  7828. }
  7829. } else {
  7830. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7831. }
  7832. }
  7833. // func ToggleCcount(c *gin.Context) {
  7834. // appG := app.Gin{C: c}
  7835. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7836. // fsion := gofasion.NewFasion(string(dataByte))
  7837. // // 0 实际 1 软件
  7838. // status := fsion.Get("status").ValueDefaultInt64(0)
  7839. // pastureId := fsion.Get("pastureId").ValueStr()
  7840. // tx := restful.Engine.NewSession()
  7841. // err := tx.Begin()
  7842. // defer func() {
  7843. // switch {
  7844. // case err != nil:
  7845. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7846. // if tx != nil {
  7847. // tx.Rollback()
  7848. // }
  7849. // default:
  7850. // if tx != nil {
  7851. // err = tx.Commit()
  7852. // }
  7853. // }
  7854. // if tx != nil {
  7855. // tx.Close()
  7856. // }
  7857. // }()
  7858. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7859. // if err != nil {
  7860. // logs.Error(err)
  7861. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7862. // return
  7863. // }
  7864. // for _, bar := range barList {
  7865. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7866. // if err != nil {
  7867. // logs.Error(err)
  7868. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7869. // return
  7870. // }
  7871. // if !exist {
  7872. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7873. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7874. // if err != nil {
  7875. // logs.Error(err)
  7876. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7877. // return
  7878. // }
  7879. // }
  7880. // }
  7881. // if status == 0 {
  7882. // tx.Exec(`update feedp set ccount = actualcount `)
  7883. // }else{
  7884. // tx.Exec(`update feedp set ccount = softccount `)
  7885. // }
  7886. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7887. // if err != nil {
  7888. // logs.Error(err)
  7889. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7890. // return
  7891. // }
  7892. // for _, feedpData :=range feedpList{
  7893. // var feedpargs []interface{}
  7894. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7895. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7896. // if _, ok := feedpData["ftname"]; ok {
  7897. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7898. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7899. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7900. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7901. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7902. // } else {
  7903. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7904. // }
  7905. // if _, ok := feedpData["ptsfname"]; ok {
  7906. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7907. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7908. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7909. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7910. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7911. // } else {
  7912. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7913. // }
  7914. // upFeedpSql += " where barname = ? and pastureid = ? "
  7915. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7916. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7917. // if err != nil {
  7918. // logs.Error(err)
  7919. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7920. // return
  7921. // }
  7922. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7923. // if err != nil {
  7924. // logs.Error(err)
  7925. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7926. // return
  7927. // }
  7928. // if !exist1 {
  7929. // _, 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) `,
  7930. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7931. // if err != nil {
  7932. // logs.Error(err)
  7933. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7934. // return
  7935. // }
  7936. // }
  7937. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7938. // if err != nil {
  7939. // logs.Error(err)
  7940. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7941. // return
  7942. // }
  7943. // if !exist2 {
  7944. // _, 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) `,
  7945. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7946. // if err != nil {
  7947. // logs.Error(err)
  7948. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7949. // return
  7950. // }
  7951. // }
  7952. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7953. // if err != nil {
  7954. // logs.Error(err)
  7955. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7956. // return
  7957. // }
  7958. // if !exist3 {
  7959. // _, 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) `,
  7960. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7961. // if err != nil {
  7962. // logs.Error(err)
  7963. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7964. // return
  7965. // }
  7966. // }
  7967. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7968. // if err != nil {
  7969. // logs.Error(err)
  7970. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7971. // return
  7972. // }
  7973. // if !exist4 {
  7974. // _, 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) `,
  7975. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7976. // if err != nil {
  7977. // logs.Error(err)
  7978. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7979. // return
  7980. // }
  7981. // }
  7982. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7983. // if err != nil {
  7984. // logs.Error(err)
  7985. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7986. // return
  7987. // }
  7988. // if !exist5 {
  7989. // _, 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) `,
  7990. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7991. // if err != nil {
  7992. // logs.Error(err)
  7993. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7994. // return
  7995. // }
  7996. // }
  7997. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7998. // if err != nil {
  7999. // logs.Error(err)
  8000. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8001. // return
  8002. // }
  8003. // if !exist6 {
  8004. // _, 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) `,
  8005. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8006. // if err != nil {
  8007. // logs.Error(err)
  8008. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8009. // return
  8010. // }
  8011. // }
  8012. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8013. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8014. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8015. // and pastureid = ? and times = ?`
  8016. // var fpdargs1 []interface{}
  8017. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8018. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8019. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8020. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8021. // if err != nil {
  8022. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8023. // return
  8024. // }
  8025. // var fpdargs2 []interface{}
  8026. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8027. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8028. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8029. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8030. // if err != nil {
  8031. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8032. // return
  8033. // }
  8034. // var fpdargs3 []interface{}
  8035. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8036. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8037. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8038. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8039. // if err != nil {
  8040. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8041. // return
  8042. // }
  8043. // var fpdargs4 []interface{}
  8044. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8045. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8046. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8047. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8048. // if err != nil {
  8049. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8050. // return
  8051. // }
  8052. // var fpdargs5 []interface{}
  8053. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8054. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8055. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8056. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8057. // if err != nil {
  8058. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8059. // return
  8060. // }
  8061. // var fpdargs6 []interface{}
  8062. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8063. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8064. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8065. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8066. // if err != nil {
  8067. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8068. // return
  8069. // }
  8070. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8071. // 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()
  8072. // if err != nil {
  8073. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8074. // return
  8075. // }
  8076. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8077. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8078. // upFpdetailList := make([]*upFpdetail, 0)
  8079. // for _, newfpd := range newList {
  8080. // for _, oldfpd := range oldFpdList {
  8081. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8082. // var oldweight, newweight float64
  8083. // if oldfpd["weight"] != nil {
  8084. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8085. // }
  8086. // if newfpd["weight"] != nil {
  8087. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8088. // }
  8089. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8090. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8091. // Old: oldweight,
  8092. // New: newweight,
  8093. // Times: newfpd["times"].(int64),
  8094. // Ptid: newfpd["ptid"].(int64),
  8095. // Fweight: fweight,
  8096. // Id: oldfpd["id"].(int64),
  8097. // })
  8098. // break
  8099. // }
  8100. // }
  8101. // }
  8102. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8103. // }
  8104. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8105. // }
  8106. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8107. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8108. if err != nil {
  8109. return err
  8110. }
  8111. for _, item := range feedpList {
  8112. // if item["ftid"].(string) != data["ftid"].(string) {
  8113. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8114. if err != nil {
  8115. return err
  8116. }
  8117. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8118. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8119. if err != nil {
  8120. return err
  8121. }
  8122. // }
  8123. }
  8124. return nil
  8125. }
  8126. func PostPlanDatas(c *gin.Context) {
  8127. appG := app.Gin{C: c}
  8128. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8129. fsions := gofasion.NewFasion(string(dataByte))
  8130. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8131. tx := restful.Engine.NewSession()
  8132. err := tx.Begin()
  8133. defer func() {
  8134. switch {
  8135. case err != nil:
  8136. if tx != nil {
  8137. tx.Rollback()
  8138. }
  8139. default:
  8140. if tx != nil {
  8141. err = tx.Commit()
  8142. }
  8143. }
  8144. if tx != nil {
  8145. tx.Close()
  8146. }
  8147. }()
  8148. pastureId := fsions.Get("pastureid").ValueStr()
  8149. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8150. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8151. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8152. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8153. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8154. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8155. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8156. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8157. for _, parammaps := range fsions.Get("arrList").Array() {
  8158. fmt.Println(parammaps.Json())
  8159. if parammaps.Json() == "null" {
  8160. continue
  8161. }
  8162. // if !fsion.HasKey("arrList") {
  8163. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8164. // return
  8165. // continue
  8166. // }
  8167. // parammaps := fsion.Get("arrList")
  8168. s_params := make([]interface{}, 0)
  8169. // paramslist := strings.Split(p, ",")
  8170. // if len(paramslist) > 0 && p != "" {
  8171. // for _, value := range paramslist {
  8172. // if value == "pastureid" {
  8173. // s_params = append(s_params, pastureId)
  8174. // } else {
  8175. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8176. // }
  8177. // }
  8178. // }
  8179. // _, err = tx.SQL(sql, s_params...).Execute()
  8180. // if err != nil {
  8181. // logging.Error("PostRJSBData err: ", err)
  8182. // msg := geterrmsg(err.Error())
  8183. // appG.Response(http.StatusOK, e.ERROR, msg)
  8184. // return
  8185. // }
  8186. s_params = make([]interface{}, 0)
  8187. paramslist := strings.Split(p1, ",")
  8188. if len(paramslist) > 0 && p1 != "" {
  8189. for _, value := range paramslist {
  8190. // if value == "ID" {
  8191. // id := parammaps.Get("ID").ValueStr()
  8192. // pastureid := parammaps.Get("pastureid").ValueStr()
  8193. // 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
  8194. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8195. // if err != nil {
  8196. // logging.Error("PostRJSBData err: ", err)
  8197. // msg := geterrmsg(err.Error())
  8198. // appG.Response(http.StatusOK, e.ERROR, msg)
  8199. // return
  8200. // }
  8201. // for _, item := range datalist {
  8202. // id = item["id"]
  8203. // }
  8204. // s_params = append(s_params, id)
  8205. // } else {
  8206. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8207. // }
  8208. if value == "pastureid" {
  8209. s_params = append(s_params, pastureId)
  8210. } else {
  8211. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8212. }
  8213. }
  8214. }
  8215. _, err = tx.SQL(sql1, s_params...).Execute()
  8216. if err != nil {
  8217. logging.Error("PostRJSBData1 err: ", err)
  8218. msg := geterrmsg(err.Error())
  8219. appG.Response(http.StatusOK, e.ERROR, msg)
  8220. return
  8221. }
  8222. s_params = make([]interface{}, 0)
  8223. paramslist = strings.Split(p2, ",")
  8224. if len(paramslist) > 0 && p2 != "" {
  8225. for _, value := range paramslist {
  8226. if value == "ID" {
  8227. id := parammaps.Get("ID").ValueStr()
  8228. pastureid := parammaps.Get("pastureid").ValueStr()
  8229. 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
  8230. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8231. if err != nil {
  8232. logging.Error("PostRJSBData err: ", err)
  8233. msg := geterrmsg(err.Error())
  8234. appG.Response(http.StatusOK, e.ERROR, msg)
  8235. return
  8236. }
  8237. for _, item := range datalist {
  8238. id = item["id"]
  8239. }
  8240. s_params = append(s_params, id)
  8241. } else if value == "pastureid" {
  8242. s_params = append(s_params, pastureId)
  8243. } else {
  8244. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8245. }
  8246. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8247. }
  8248. }
  8249. _, err = tx.SQL(sql2, s_params...).Execute()
  8250. if err != nil {
  8251. logging.Error("PostRJSBData2 err: ", err)
  8252. msg := geterrmsg(err.Error())
  8253. appG.Response(http.StatusOK, e.ERROR, msg)
  8254. return
  8255. }
  8256. s_params = make([]interface{}, 0)
  8257. paramslist = strings.Split(p3, ",")
  8258. if len(paramslist) > 0 && p3 != "" {
  8259. for _, value := range paramslist {
  8260. if value == "pastureid" {
  8261. s_params = append(s_params, pastureId)
  8262. } else {
  8263. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8264. }
  8265. }
  8266. }
  8267. _, err = tx.SQL(sql3, s_params...).Execute()
  8268. if err != nil {
  8269. logging.Error("PostRJSBData3 err: ", err)
  8270. msg := geterrmsg(err.Error())
  8271. appG.Response(http.StatusOK, e.ERROR, msg)
  8272. return
  8273. }
  8274. }
  8275. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8276. }
  8277. func FpdBatchEdit(c *gin.Context) {
  8278. appG := app.Gin{C: c}
  8279. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8280. fsions := gofasion.NewFasion(string(dataByte))
  8281. barList := fsions.Get("barList").Array()
  8282. pastureid := fsions.Get("pastureId").ValueStr()
  8283. tx := restful.Engine.NewSession()
  8284. defer tx.Close()
  8285. 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
  8286. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8287. if err != nil {
  8288. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8289. return
  8290. }
  8291. for _, barFsions := range barList {
  8292. dataexcel := make(map[string]interface{}, 0)
  8293. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8294. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8295. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8296. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8297. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8298. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8299. continue
  8300. }
  8301. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8302. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8303. if err != nil {
  8304. logs.Error(err)
  8305. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8306. return
  8307. }
  8308. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8309. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8310. if err != nil {
  8311. logs.Error(err)
  8312. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8313. return
  8314. }
  8315. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8316. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8317. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8318. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8319. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8320. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8321. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8322. if err != nil {
  8323. logs.Error(err)
  8324. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8325. return
  8326. }
  8327. if !ftexist {
  8328. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8329. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8330. if err != nil {
  8331. logs.Error(err)
  8332. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8333. return
  8334. }
  8335. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8336. if err != nil {
  8337. logs.Error(err)
  8338. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8339. return
  8340. }
  8341. }
  8342. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8343. if err != nil {
  8344. logs.Error(err)
  8345. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8346. return
  8347. }
  8348. if !exist {
  8349. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8350. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8351. if err != nil {
  8352. logs.Error(err)
  8353. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8354. return
  8355. }
  8356. }
  8357. var feedpargs []interface{}
  8358. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8359. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8360. if _, ok := dataexcel["ftname"]; ok {
  8361. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8362. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8363. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8364. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8365. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8366. } else {
  8367. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8368. }
  8369. if _, ok := dataexcel["ptsfname"]; ok {
  8370. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8371. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8372. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8373. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8374. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8375. } else {
  8376. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8377. }
  8378. upFeedpSql += " where barname = ? and pastureid = ? "
  8379. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8380. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8381. if err != nil {
  8382. logs.Error(err)
  8383. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8384. return
  8385. }
  8386. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8387. if err != nil {
  8388. logs.Error(err)
  8389. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8390. return
  8391. }
  8392. if !exist1 {
  8393. _, 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) `,
  8394. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8395. if err != nil {
  8396. logs.Error(err)
  8397. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8398. return
  8399. }
  8400. }
  8401. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8402. if err != nil {
  8403. logs.Error(err)
  8404. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8405. return
  8406. }
  8407. if !exist2 {
  8408. _, 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) `,
  8409. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8410. if err != nil {
  8411. logs.Error(err)
  8412. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8413. return
  8414. }
  8415. }
  8416. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8417. if err != nil {
  8418. logs.Error(err)
  8419. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8420. return
  8421. }
  8422. if !exist3 {
  8423. _, 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) `,
  8424. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8425. if err != nil {
  8426. logs.Error(err)
  8427. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8428. return
  8429. }
  8430. }
  8431. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8432. if err != nil {
  8433. logs.Error(err)
  8434. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8435. return
  8436. }
  8437. if !exist4 {
  8438. _, 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) `,
  8439. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8440. if err != nil {
  8441. logs.Error(err)
  8442. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8443. return
  8444. }
  8445. }
  8446. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8447. if err != nil {
  8448. logs.Error(err)
  8449. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8450. return
  8451. }
  8452. if !exist5 {
  8453. _, 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) `,
  8454. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8455. if err != nil {
  8456. logs.Error(err)
  8457. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8458. return
  8459. }
  8460. }
  8461. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8462. if err != nil {
  8463. logs.Error(err)
  8464. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8465. return
  8466. }
  8467. if !exist6 {
  8468. _, 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) `,
  8469. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8470. if err != nil {
  8471. logs.Error(err)
  8472. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8473. return
  8474. }
  8475. }
  8476. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8477. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8478. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8479. and pastureid = ? and times = ?`
  8480. var fpdargs1 []interface{}
  8481. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8482. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8483. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8484. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8485. if err != nil {
  8486. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8487. return
  8488. }
  8489. var fpdargs2 []interface{}
  8490. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8491. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8492. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8493. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8494. if err != nil {
  8495. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8496. return
  8497. }
  8498. var fpdargs3 []interface{}
  8499. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8500. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8501. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8502. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8503. if err != nil {
  8504. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8505. return
  8506. }
  8507. var fpdargs4 []interface{}
  8508. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8509. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8510. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8511. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8512. if err != nil {
  8513. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8514. return
  8515. }
  8516. var fpdargs5 []interface{}
  8517. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8518. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8519. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8520. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8521. if err != nil {
  8522. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8523. return
  8524. }
  8525. var fpdargs6 []interface{}
  8526. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8527. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8528. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8529. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8530. if err != nil {
  8531. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8532. return
  8533. }
  8534. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8535. 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()
  8536. if err != nil {
  8537. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8538. return
  8539. }
  8540. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8541. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8542. upFpdetailList := make([]*upFpdetail, 0)
  8543. for _, newfpd := range newList {
  8544. for _, oldfpd := range oldFpdList {
  8545. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8546. var oldweight, newweight float64
  8547. if oldfpd["weight"] != nil {
  8548. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8549. }
  8550. if newfpd["weight"] != nil {
  8551. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8552. }
  8553. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8554. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8555. Old: oldweight,
  8556. New: newweight,
  8557. Times: newfpd["times"].(int64),
  8558. Ptid: newfpd["ptid"].(int64),
  8559. Fweight: fweight,
  8560. Id: oldfpd["id"].(int64),
  8561. })
  8562. break
  8563. }
  8564. }
  8565. }
  8566. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8567. }
  8568. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8569. }
  8570. func UdBarSync(c *gin.Context) {
  8571. appG := app.Gin{C: c}
  8572. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8573. fsions := gofasion.NewFasion(string(dataByte))
  8574. pastureid := fsions.Get("pastureId").ValueStr()
  8575. tx := restful.Engine.NewSession()
  8576. defer tx.Close()
  8577. pastureinfo := new(udPastureInfo)
  8578. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8579. if err != nil {
  8580. logs.Error(err)
  8581. return
  8582. }
  8583. gm.UdBarSync(pastureid, pastureinfo.Werks)
  8584. // jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8585. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8586. }
  8587. func UdFeedSync(c *gin.Context) {
  8588. appG := app.Gin{C: c}
  8589. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8590. fsions := gofasion.NewFasion(string(dataByte))
  8591. pastureid := fsions.Get("pastureId").ValueStr()
  8592. tx := restful.Engine.NewSession()
  8593. defer tx.Close()
  8594. pastureinfo := new(udPastureInfo)
  8595. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8596. if err != nil {
  8597. logs.Error(err)
  8598. return
  8599. }
  8600. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8601. // jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8602. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8603. }
  8604. func UdFeedtempletPush(c *gin.Context) {
  8605. appG := app.Gin{C: c}
  8606. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8607. fsions := gofasion.NewFasion(string(dataByte))
  8608. pastureid := fsions.Get("pastureId").ValueStr()
  8609. date := fsions.Get("date").ValueStr()
  8610. tx := restful.Engine.NewSession()
  8611. defer tx.Close()
  8612. pastureinfo := new(udPastureInfo)
  8613. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8614. if err != nil {
  8615. logs.Error(err)
  8616. return
  8617. }
  8618. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8619. // jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8620. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8621. }
  8622. func UdUtirPush(c *gin.Context) {
  8623. appG := app.Gin{C: c}
  8624. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8625. fsions := gofasion.NewFasion(string(dataByte))
  8626. pastureid := fsions.Get("pastureId").ValueStr()
  8627. date := fsions.Get("date").ValueStr()
  8628. tx := restful.Engine.NewSession()
  8629. defer tx.Close()
  8630. pastureinfo := new(udPastureInfo)
  8631. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8632. if err != nil {
  8633. logs.Error(err)
  8634. return
  8635. }
  8636. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8637. // jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8638. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8639. }
  8640. func UdBarFeedRemainPush(c *gin.Context) {
  8641. appG := app.Gin{C: c}
  8642. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8643. fsions := gofasion.NewFasion(string(dataByte))
  8644. pastureid := fsions.Get("pastureId").ValueStr()
  8645. date := fsions.Get("date").ValueStr()
  8646. tx := restful.Engine.NewSession()
  8647. defer tx.Close()
  8648. pastureinfo := new(udPastureInfo)
  8649. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8650. if err != nil {
  8651. logs.Error(err)
  8652. return
  8653. }
  8654. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8655. // jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8656. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8657. }
  8658. func UdMaterialIssuePush(c *gin.Context) {
  8659. appG := app.Gin{C: c}
  8660. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8661. fsions := gofasion.NewFasion(string(dataByte))
  8662. pastureid := fsions.Get("pastureId").ValueStr()
  8663. date := fsions.Get("date").ValueStr()
  8664. tx := restful.Engine.NewSession()
  8665. defer tx.Close()
  8666. pastureinfo := new(udPastureInfo)
  8667. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8668. if err != nil {
  8669. logs.Error(err)
  8670. return
  8671. }
  8672. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8673. // jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8674. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8675. }
  8676. //搅拌
  8677. func YmyUtirPush(c *gin.Context) {
  8678. appG := app.Gin{C: c}
  8679. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8680. fsions := gofasion.NewFasion(string(dataByte))
  8681. pastureid := fsions.Get("pastureId").ValueStr()
  8682. date := fsions.Get("date").ValueStr()
  8683. tx := restful.Engine.NewSession()
  8684. defer tx.Close()
  8685. pastureinfo := new(udPastureInfo)
  8686. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8687. if err != nil {
  8688. logs.Error(err)
  8689. return
  8690. }
  8691. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8692. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8693. }
  8694. //撒料
  8695. func YmyMaterialIssuePush(c *gin.Context) {
  8696. appG := app.Gin{C: c}
  8697. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8698. fsions := gofasion.NewFasion(string(dataByte))
  8699. pastureid := fsions.Get("pastureId").ValueStr()
  8700. date := fsions.Get("date").ValueStr()
  8701. tx := restful.Engine.NewSession()
  8702. defer tx.Close()
  8703. pastureinfo := new(udPastureInfo)
  8704. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8705. if err != nil {
  8706. logs.Error(err)
  8707. return
  8708. }
  8709. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8710. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8711. }
  8712. func YmyFeedtempletPush(c *gin.Context) {
  8713. appG := app.Gin{C: c}
  8714. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8715. fsions := gofasion.NewFasion(string(dataByte))
  8716. pastureid := fsions.Get("pastureId").ValueStr()
  8717. date := fsions.Get("date").ValueStr()
  8718. tx := restful.Engine.NewSession()
  8719. defer tx.Close()
  8720. pastureinfo := new(udPastureInfo)
  8721. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8722. if err != nil {
  8723. logs.Error(err)
  8724. return
  8725. }
  8726. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8727. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8728. }
  8729. //饲料
  8730. func YmySyncFeed(c *gin.Context) {
  8731. appG := app.Gin{C: c}
  8732. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8733. fsions := gofasion.NewFasion(string(dataByte))
  8734. pastureid := fsions.Get("pastureId").ValueStr()
  8735. // date := fsions.Get("date").ValueStr()
  8736. tx := restful.Engine.NewSession()
  8737. defer tx.Close()
  8738. ymy.YmySyncFeed(pastureid)
  8739. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8740. }
  8741. // 栏舍
  8742. func YmySyncBar(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. pastureinfo := new(udPastureInfo)
  8751. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8752. if err != nil {
  8753. logs.Error(err)
  8754. return
  8755. }
  8756. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8757. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8758. }
  8759. func DelFeedTemplet(c *gin.Context) {
  8760. appG := app.Gin{C: c}
  8761. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8762. fsions := gofasion.NewFasion(string(dataByte))
  8763. ftId := fsions.Get("ftId").ValueStr()
  8764. // userId := fsions.Get("userId").ValueStr()
  8765. tx := restful.Engine.NewSession()
  8766. defer tx.Close()
  8767. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8768. if err != nil {
  8769. logs.Error(err)
  8770. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8771. return
  8772. }
  8773. /*
  8774. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8775. if err != nil {
  8776. logs.Error(err)
  8777. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8778. return
  8779. }
  8780. */
  8781. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8782. if err != nil {
  8783. logs.Error(err)
  8784. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8785. return
  8786. }
  8787. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8788. if err != nil {
  8789. logs.Error(err)
  8790. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8791. return
  8792. }
  8793. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8794. if count > 0 {
  8795. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8796. if err != nil {
  8797. logs.Error(err)
  8798. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8799. return
  8800. }
  8801. }
  8802. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8803. if err != nil {
  8804. logs.Error(err)
  8805. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8806. return
  8807. }
  8808. // var barIdStr []string
  8809. // for _, bar := range barIdList {
  8810. // barIdStr = append(barIdStr, bar["barid"])
  8811. // }
  8812. // if len(barIdStr) > 0 {
  8813. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8814. // if err != nil {
  8815. // logs.Error(err)
  8816. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8817. // return
  8818. // }
  8819. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8820. // if err != nil {
  8821. // logs.Error(err)
  8822. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8823. // return
  8824. // }
  8825. // now := time.Now()
  8826. // for _, newFpd := range newFpdDataList {
  8827. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8828. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8829. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8830. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8831. // if err != nil {
  8832. // logs.Error(err)
  8833. // appG.Response(http.StatusOK, e.ERROR, false)
  8834. // return
  8835. // }
  8836. // }
  8837. // for _, newFeedp := range newFeedpList {
  8838. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8839. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8840. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8841. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8842. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8843. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8844. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8845. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8846. // if err != nil {
  8847. // logs.Error(err)
  8848. // appG.Response(http.StatusOK, e.ERROR, false)
  8849. // return
  8850. // }
  8851. // }
  8852. // }
  8853. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8854. }
  8855. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8856. data := fasion["parammaps"].(map[string]interface{})
  8857. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8858. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8859. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8860. //
  8861. lweight := 20.0
  8862. for _, downloadedplan := range downloadedplanList {
  8863. downloadplandtl1List :=make([]*models.DownloadPlanDtl1,0)
  8864. downloadplandtl1ExecList :=make([]*models.DownloadPlanDtl1Exec,0)
  8865. downloadplandtl2List :=make([]*models.DownloadPlanDtl2,0)
  8866. tx.Table("downloadplandtl1").Where(" pid = ? ",downloadedplan.ID).Find(&downloadplandtl1List)
  8867. tx.Table("downloadplandtl2").Where(" pid = ? ",downloadedplan.ID).Find(&downloadplandtl2List)
  8868. tx.Table("downloadplandtl1_exec").Where(" pid = ? ",downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8869. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8870. for i := 0; i <= int(lweightCount); i++ {
  8871. if i ==0 {
  8872. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8873. for _, downloadplandtl1 := range downloadplandtl1List{
  8874. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8875. }
  8876. for _, downloadplandtl2 := range downloadplandtl2List{
  8877. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl2.LWeight, downloadplandtl2.ID)
  8878. }
  8879. for _, downloadplandtl2 := range downloadplandtl1ExecList{
  8880. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl2.LWeight, downloadplandtl2.ID)
  8881. }
  8882. } else if i < int(lweightCount) {
  8883. parts := strings.Split(downloadedplan.ProjName, ".")
  8884. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8885. data :=&models.DownloadedPlan{
  8886. PastureID :downloadedplan.PastureID ,
  8887. MyDate :downloadedplan.MyDate ,
  8888. ProjName :strings.Join(parts, ".") ,
  8889. DataCaptureNo :downloadedplan.DataCaptureNo ,
  8890. TmrID :downloadedplan.TmrID ,
  8891. TmrtName :downloadedplan.TmrtName ,
  8892. HaveButton :downloadedplan.HaveButton ,
  8893. InButtonType :downloadedplan.InButtonType ,
  8894. PlanTime :downloadedplan.PlanTime ,
  8895. InTime :downloadedplan.InTime ,
  8896. CompletedTime :downloadedplan.CompletedTime ,
  8897. IsCompleted :downloadedplan.IsCompleted ,
  8898. LpPlanType :downloadedplan.LpPlanType ,
  8899. Times :downloadedplan.Times ,
  8900. Sort :downloadedplan.Sort ,
  8901. Remark :downloadedplan.Remark ,
  8902. ItemNum :downloadedplan.ItemNum ,
  8903. OutItems :downloadedplan.OutItems ,
  8904. FeedPName :downloadedplan.FeedPName ,
  8905. FeedPCount :downloadedplan.FeedPCount ,
  8906. Pid :downloadedplan.Pid ,
  8907. TempID :downloadedplan.TempID ,
  8908. TempletName :downloadedplan.TempletName ,
  8909. PtsTempID :downloadedplan.PtsTempID ,
  8910. PtsTempletName:downloadedplan.PtsTempletName,
  8911. ThoWeight :downloadedplan.ThoWeight ,
  8912. FpWeight :downloadedplan.FpWeight ,
  8913. LWeight :lweight ,
  8914. IWeight :downloadedplan.IWeight ,
  8915. OWeight :downloadedplan.OWeight ,
  8916. TVersion :downloadedplan.TVersion ,
  8917. PtVersion :downloadedplan.PtVersion ,
  8918. Enable :downloadedplan.Enable ,
  8919. IsUse :downloadedplan.IsUse ,
  8920. OldTmrID :downloadedplan.OldTmrID ,
  8921. DriverID :downloadedplan.DriverID ,
  8922. Artificial :downloadedplan.Artificial ,
  8923. }
  8924. _, err := tx.Insert(data)
  8925. fmt.Println(data,err)
  8926. for _, downloadplandtl1 := range downloadplandtl1List{
  8927. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8928. d1 :=&models.DownloadPlanDtl1{
  8929. PastureID :downloadplandtl1.PastureID ,
  8930. Pid :data.ID ,
  8931. Flpid :downloadplandtl1.Flpid ,
  8932. Fid :downloadplandtl1.Fid ,
  8933. LWeight :lweight/downloadedplan.LWeight * downloadplandtl1.LWeight ,
  8934. Sort :downloadplandtl1.Sort ,
  8935. ButtonType :downloadplandtl1.ButtonType ,
  8936. OptDevice :downloadplandtl1.OptDevice ,
  8937. FeedCode :downloadplandtl1.FeedCode ,
  8938. FName :downloadplandtl1.FName ,
  8939. FeedSort :downloadplandtl1.FeedSort ,
  8940. FeedAllowRatio :downloadplandtl1.FeedAllowRatio ,
  8941. StirDelay :downloadplandtl1.StirDelay ,
  8942. FWeight :downloadplandtl1.FWeight ,
  8943. TmrLoadName :downloadplandtl1.TmrLoadName ,
  8944. DryFeed :downloadplandtl1.DryFeed ,
  8945. PriceFeed :downloadplandtl1.PriceFeed ,
  8946. OutWeight :downloadplandtl1.OutWeight ,
  8947. ErrRatio :downloadplandtl1.ErrRatio ,
  8948. Date :downloadplandtl1.Date ,
  8949. ButtonSucc :downloadplandtl1.ButtonSucc ,
  8950. Type :downloadplandtl1.Type ,
  8951. Deviation :downloadplandtl1.Deviation ,
  8952. XxwFeedCode :downloadplandtl1.XxwFeedCode ,
  8953. }
  8954. tx.Insert(d1)
  8955. }
  8956. for _, downloadplandtl2 := range downloadplandtl2List{
  8957. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8958. d2 :=&models.DownloadPlanDtl2{
  8959. PastureID :downloadplandtl2.PastureID ,
  8960. Pid :data.ID ,
  8961. Flpid :downloadplandtl2.Flpid ,
  8962. Fbarid :downloadplandtl2.Fbarid ,
  8963. FName :downloadplandtl2.FName ,
  8964. LWeight :lweight/downloadedplan.LWeight * downloadplandtl2.LWeight ,
  8965. LWeightHis :lweight/downloadedplan.LWeight * downloadplandtl2.LWeight ,
  8966. RemainLeftW :downloadplandtl2.RemainLeftW ,
  8967. AllowRW :downloadplandtl2.AllowRW ,
  8968. Sort :downloadplandtl2.Sort ,
  8969. HaveButton :downloadplandtl2.HaveButton ,
  8970. BeginTag :downloadplandtl2.BeginTag ,
  8971. EndTag :downloadplandtl2.EndTag ,
  8972. ButtonType :downloadplandtl2.ButtonType ,
  8973. OptDevice :downloadplandtl2.OptDevice ,
  8974. CowCount :downloadplandtl2.CowCount ,
  8975. CowClassID :downloadplandtl2.CowClassID ,
  8976. CowClassName :downloadplandtl2.CowClassName ,
  8977. BigCowName :downloadplandtl2.BigCowName ,
  8978. PWeight :downloadplandtl2.PWeight ,
  8979. CCountRatio :downloadplandtl2.CCountRatio ,
  8980. SumRTime :downloadplandtl2.SumRTime ,
  8981. FeedTempletID :downloadplandtl2.FeedTempletID ,
  8982. FeedTempletName :downloadplandtl2.FeedTempletName,
  8983. DryWeight :downloadplandtl2.DryWeight ,
  8984. SumWeight :downloadplandtl2.SumWeight ,
  8985. PriceWeight :downloadplandtl2.PriceWeight ,
  8986. // ProcessTime :downloadplandtl2.ProcessTime ,
  8987. Fpid :downloadplandtl2.Fpid ,
  8988. UseInBarType :downloadplandtl2.UseInBarType ,
  8989. Date :downloadplandtl2.Date ,
  8990. AllowRatio :downloadplandtl2.AllowRatio ,
  8991. ErrRatio :downloadplandtl2.ErrRatio ,
  8992. ButtonSucc :downloadplandtl2.ButtonSucc ,
  8993. Type :downloadplandtl2.Type ,
  8994. XxwTempletCode :downloadplandtl2.XxwTempletCode ,
  8995. XxwBarCode :downloadplandtl2.XxwBarCode ,
  8996. }
  8997. _,err :=tx.Insert(d2)
  8998. fmt.Println(err )
  8999. }
  9000. for _, downloadplandtl2 := range downloadplandtl1ExecList{
  9001. d2 :=&models.DownloadPlanDtl1Exec{
  9002. PastureID:downloadplandtl2.PastureID,
  9003. Pid:data.ID,
  9004. Flpid:downloadplandtl2.Flpid,
  9005. LWeight:lweight/downloadedplan.LWeight * downloadplandtl2.LWeight ,
  9006. HaveButton:downloadplandtl2.HaveButton,
  9007. ButtonType:downloadplandtl2.ButtonType,
  9008. OptDevice:downloadplandtl2.OptDevice,
  9009. Sort:downloadplandtl2.Sort,
  9010. FName:downloadplandtl2.FName,
  9011. FCount:downloadplandtl2.FCount ,
  9012. TmrLoadName:downloadplandtl2.TmrLoadName ,
  9013. FeedAllowRatio:downloadplandtl2.FeedAllowRatio ,
  9014. StirDelay:downloadplandtl2.StirDelay ,
  9015. ButtonSucc:downloadplandtl2.ButtonSucc ,
  9016. ErrRatio:downloadplandtl2.ErrRatio ,
  9017. Date:downloadplandtl2.Date ,
  9018. Type:downloadplandtl2.Type ,
  9019. Deviation:downloadplandtl2.Deviation ,
  9020. XxwFeedCode:downloadplandtl2.XxwFeedCode ,
  9021. }
  9022. _,err :=tx.Insert(d2)
  9023. fmt.Println(err )
  9024. }
  9025. } else {
  9026. parts := strings.Split(downloadedplan.ProjName, ".")
  9027. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9028. data := &models.DownloadedPlan{
  9029. PastureID :downloadedplan.PastureID ,
  9030. MyDate :downloadedplan.MyDate ,
  9031. ProjName :strings.Join(parts, ".") ,
  9032. DataCaptureNo :downloadedplan.DataCaptureNo ,
  9033. TmrID :downloadedplan.TmrID ,
  9034. TmrtName :downloadedplan.TmrtName ,
  9035. HaveButton :downloadedplan.HaveButton ,
  9036. InButtonType :downloadedplan.InButtonType ,
  9037. PlanTime :downloadedplan.PlanTime ,
  9038. InTime :downloadedplan.InTime ,
  9039. CompletedTime :downloadedplan.CompletedTime ,
  9040. IsCompleted :downloadedplan.IsCompleted ,
  9041. LpPlanType :downloadedplan.LpPlanType ,
  9042. Times :downloadedplan.Times ,
  9043. Sort :downloadedplan.Sort ,
  9044. Remark :downloadedplan.Remark ,
  9045. ItemNum :downloadedplan.ItemNum ,
  9046. OutItems :downloadedplan.OutItems ,
  9047. FeedPName :downloadedplan.FeedPName ,
  9048. FeedPCount :downloadedplan.FeedPCount ,
  9049. Pid :downloadedplan.Pid ,
  9050. TempID :downloadedplan.TempID ,
  9051. TempletName :downloadedplan.TempletName ,
  9052. PtsTempID :downloadedplan.PtsTempID ,
  9053. PtsTempletName:downloadedplan.PtsTempletName,
  9054. ThoWeight :downloadedplan.ThoWeight ,
  9055. FpWeight :downloadedplan.FpWeight ,
  9056. LWeight :downloadedplan.LWeight-float64(i)*lweight,
  9057. IWeight :downloadedplan.IWeight ,
  9058. OWeight :downloadedplan.OWeight ,
  9059. TVersion :downloadedplan.TVersion ,
  9060. PtVersion :downloadedplan.PtVersion ,
  9061. Enable :downloadedplan.Enable ,
  9062. IsUse :downloadedplan.IsUse ,
  9063. OldTmrID :downloadedplan.OldTmrID ,
  9064. DriverID :downloadedplan.DriverID ,
  9065. Artificial :downloadedplan.Artificial ,
  9066. }
  9067. _, err := tx.Insert(data)
  9068. fmt.Println(data,err)
  9069. for _, downloadplandtl1 := range downloadplandtl1List{
  9070. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9071. d1 :=&models.DownloadPlanDtl1{
  9072. PastureID :downloadplandtl1.PastureID ,
  9073. Pid :data.ID ,
  9074. Flpid :downloadplandtl1.Flpid ,
  9075. Fid :downloadplandtl1.Fid ,
  9076. LWeight :(downloadedplan.LWeight-float64(i)*lweight )/downloadedplan.LWeight * downloadplandtl1.LWeight ,
  9077. Sort :downloadplandtl1.Sort ,
  9078. ButtonType :downloadplandtl1.ButtonType ,
  9079. OptDevice :downloadplandtl1.OptDevice ,
  9080. FeedCode :downloadplandtl1.FeedCode ,
  9081. FName :downloadplandtl1.FName ,
  9082. FeedSort :downloadplandtl1.FeedSort ,
  9083. FeedAllowRatio :downloadplandtl1.FeedAllowRatio ,
  9084. StirDelay :downloadplandtl1.StirDelay ,
  9085. FWeight :downloadplandtl1.FWeight ,
  9086. TmrLoadName :downloadplandtl1.TmrLoadName ,
  9087. DryFeed :downloadplandtl1.DryFeed ,
  9088. PriceFeed :downloadplandtl1.PriceFeed ,
  9089. OutWeight :downloadplandtl1.OutWeight ,
  9090. ErrRatio :downloadplandtl1.ErrRatio ,
  9091. Date :downloadplandtl1.Date ,
  9092. ButtonSucc :downloadplandtl1.ButtonSucc ,
  9093. Type :downloadplandtl1.Type ,
  9094. Deviation :downloadplandtl1.Deviation ,
  9095. XxwFeedCode :downloadplandtl1.XxwFeedCode ,
  9096. }
  9097. tx.Insert(d1)
  9098. }
  9099. for _, downloadplandtl2 := range downloadplandtl2List{
  9100. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9101. d2 :=&models.DownloadPlanDtl2{
  9102. PastureID :downloadplandtl2.PastureID ,
  9103. Pid :data.ID ,
  9104. Flpid :downloadplandtl2.Flpid ,
  9105. Fbarid :downloadplandtl2.Fbarid ,
  9106. FName :downloadplandtl2.FName ,
  9107. LWeight :(downloadedplan.LWeight-float64(i)*lweight )/downloadedplan.LWeight * downloadplandtl2.LWeight ,
  9108. LWeightHis :(downloadedplan.LWeight-float64(i)*lweight )/downloadedplan.LWeight * downloadplandtl2.LWeight ,
  9109. RemainLeftW :downloadplandtl2.RemainLeftW ,
  9110. AllowRW :downloadplandtl2.AllowRW ,
  9111. Sort :downloadplandtl2.Sort ,
  9112. HaveButton :downloadplandtl2.HaveButton ,
  9113. BeginTag :downloadplandtl2.BeginTag ,
  9114. EndTag :downloadplandtl2.EndTag ,
  9115. ButtonType :downloadplandtl2.ButtonType ,
  9116. OptDevice :downloadplandtl2.OptDevice ,
  9117. CowCount :downloadplandtl2.CowCount ,
  9118. CowClassID :downloadplandtl2.CowClassID ,
  9119. CowClassName :downloadplandtl2.CowClassName ,
  9120. BigCowName :downloadplandtl2.BigCowName ,
  9121. PWeight :downloadplandtl2.PWeight ,
  9122. CCountRatio :downloadplandtl2.CCountRatio ,
  9123. SumRTime :downloadplandtl2.SumRTime ,
  9124. FeedTempletID :downloadplandtl2.FeedTempletID ,
  9125. FeedTempletName :downloadplandtl2.FeedTempletName,
  9126. DryWeight :downloadplandtl2.DryWeight ,
  9127. SumWeight :downloadplandtl2.SumWeight ,
  9128. PriceWeight :downloadplandtl2.PriceWeight ,
  9129. // ProcessTime :downloadplandtl2.ProcessTime ,
  9130. Fpid :downloadplandtl2.Fpid ,
  9131. UseInBarType :downloadplandtl2.UseInBarType ,
  9132. Date :downloadplandtl2.Date ,
  9133. AllowRatio :downloadplandtl2.AllowRatio ,
  9134. ErrRatio :downloadplandtl2.ErrRatio ,
  9135. ButtonSucc :downloadplandtl2.ButtonSucc ,
  9136. Type :downloadplandtl2.Type ,
  9137. XxwTempletCode :downloadplandtl2.XxwTempletCode ,
  9138. XxwBarCode :downloadplandtl2.XxwBarCode ,
  9139. }
  9140. _,err :=tx.Insert(d2)
  9141. fmt.Println(err )
  9142. }
  9143. for _, downloadplandtl2 := range downloadplandtl1ExecList{
  9144. d2 :=&models.DownloadPlanDtl1Exec{
  9145. PastureID:downloadplandtl2.PastureID,
  9146. Pid:data.ID,
  9147. Flpid:downloadplandtl2.Flpid,
  9148. LWeight:(downloadedplan.LWeight-float64(i)*lweight )/downloadedplan.LWeight * downloadplandtl2.LWeight ,
  9149. HaveButton:downloadplandtl2.HaveButton,
  9150. ButtonType:downloadplandtl2.ButtonType,
  9151. OptDevice:downloadplandtl2.OptDevice,
  9152. Sort:downloadplandtl2.Sort,
  9153. FName:downloadplandtl2.FName,
  9154. FCount:downloadplandtl2.FCount ,
  9155. TmrLoadName:downloadplandtl2.TmrLoadName ,
  9156. FeedAllowRatio:downloadplandtl2.FeedAllowRatio ,
  9157. StirDelay:downloadplandtl2.StirDelay ,
  9158. ButtonSucc:downloadplandtl2.ButtonSucc ,
  9159. ErrRatio:downloadplandtl2.ErrRatio ,
  9160. Date:downloadplandtl2.Date ,
  9161. Type:downloadplandtl2.Type ,
  9162. Deviation:downloadplandtl2.Deviation ,
  9163. XxwFeedCode:downloadplandtl2.XxwFeedCode ,
  9164. }
  9165. fmt.Println(d2)
  9166. _,err :=tx.Insert(d2)
  9167. fmt.Println(err )
  9168. }
  9169. }
  9170. }
  9171. }
  9172. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9173. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`,data["startTime"] ).Find(&downloadedplanSortList)
  9174. for i,d :=range downloadedplanSortList{
  9175. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9176. }
  9177. }
  9178. func EditPlanSort(c *gin.Context) {
  9179. appG := app.Gin{C: c}
  9180. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9181. fsions := gofasion.NewFasion(string(dataByte))
  9182. planIdStr := fsions.Get("planId").ValueStr()
  9183. mydate := fsions.Get("mydate").ValueStr()
  9184. sort := fsions.Get("sort").ValueStr()
  9185. tx := restful.Engine.NewSession()
  9186. defer tx.Close()
  9187. tx.Begin()
  9188. type downloadedplan struct {
  9189. Id int64 `xorm:"id"`
  9190. Sort int `xorm:"sort"`
  9191. Pid int64 `xorm:"pid"`
  9192. }
  9193. planInfo := new(downloadedplan)
  9194. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9195. if err != nil {
  9196. logs.Error(err)
  9197. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9198. tx.Rollback()
  9199. return
  9200. }
  9201. sort1, _ := strconv.Atoi(sort)
  9202. if sort1 == planInfo.Sort {
  9203. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9204. tx.Rollback()
  9205. return
  9206. }
  9207. 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()
  9208. if err != nil {
  9209. logs.Error(err)
  9210. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9211. tx.Rollback()
  9212. return
  9213. }
  9214. if count1 == 0 {
  9215. tx.Rollback()
  9216. logs.Error(err)
  9217. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9218. return
  9219. }
  9220. 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()
  9221. if err != nil {
  9222. logs.Error(err)
  9223. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9224. tx.Rollback()
  9225. return
  9226. }
  9227. if count > 0 {
  9228. tx.Rollback()
  9229. logs.Error(err)
  9230. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9231. return
  9232. }
  9233. if planInfo.Sort > sort1 {
  9234. 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()
  9235. if err != nil {
  9236. logs.Error(err)
  9237. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9238. tx.Rollback()
  9239. return
  9240. }
  9241. var minSort, pidCount int
  9242. for _, sort := range minSortList {
  9243. minSort, _ = strconv.Atoi(sort["sort"])
  9244. }
  9245. planList := make([]*downloadedplan, 0)
  9246. 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)
  9247. if err != nil {
  9248. logs.Error(err)
  9249. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9250. tx.Rollback()
  9251. return
  9252. }
  9253. planPid := planInfo.Pid
  9254. planList1 := make([]*downloadedplan, 0)
  9255. planList2 := make([]*downloadedplan, 0)
  9256. for _, plan := range planList {
  9257. if plan.Pid == planPid {
  9258. pidCount++
  9259. planList1 = append(planList1, plan)
  9260. } else {
  9261. planList2 = append(planList2, plan)
  9262. }
  9263. }
  9264. planList1 = append(planList1, planList2...)
  9265. for i, plan := range planList1 {
  9266. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9267. if err != nil {
  9268. logs.Error(err)
  9269. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9270. tx.Rollback()
  9271. return
  9272. }
  9273. }
  9274. } else {
  9275. 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()
  9276. if err != nil {
  9277. logs.Error(err)
  9278. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9279. tx.Rollback()
  9280. return
  9281. }
  9282. var maxSort int
  9283. for _, sort := range maxSortList {
  9284. maxSort, _ = strconv.Atoi(sort["sort"])
  9285. }
  9286. planList := make([]*downloadedplan, 0)
  9287. 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)
  9288. if err != nil {
  9289. logs.Error(err)
  9290. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9291. tx.Rollback()
  9292. return
  9293. }
  9294. planPid := planInfo.Pid
  9295. planList1 := make([]*downloadedplan, 0)
  9296. planList2 := make([]*downloadedplan, 0)
  9297. for _, plan := range planList {
  9298. if plan.Pid == planPid {
  9299. // pidCount++
  9300. planList1 = append(planList1, plan)
  9301. } else {
  9302. planList2 = append(planList2, plan)
  9303. }
  9304. }
  9305. planList2 = append(planList2, planList1...)
  9306. for i, plan := range planList2 {
  9307. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9308. if err != nil {
  9309. logs.Error(err)
  9310. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9311. tx.Rollback()
  9312. return
  9313. }
  9314. }
  9315. }
  9316. err = tx.Commit()
  9317. if err != nil {
  9318. logs.Error(err)
  9319. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9320. tx.Rollback()
  9321. return
  9322. }
  9323. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9324. }
  9325. func EditDownloadedplanArtificial(c *gin.Context) {
  9326. appG := app.Gin{C: c}
  9327. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9328. fsions := gofasion.NewFasion(string(dataByte))
  9329. planIdStr := fsions.Get("planId").ValueStr()
  9330. tx := restful.Engine.NewSession()
  9331. defer tx.Close()
  9332. tx.Begin()
  9333. planIdList := strings.Split(planIdStr, ",")
  9334. for _, planId := range planIdList {
  9335. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9336. if err != nil {
  9337. logs.Error(err)
  9338. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9339. tx.Rollback()
  9340. return
  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. type PlanRFID struct {
  9353. RFID string `json:"RFID"`
  9354. Lweight string `json:"lweight"`
  9355. Gear string `json:"gear"`
  9356. Speed string `json:"speed"`
  9357. }
  9358. func GetPlanRFID(c *gin.Context) {
  9359. appG := app.Gin{C: c}
  9360. RFIDStr := c.Query("RFID")
  9361. planRFIDList := make([]*PlanRFID, 0)
  9362. planRFIDList = append(planRFIDList, &PlanRFID{
  9363. RFID: RFIDStr,
  9364. Lweight: "1411.1",
  9365. Gear: "1",
  9366. Speed: "10",
  9367. })
  9368. planRFIDList = append(planRFIDList, &PlanRFID{
  9369. RFID: RFIDStr,
  9370. Lweight: "1322.1",
  9371. Gear: "1",
  9372. Speed: "10",
  9373. })
  9374. planRFIDList = append(planRFIDList, &PlanRFID{
  9375. RFID: RFIDStr,
  9376. Lweight: "1904.1",
  9377. Gear: "1",
  9378. Speed: "10",
  9379. })
  9380. planRFIDList = append(planRFIDList, &PlanRFID{
  9381. RFID: RFIDStr,
  9382. Lweight: "1870.1",
  9383. Gear: "1",
  9384. Speed: "10",
  9385. })
  9386. planRFIDList = append(planRFIDList, &PlanRFID{
  9387. RFID: RFIDStr,
  9388. Lweight: "2041.1",
  9389. Gear: "1",
  9390. Speed: "10",
  9391. })
  9392. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9393. }
  9394. type tmrEquipmentMuster struct {
  9395. A string
  9396. N string
  9397. }
  9398. func GetTmrEquipmentMuster(c *gin.Context) {
  9399. appG := app.Gin{C: c}
  9400. id := c.Query("id")
  9401. tx := restful.Engine.NewSession()
  9402. defer tx.Close()
  9403. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9404. if err != nil {
  9405. logs.Error(err)
  9406. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9407. return
  9408. }
  9409. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9410. for _, data := range dataList {
  9411. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9412. for _, g := range tmrEquipmentMusterList {
  9413. a, _ := strconv.ParseFloat(g.A, 64)
  9414. n, _ := strconv.ParseFloat(g.N, 64)
  9415. a1, n1 := ddmmtoddd(a, n)
  9416. g.A = fmt.Sprintf("%f", n1)
  9417. g.N = fmt.Sprintf("%f", a1)
  9418. }
  9419. }
  9420. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9421. }
  9422. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9423. lngDegree := fmt.Sprintf("%f", lng/100)
  9424. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9425. lngDegreeInt := int(lngDegreefloat * 1000000)
  9426. dd := lngDegreeInt / 100 * 100 / 60
  9427. fmt.Println(dd)
  9428. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9429. latDegree := fmt.Sprintf("%f", lat/100)
  9430. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9431. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9432. latDegreeInt := int(latDegreefloat * 1000000)
  9433. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9434. a, _ := strconv.ParseFloat(lngStr, 64)
  9435. b, _ := strconv.ParseFloat(latStr, 64)
  9436. return coordtransform.WGS84toGCJ02(b, a)
  9437. }
  9438. func EditDownloadedplanExecWeight(c *gin.Context) {
  9439. appG := app.Gin{C: c}
  9440. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9441. fsions := gofasion.NewFasion(string(dataByte))
  9442. pid := fsions.Get("pid").ValueStr()
  9443. sort := fsions.Get("sort").ValueStr()
  9444. weight := fsions.Get("weight").ValueStr()
  9445. userId := fsions.Get("userId").ValueStr()
  9446. tx := restful.Engine.NewSession()
  9447. defer tx.Close()
  9448. tx.Begin()
  9449. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9450. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9451. pid, sort, pid, sort, weight, userId)
  9452. if err != nil {
  9453. logs.Error(err)
  9454. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9455. tx.Rollback()
  9456. return
  9457. }
  9458. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9459. if err != nil {
  9460. logs.Error(err)
  9461. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9462. tx.Rollback()
  9463. return
  9464. }
  9465. _, 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)
  9466. if err != nil {
  9467. logs.Error(err)
  9468. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9469. tx.Rollback()
  9470. return
  9471. }
  9472. err = tx.Commit()
  9473. if err != nil {
  9474. logs.Error(err)
  9475. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9476. tx.Rollback()
  9477. return
  9478. }
  9479. appG.Response(http.StatusOK, e.SUCCESS, true)
  9480. }
  9481. func EditDownloadplandtl2Weight(c *gin.Context) {
  9482. appG := app.Gin{C: c}
  9483. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9484. fsions := gofasion.NewFasion(string(dataByte))
  9485. pid := fsions.Get("pid").ValueStr()
  9486. sort := fsions.Get("sort").ValueStr()
  9487. weight := fsions.Get("weight").ValueStr()
  9488. userId := fsions.Get("userId").ValueStr()
  9489. tx := restful.Engine.NewSession()
  9490. defer tx.Close()
  9491. tx.Begin()
  9492. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9493. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9494. pid, sort, pid, sort, weight, userId)
  9495. if err != nil {
  9496. logs.Error(err)
  9497. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9498. tx.Rollback()
  9499. return
  9500. }
  9501. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9502. if err != nil {
  9503. logs.Error(err)
  9504. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9505. tx.Rollback()
  9506. return
  9507. }
  9508. err = tx.Commit()
  9509. if err != nil {
  9510. logs.Error(err)
  9511. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9512. tx.Rollback()
  9513. return
  9514. }
  9515. appG.Response(http.StatusOK, e.SUCCESS, true)
  9516. }
  9517. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9518. params := fasion.Get("parammaps")
  9519. surplus := params.Get("surplus").ValueStr()
  9520. surplusId := params.Get("surplusId").ValueStr()
  9521. tx := restful.Engine.NewSession()
  9522. defer tx.Close()
  9523. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9524. if surplusId != "0" {
  9525. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9526. if err != nil {
  9527. log.Println("PostDataByName-error-1: ", err)
  9528. return errors.New("配方修改失败!")
  9529. }
  9530. type ftdetail struct {
  9531. Id string
  9532. Fname string
  9533. Sort int64
  9534. }
  9535. ftList := make([]*ftdetail, 0)
  9536. for _, data := range dataList {
  9537. ft := new(ftdetail)
  9538. ft.Fname = data["fname"]
  9539. ft.Id = data["id"]
  9540. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9541. if err != nil {
  9542. log.Println("PostDataByName-error-2: ", err)
  9543. return err
  9544. }
  9545. ft.Sort = sort
  9546. ftList = append(ftList, ft)
  9547. }
  9548. if surplus == "日粮" {
  9549. for _, ft := range ftList {
  9550. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9551. }
  9552. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9553. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9554. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9555. fmt.Println(err)
  9556. } else {
  9557. var sort int64
  9558. for _, ft := range ftList {
  9559. if ft.Fname == surplus {
  9560. sort = ft.Sort
  9561. break
  9562. }
  9563. }
  9564. if sort == 0 {
  9565. for _, ft := range ftList {
  9566. ft.Sort = ft.Sort + 1
  9567. }
  9568. } else {
  9569. for _, ft := range ftList {
  9570. if ft.Sort >= sort {
  9571. ft.Sort = ft.Sort + 1
  9572. }
  9573. }
  9574. }
  9575. for _, ft := range ftList {
  9576. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9577. }
  9578. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9579. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9580. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9581. if err != nil {
  9582. log.Println("PostDataByName-error-1: ", err)
  9583. fmt.Println(err)
  9584. return errors.New("配方修改失败!")
  9585. }
  9586. }
  9587. }
  9588. return nil
  9589. }
  9590. func FeedSurplus(fasion *gofasion.Fasion) {
  9591. tx := restful.Engine.NewSession()
  9592. defer tx.Close()
  9593. params := fasion.Get("parammaps")
  9594. feedId := params.Get("id").ValueStr()
  9595. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9596. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9597. }
  9598. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9599. // params := fasion.Get("parammaps")
  9600. // surplus := params.Get("surplus").ValueStr()
  9601. // surplusId := params.Get("surplusId").ValueStr()
  9602. tx := restful.Engine.NewSession()
  9603. defer tx.Close()
  9604. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9605. if surplusId != "0" {
  9606. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9607. if err != nil {
  9608. log.Println("PostDataByName-error-1: ", err)
  9609. return errors.New("配方修改失败!")
  9610. }
  9611. type ftdetail struct {
  9612. Id string
  9613. Fname string
  9614. Sort int64
  9615. }
  9616. ftList := make([]*ftdetail, 0)
  9617. for _, data := range dataList {
  9618. ft := new(ftdetail)
  9619. ft.Fname = data["fname"]
  9620. ft.Id = data["id"]
  9621. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9622. if err != nil {
  9623. log.Println("PostDataByName-error-2: ", err)
  9624. return err
  9625. }
  9626. ft.Sort = sort
  9627. ftList = append(ftList, ft)
  9628. }
  9629. if surplus == "日粮" {
  9630. for _, ft := range ftList {
  9631. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9632. }
  9633. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9634. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9635. pastureId, id, surplusId, surplusId, surplusId)
  9636. fmt.Println(err)
  9637. } else {
  9638. var sort int64
  9639. for _, ft := range ftList {
  9640. if ft.Fname == surplus {
  9641. sort = ft.Sort
  9642. break
  9643. }
  9644. }
  9645. if sort == 0 {
  9646. for _, ft := range ftList {
  9647. ft.Sort = ft.Sort + 1
  9648. }
  9649. } else {
  9650. for _, ft := range ftList {
  9651. if ft.Sort >= sort {
  9652. ft.Sort = ft.Sort + 1
  9653. }
  9654. }
  9655. }
  9656. for _, ft := range ftList {
  9657. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9658. }
  9659. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9660. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9661. id, surplusId, surplusId, sort, surplusId, pastureId)
  9662. if err != nil {
  9663. log.Println("PostDataByName-error-1: ", err)
  9664. fmt.Println(err)
  9665. return errors.New("配方修改失败!")
  9666. }
  9667. }
  9668. }
  9669. return nil
  9670. }
  9671. func GetLanguageStatus() string {
  9672. tx := restful.Engine.NewSession()
  9673. defer tx.Close()
  9674. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9675. if err != nil {
  9676. log.Println(err)
  9677. return "0"
  9678. }
  9679. return dataList[0]["inforvalue"]
  9680. }
  9681. func EditLanguage(c *gin.Context) {
  9682. appG := app.Gin{C: c}
  9683. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9684. fsions := gofasion.NewFasion(string(dataByte))
  9685. language := fsions.Get("language").ValueStr()
  9686. tx := restful.Engine.NewSession()
  9687. defer tx.Close()
  9688. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9689. if err != nil {
  9690. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9691. return
  9692. }
  9693. if language == "0" {
  9694. _, err := tx.Exec(`delete from dictlist `)
  9695. if err != nil {
  9696. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9697. return
  9698. }
  9699. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9700. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9701. if err != nil {
  9702. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9703. return
  9704. }
  9705. } else {
  9706. _, err := tx.Exec(`delete from dictlist `)
  9707. if err != nil {
  9708. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9709. return
  9710. }
  9711. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9712. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9713. if err != nil {
  9714. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9715. return
  9716. }
  9717. }
  9718. appG.Response(http.StatusOK, e.SUCCESS, true)
  9719. }
  9720. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9721. tx := restful.Engine.NewSession()
  9722. defer tx.Close()
  9723. 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
  9724. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9725. if err != nil {
  9726. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9727. return
  9728. }
  9729. for _, dataexcel := range barList {
  9730. // dataexcel := make(map[string]interface{}, 0)
  9731. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9732. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9733. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9734. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9735. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9736. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9737. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9738. // if err != nil {
  9739. // logs.Error(err)
  9740. // return
  9741. // }
  9742. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9743. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9744. // if err != nil {
  9745. // logs.Error(err)
  9746. // return
  9747. // }
  9748. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9749. continue
  9750. }
  9751. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9752. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9753. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9754. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9755. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9756. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9757. // /*
  9758. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9759. if err != nil {
  9760. logs.Error(err)
  9761. return
  9762. }
  9763. if !ftexist {
  9764. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9765. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9766. if err != nil {
  9767. logs.Error(err)
  9768. return
  9769. }
  9770. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9771. if err != nil {
  9772. logs.Error(err)
  9773. return
  9774. }
  9775. }
  9776. // */
  9777. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9778. if err != nil {
  9779. logs.Error(err)
  9780. return
  9781. }
  9782. if !exist {
  9783. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9784. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9785. if err != nil {
  9786. logs.Error(err)
  9787. return
  9788. }
  9789. }
  9790. var feedpargs []interface{}
  9791. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9792. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9793. if _, ok := dataexcel["ftname"]; ok {
  9794. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9795. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9796. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9797. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9798. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9799. } else {
  9800. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9801. }
  9802. if _, ok := dataexcel["ptsfname"]; ok {
  9803. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9804. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9805. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9806. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9807. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9808. } else {
  9809. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9810. }
  9811. upFeedpSql += " where barname = ? and pastureid = ? "
  9812. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9813. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9814. if err != nil {
  9815. logs.Error(err)
  9816. return
  9817. }
  9818. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9819. if err != nil {
  9820. logs.Error(err)
  9821. return
  9822. }
  9823. if !exist1 {
  9824. _, 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) `,
  9825. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9826. if err != nil {
  9827. logs.Error(err)
  9828. return
  9829. }
  9830. }
  9831. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9832. if err != nil {
  9833. logs.Error(err)
  9834. return
  9835. }
  9836. if !exist2 {
  9837. _, 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) `,
  9838. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9839. if err != nil {
  9840. logs.Error(err)
  9841. return
  9842. }
  9843. }
  9844. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9845. if err != nil {
  9846. logs.Error(err)
  9847. return
  9848. }
  9849. if !exist3 {
  9850. _, 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) `,
  9851. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9852. if err != nil {
  9853. logs.Error(err)
  9854. return
  9855. }
  9856. }
  9857. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9858. if err != nil {
  9859. logs.Error(err)
  9860. return
  9861. }
  9862. if !exist4 {
  9863. _, 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) `,
  9864. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9865. if err != nil {
  9866. logs.Error(err)
  9867. return
  9868. }
  9869. }
  9870. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9871. if err != nil {
  9872. logs.Error(err)
  9873. return
  9874. }
  9875. if !exist5 {
  9876. _, 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) `,
  9877. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9878. if err != nil {
  9879. logs.Error(err)
  9880. return
  9881. }
  9882. }
  9883. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9884. if err != nil {
  9885. logs.Error(err)
  9886. return
  9887. }
  9888. if !exist6 {
  9889. _, 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) `,
  9890. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9891. if err != nil {
  9892. logs.Error(err)
  9893. return
  9894. }
  9895. }
  9896. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9897. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9898. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9899. and pastureid = ? and times = ?`
  9900. var fpdargs1 []interface{}
  9901. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9902. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9903. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9904. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9905. if err != nil {
  9906. fmt.Println(err)
  9907. return
  9908. }
  9909. var fpdargs2 []interface{}
  9910. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9911. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9912. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9913. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9914. if err != nil {
  9915. fmt.Println(err)
  9916. return
  9917. }
  9918. var fpdargs3 []interface{}
  9919. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9920. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9921. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9922. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9923. if err != nil {
  9924. fmt.Println(err)
  9925. return
  9926. }
  9927. var fpdargs4 []interface{}
  9928. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9929. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9930. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9931. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9932. if err != nil {
  9933. fmt.Println(err)
  9934. return
  9935. }
  9936. var fpdargs5 []interface{}
  9937. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9938. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9939. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9940. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9941. if err != nil {
  9942. fmt.Println(err)
  9943. return
  9944. }
  9945. var fpdargs6 []interface{}
  9946. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9947. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9948. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9949. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9950. if err != nil {
  9951. fmt.Println(err)
  9952. return
  9953. }
  9954. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9955. 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()
  9956. if err != nil {
  9957. return
  9958. }
  9959. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9960. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9961. upFpdetailList := make([]*upFpdetail, 0)
  9962. for _, newfpd := range newList {
  9963. for _, oldfpd := range oldFpdList {
  9964. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9965. var oldweight, newweight float64
  9966. if oldfpd["weight"] != nil {
  9967. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9968. }
  9969. if newfpd["weight"] != nil {
  9970. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9971. }
  9972. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9973. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9974. Old: oldweight,
  9975. New: newweight,
  9976. Times: newfpd["times"].(int64),
  9977. Ptid: newfpd["ptid"].(int64),
  9978. Fweight: fweight,
  9979. Id: oldfpd["id"].(int64),
  9980. })
  9981. break
  9982. }
  9983. }
  9984. }
  9985. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9986. }
  9987. }
  9988. func AddXxwFtdetail(c *gin.Context) {
  9989. appG := app.Gin{C: c}
  9990. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  9991. c.Bind(&xxwFtdetailList)
  9992. tx := restful.Engine.NewSession()
  9993. defer tx.Close()
  9994. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  9995. if err != nil {
  9996. logs.Error(err)
  9997. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9998. }
  9999. _, err = tx.Insert(xxwFtdetailList)
  10000. if err != nil {
  10001. logs.Error(err)
  10002. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10003. }
  10004. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10005. appG.Response(http.StatusOK, e.SUCCESS, true)
  10006. }
  10007. func AddXxwFeedtemplet(c *gin.Context) {
  10008. appG := app.Gin{C: c}
  10009. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10010. c.Bind(&xxwFeedtempletList)
  10011. tx := restful.Engine.NewSession()
  10012. defer tx.Close()
  10013. pastureinfo := new(udPastureInfo)
  10014. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10015. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10016. if err != nil {
  10017. logs.Error(err)
  10018. return
  10019. }
  10020. for _, ft := range xxwFeedtempletList {
  10021. ids, err := setting.SnowIds.NextId()
  10022. if err != nil {
  10023. ids = time.Now().UnixNano()
  10024. logging.Info("create SnowIds err", err)
  10025. }
  10026. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10027. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10028. ft.RecipeobjName, ft.RecipeobjName)
  10029. if err != nil {
  10030. logs.Error(err)
  10031. return
  10032. }
  10033. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10034. _, 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')),
  10035. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10036. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10037. if err != nil {
  10038. logs.Error(err)
  10039. return
  10040. }
  10041. }
  10042. appG.Response(http.StatusOK, e.SUCCESS, true)
  10043. }
  10044. func ProcessExcel(c *gin.Context) {
  10045. appG := app.Gin{C: c}
  10046. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10047. fasion := gofasion.NewFasion(string(dataByte))
  10048. params := fasion.Get("parammaps")
  10049. pastureid := params.Get("pastureid").ValueStr()
  10050. startTime := params.Get("startTime").ValueStr()
  10051. stopTime := params.Get("stopTime").ValueStr()
  10052. iscompleted := params.Get("iscompleted").ValueStr()
  10053. lpplantype := params.Get("lpplantype").ValueStr()
  10054. error := params.Get("error").ValueStr()
  10055. hlwc1 := params.Get("hlwc1").ValueStr()
  10056. hlwc2 := params.Get("hlwc2").ValueStr()
  10057. slwc1 := params.Get("slwc1").ValueStr()
  10058. slwc2 := params.Get("slwc2").ValueStr()
  10059. hlzq1 := params.Get("hlzq1").ValueStr()
  10060. hlzq2 := params.Get("hlzq2").ValueStr()
  10061. slzq1 := params.Get("slzq1").ValueStr()
  10062. slzq2 := params.Get("slzq2").ValueStr()
  10063. fclassid := params.Get("fclassid").ValueStr()
  10064. minproesstime := params.Get("minproesstime").ValueStr()
  10065. maxproesstime := params.Get("maxproesstime").ValueStr()
  10066. tx := restful.Engine.NewSession()
  10067. defer tx.Close()
  10068. planList, err := tx.SQL(`SELECT
  10069. 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
  10070. FROM downloadedplan d
  10071. join pasture p on p.pastureid = d.pastureid
  10072. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10073. AND mydate >= ? AND mydate <= ?
  10074. AND (iscompleted=? or ?='')
  10075. AND (lpplantype = ? or ? = '')
  10076. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10077. 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
  10078. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10079. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10080. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10081. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10082. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10083. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10084. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10085. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10086. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10087. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10088. 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,
  10089. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10090. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10091. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10092. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10093. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10094. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10095. or (?= '' and ? = '' ))
  10096. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10097. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10098. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10099. maxproesstime, minproesstime, maxproesstime).QueryString()
  10100. if err != nil {
  10101. logs.Error(err)
  10102. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10103. return
  10104. }
  10105. planExecList, err := tx.SQL(`SELECT
  10106. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10107. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10108. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10109. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10110. ) proesstime,
  10111. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10112. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10113. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10114. sumproesstime, d1.pid,
  10115. d1.sort,
  10116. d1.fname,
  10117. d1.lweight,
  10118. d1.actualweightminus,
  10119. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10120. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10121. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10122. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10123. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10124. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10125. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10126. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10127. d1.begintime stoptime,
  10128. d1.lastactualweight,
  10129. d1.actualweight,
  10130. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10131. case d1.buttontype
  10132. when 1 then '自动'
  10133. when 2 then '手动'
  10134. when 3 then '手动'
  10135. end,
  10136. case d1.buttontype
  10137. when 1 then 'Automatic'
  10138. when 2 then 'Manual'
  10139. when 3 then 'Manual'
  10140. end
  10141. ) buttontype
  10142. FROM
  10143. downloadplandtl1_exec d1
  10144. WHERE d1.date between ? and ?
  10145. ORDER BY sort
  10146. `, startTime, stopTime).QueryString()
  10147. if err != nil {
  10148. logs.Error(err)
  10149. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10150. return
  10151. }
  10152. planExec2, err := tx.SQL(`SELECT
  10153. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10154. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10155. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10156. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10157. ) proesstime,
  10158. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10159. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10160. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10161. d1.sort,
  10162. d1.fname,
  10163. d1.lweight,
  10164. d1.actualweightminus,
  10165. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10166. ABS(d1.lweight- d1.actualweightminus) diff,
  10167. 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,
  10168. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10169. d1.begintime stoptime,
  10170. d1.lastactualweight,
  10171. d1.actualweight,d1.pid
  10172. FROM
  10173. downloadplandtl2 d1
  10174. WHERE d1.date between ? and ?
  10175. ORDER BY sort`, startTime, stopTime).QueryString()
  10176. if err != nil {
  10177. logs.Error(err)
  10178. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10179. return
  10180. }
  10181. // 创建一个新的 Excel 文件
  10182. f := excelizexuri.NewFile()
  10183. // 创建工作表名称
  10184. sheetName := "Sheet1"
  10185. // border := []excelizexuri.Border{
  10186. // {Type: "left", Color: "000000", Style: 1},
  10187. // {Type: "right", Color: "000000", Style: 1},
  10188. // {Type: "top", Color: "000000", Style: 1},
  10189. // {Type: "bottom", Color: "000000", Style: 1},
  10190. // }
  10191. // 创建新的样式
  10192. style := &excelizexuri.Style{
  10193. // Border: border,
  10194. Alignment: &excelizexuri.Alignment{
  10195. Vertical: "center",
  10196. Horizontal: "center",
  10197. ShrinkToFit: true,
  10198. WrapText: true,
  10199. },
  10200. }
  10201. styleTitle := &excelizexuri.Style{
  10202. Fill: excelizexuri.Fill{
  10203. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10204. },
  10205. // Border: border,
  10206. Font: &excelizexuri.Font{
  10207. Bold: true, // 加粗
  10208. Size: 24, // 字体大小
  10209. // Name: "宋体", // 字体名称
  10210. // WrapText :true,
  10211. Color: "000000", // 字体颜色(黑色)
  10212. },
  10213. Alignment: &excelizexuri.Alignment{
  10214. Vertical: "center", // 垂直居中
  10215. Horizontal: "center", // 水平居中
  10216. ShrinkToFit: true,
  10217. WrapText: true,
  10218. },
  10219. }
  10220. // 创建样式 ID
  10221. styleTitleId, err := f.NewStyle(styleTitle)
  10222. if err != nil {
  10223. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10224. return
  10225. }
  10226. // 创建样式 ID
  10227. styleID, err := f.NewStyle(style)
  10228. if err != nil {
  10229. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10230. return
  10231. }
  10232. // 合并单元格并设置内容
  10233. f.MergeCell(sheetName, "A1", "K1")
  10234. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10235. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10236. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10237. planExecMap := make(map[string][]map[string]string, 0)
  10238. for _, planExec := range planExecList {
  10239. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10240. }
  10241. plan2Map := make(map[string][]map[string]string, 0)
  10242. for _, plan2 := range planExec2 {
  10243. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10244. }
  10245. num := 2
  10246. var notBorder []int
  10247. for _, plan := range planList {
  10248. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10249. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10250. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10251. for i, header := range headers {
  10252. // 从 A2 开始
  10253. if header == "开始日期" {
  10254. cell := "%" + fmt.Sprintf("c%d", num)
  10255. cell = fmt.Sprintf(cell, 'A'+i+1)
  10256. f.SetCellValue(sheetName, cell, header)
  10257. f.SetCellStyle(sheetName, cell, cell, styleID)
  10258. continue
  10259. }
  10260. cell := "%" + fmt.Sprintf("c%d", num)
  10261. cell = fmt.Sprintf(cell, 'A'+i)
  10262. f.SetCellValue(sheetName, cell, header)
  10263. f.SetCellStyle(sheetName, cell, cell, styleID)
  10264. }
  10265. num += 1
  10266. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10267. cell := "%" + fmt.Sprintf("c%d", num)
  10268. cell = fmt.Sprintf(cell, 'A'+0)
  10269. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10270. f.SetCellStyle(sheetName, cell, cell, styleID)
  10271. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10272. cell = "%" + fmt.Sprintf("c%d", num)
  10273. cell = fmt.Sprintf(cell, 'A'+1)
  10274. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10275. f.SetCellStyle(sheetName, cell, cell, styleID)
  10276. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10277. cell = "%" + fmt.Sprintf("c%d", num)
  10278. cell = fmt.Sprintf(cell, 'A'+2)
  10279. f.SetCellValue(sheetName, cell, plan["projname"])
  10280. f.SetCellStyle(sheetName, cell, cell, styleID)
  10281. cell = "%" + fmt.Sprintf("c%d", num)
  10282. cell = fmt.Sprintf(cell, 'A'+3)
  10283. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10284. f.SetCellValue(sheetName, cell, plan["mydate"])
  10285. f.SetCellStyle(sheetName, cell, cell, styleID)
  10286. cell = "%" + fmt.Sprintf("c%d", num)
  10287. cell = fmt.Sprintf(cell, 'A'+6)
  10288. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10289. f.SetCellValue(sheetName, cell, plan["intime"])
  10290. f.SetCellStyle(sheetName, cell, cell, styleID)
  10291. num += 1
  10292. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10293. for i, header := range headers1 {
  10294. cell = "%" + fmt.Sprintf("c%d", num)
  10295. cell = fmt.Sprintf(cell, 'C'+i)
  10296. f.SetCellValue(sheetName, cell, header)
  10297. f.SetCellStyle(sheetName, cell, cell, styleID)
  10298. // maxWidth := len(header)
  10299. // colName := string('C' + i)
  10300. // f.SetColWidth(sheetName, colName, colName, 20)
  10301. f.SetColWidth(sheetName, header, header, 40)
  10302. }
  10303. num += 1
  10304. // 在循环外部创建红色样式(只创建一次)
  10305. redStyle := &excelizexuri.Style{
  10306. Fill: excelizexuri.Fill{
  10307. Type: "pattern",
  10308. Color: []string{"FF0000"},
  10309. Pattern: 1,
  10310. },
  10311. // Font: &excelizexuri.Font{
  10312. // Bold: true, // 加粗
  10313. // Size: 24, // 字体大小
  10314. // // Name: "宋体", // 字体名称
  10315. // // WrapText :true,
  10316. // Color: "FFFF0000", // 字体颜色(黑色)
  10317. // },
  10318. Alignment: &excelizexuri.Alignment{
  10319. Vertical: "center",
  10320. Horizontal: "center",
  10321. ShrinkToFit: true,
  10322. WrapText: true,
  10323. },
  10324. }
  10325. redStyleID, err := f.NewStyle(redStyle)
  10326. if err != nil {
  10327. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10328. return
  10329. }
  10330. // 在循环内部正确使用条件判断
  10331. for _, planExec := range planExecMap[plan["id"]] {
  10332. var currentStyleID int
  10333. if planExec["abnormal"] == "1" {
  10334. currentStyleID = redStyleID
  10335. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10336. } else {
  10337. currentStyleID = styleID
  10338. }
  10339. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10340. sort, _ := strconv.Atoi(planExec["sort"])
  10341. f.SetCellValue(sheetName, cell, sort)
  10342. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10343. cell = fmt.Sprintf("D%d", num)
  10344. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10345. f.SetCellValue(sheetName, cell, lweight)
  10346. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10347. cell = fmt.Sprintf("E%d", num)
  10348. if _, ok := planExec["actualweightminus"]; ok {
  10349. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10350. f.SetCellValue(sheetName, cell, actualweightminus)
  10351. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10352. } else {
  10353. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10354. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10355. }
  10356. cell = fmt.Sprintf("F%d", num)
  10357. f.SetCellValue(sheetName, cell, planExec["fname"])
  10358. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10359. cell = fmt.Sprintf("G%d", num)
  10360. if _, ok := planExec["diff"]; ok {
  10361. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10362. f.SetCellValue(sheetName, cell, diff)
  10363. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10364. } else {
  10365. f.SetCellValue(sheetName, cell, planExec["diff"])
  10366. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10367. }
  10368. cell = fmt.Sprintf("H%d", num)
  10369. if _, ok := planExec["diffRate"]; ok {
  10370. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10371. f.SetCellValue(sheetName, cell, diffRate)
  10372. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10373. } else {
  10374. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10375. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10376. }
  10377. cell = fmt.Sprintf("I%d", num)
  10378. f.SetCellValue(sheetName, cell, planExec["intime"])
  10379. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10380. cell = fmt.Sprintf("J%d", num)
  10381. if _, ok := planExec["lastactualweight"]; ok {
  10382. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10383. f.SetCellValue(sheetName, cell, lastactualweight)
  10384. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10385. } else {
  10386. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10387. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10388. }
  10389. cell = fmt.Sprintf("K%d", num)
  10390. if _, ok := planExec["actualweight"]; ok {
  10391. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10392. f.SetCellValue(sheetName, cell, actualweight)
  10393. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10394. } else {
  10395. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10396. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10397. }
  10398. num += 1
  10399. }
  10400. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10401. for i, header := range headers2 {
  10402. cell := "%" + fmt.Sprintf("c%d", num)
  10403. cell = fmt.Sprintf(cell, 'C'+i)
  10404. f.SetCellValue(sheetName, cell, header)
  10405. f.SetCellStyle(sheetName, cell, cell, styleID)
  10406. maxWidth := len(header)
  10407. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10408. }
  10409. num += 1
  10410. for _, plan2 := range plan2Map[plan["id"]] {
  10411. var currentStyleID int
  10412. if plan2["abnormal"] == "1" {
  10413. currentStyleID = redStyleID
  10414. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10415. } else {
  10416. currentStyleID = styleID
  10417. }
  10418. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10419. sort, _ := strconv.Atoi(plan2["sort"])
  10420. f.SetCellValue(sheetName, cell, sort)
  10421. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10422. cell = fmt.Sprintf("D%d", num)
  10423. f.SetCellValue(sheetName, cell, plan2["fname"])
  10424. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10425. cell = fmt.Sprintf("E%d", num)
  10426. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10427. f.SetCellValue(sheetName, cell, lweight)
  10428. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10429. cell = fmt.Sprintf("F%d", num)
  10430. if _, ok := plan2["actualweightminus"]; ok {
  10431. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10432. f.SetCellValue(sheetName, cell, actualweightminus)
  10433. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10434. } else {
  10435. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10436. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10437. }
  10438. cell = fmt.Sprintf("G%d", num)
  10439. if _, ok := plan2["diff"]; ok {
  10440. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10441. f.SetCellValue(sheetName, cell, diff)
  10442. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10443. } else {
  10444. f.SetCellValue(sheetName, cell, plan2["diff"])
  10445. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10446. }
  10447. cell = fmt.Sprintf("H%d", num)
  10448. if _, ok := plan2["diffRate"]; ok {
  10449. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10450. f.SetCellValue(sheetName, cell, diffRate)
  10451. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10452. } else {
  10453. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10454. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10455. }
  10456. cell = fmt.Sprintf("I%d", num)
  10457. f.SetCellValue(sheetName, cell, plan2["intime"])
  10458. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10459. cell = fmt.Sprintf("J%d", num)
  10460. if _, ok := plan2["lastactualweight"]; ok {
  10461. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10462. f.SetCellValue(sheetName, cell, lastactualweight)
  10463. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10464. } else {
  10465. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10466. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10467. }
  10468. cell = fmt.Sprintf("K%d", num)
  10469. if _, ok := plan2["lastactualweight"]; ok {
  10470. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10471. f.SetCellValue(sheetName, cell, actualweight)
  10472. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10473. } else {
  10474. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10475. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10476. }
  10477. num += 1
  10478. }
  10479. num += 1
  10480. notBorder = append(notBorder, num)
  10481. }
  10482. // for i := 2; i < num; i++ {
  10483. // exist := false
  10484. // for _, n := range notBorder {
  10485. // if i+1 == n {
  10486. // exist = true
  10487. // break
  10488. // }
  10489. // }
  10490. // if !exist {
  10491. // // 为 A-K 列设置边框
  10492. // for col := 'A'; col <= 'K'; col++ {
  10493. // cellName := fmt.Sprintf("%c%d", col, i)
  10494. // style, _ := f.NewStyle(&excelizexuri.Style{
  10495. // // Border: border,
  10496. // Alignment: &excelizexuri.Alignment{
  10497. // Vertical: "center",
  10498. // Horizontal: "center",
  10499. // ShrinkToFit: true,
  10500. // WrapText: true,
  10501. // },
  10502. // })
  10503. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10504. // }
  10505. // }
  10506. // }
  10507. for col := 'A'; col <= 'K'; col++ {
  10508. colName := string(col)
  10509. switch colName {
  10510. case "A", "B": // 牧场名称、TMR列
  10511. f.SetColWidth(sheetName, colName, colName, 10)
  10512. case "C": // 操作编号列
  10513. f.SetColWidth(sheetName, colName, colName, 10)
  10514. case "D", "E": // 计划重量、实际重量列
  10515. f.SetColWidth(sheetName, colName, colName, 12)
  10516. case "F": // 代表成分/投料位置列
  10517. f.SetColWidth(sheetName, colName, colName, 20)
  10518. case "G", "H": // 误差数、准确率列
  10519. f.SetColWidth(sheetName, colName, colName, 12)
  10520. case "I": // 完成时间列
  10521. f.SetColWidth(sheetName, colName, colName, 15)
  10522. case "J", "K": // 起始读数重量、完成读数重量列
  10523. f.SetColWidth(sheetName, colName, colName, 15)
  10524. }
  10525. }
  10526. // 设置响应头
  10527. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10528. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10529. c.Header("Content-Transfer-Encoding", "binary")
  10530. // 写入 Excel 文件到响应
  10531. if err := f.Write(c.Writer); err != nil {
  10532. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10533. return
  10534. }
  10535. }
  10536. func RestartMqtt(c *gin.Context) {
  10537. appG := app.Gin{C: c}
  10538. // 发送 GET 请求到 MQTT 重启接口
  10539. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10540. if err != nil {
  10541. logging.Error("RestartMqtt request failed:", err)
  10542. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10543. return
  10544. }
  10545. defer resp.Body.Close()
  10546. // 读取响应内容f
  10547. body, err := ioutil.ReadAll(resp.Body)
  10548. if err != nil {
  10549. logging.Error("RestartMqtt read response failed:", err)
  10550. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10551. return
  10552. }
  10553. // 检查响应状态码
  10554. if resp.StatusCode != http.StatusOK {
  10555. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10556. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10557. return
  10558. }
  10559. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10560. }
  10561. func FpdBatchEditByWeight(c *gin.Context) {
  10562. appG := app.Gin{C: c}
  10563. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10564. fsions := gofasion.NewFasion(string(dataByte))
  10565. barList := fsions.Get("barList").Array()
  10566. pastureid := fsions.Get("pastureId").ValueStr()
  10567. tx := restful.Engine.NewSession()
  10568. defer tx.Close()
  10569. 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
  10570. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10571. if err != nil {
  10572. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10573. return
  10574. }
  10575. for _, barFsions := range barList {
  10576. dataexcel := make(map[string]interface{}, 0)
  10577. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10578. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10579. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10580. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10581. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10582. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10583. continue
  10584. }
  10585. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10586. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10587. // if err != nil {
  10588. // logs.Error(err)
  10589. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10590. // return
  10591. // }
  10592. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10593. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10594. // if err != nil {
  10595. // logs.Error(err)
  10596. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10597. // return
  10598. // }
  10599. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10600. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10601. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10602. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10603. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10604. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10605. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10606. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10607. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10608. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10609. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10610. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10611. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10612. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10613. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10614. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10615. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10616. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10617. if err != nil {
  10618. logs.Error(err)
  10619. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10620. return
  10621. }
  10622. if !ftexist {
  10623. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10624. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10625. if err != nil {
  10626. logs.Error(err)
  10627. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10628. return
  10629. }
  10630. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10631. if err != nil {
  10632. logs.Error(err)
  10633. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10634. return
  10635. }
  10636. }
  10637. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10638. if err != nil {
  10639. logs.Error(err)
  10640. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10641. return
  10642. }
  10643. if !exist {
  10644. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10645. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10646. if err != nil {
  10647. logs.Error(err)
  10648. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10649. return
  10650. }
  10651. }
  10652. var feedpargs []interface{}
  10653. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10654. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10655. if _, ok := dataexcel["ftname"]; ok {
  10656. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10657. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10658. // upFeedpSql += `,ftweight = ? `
  10659. // feedpargs = append(feedpargs, weight)
  10660. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10661. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10662. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10663. } else {
  10664. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10665. }
  10666. // if _, ok := dataexcel["ptsfname"]; ok {
  10667. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10668. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10669. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10670. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10671. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10672. // } else {
  10673. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10674. // }
  10675. upFeedpSql += " where barname = ? and pastureid = ? "
  10676. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10677. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10678. if err != nil {
  10679. logs.Error(err)
  10680. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10681. return
  10682. }
  10683. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10684. if err != nil {
  10685. logs.Error(err)
  10686. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10687. return
  10688. }
  10689. if !exist1 {
  10690. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10691. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10692. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10693. if err != nil {
  10694. logs.Error(err)
  10695. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10696. return
  10697. }
  10698. }
  10699. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10700. if err != nil {
  10701. logs.Error(err)
  10702. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10703. return
  10704. }
  10705. if !exist2 {
  10706. _, 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) `,
  10707. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10708. if err != nil {
  10709. logs.Error(err)
  10710. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10711. return
  10712. }
  10713. }
  10714. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10715. if err != nil {
  10716. logs.Error(err)
  10717. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10718. return
  10719. }
  10720. if !exist3 {
  10721. _, 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) `,
  10722. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10723. if err != nil {
  10724. logs.Error(err)
  10725. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10726. return
  10727. }
  10728. }
  10729. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10730. if err != nil {
  10731. logs.Error(err)
  10732. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10733. return
  10734. }
  10735. if !exist4 {
  10736. _, 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) `,
  10737. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10738. if err != nil {
  10739. logs.Error(err)
  10740. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10741. return
  10742. }
  10743. }
  10744. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10745. if err != nil {
  10746. logs.Error(err)
  10747. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10748. return
  10749. }
  10750. if !exist5 {
  10751. _, 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) `,
  10752. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10753. if err != nil {
  10754. logs.Error(err)
  10755. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10756. return
  10757. }
  10758. }
  10759. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10760. if err != nil {
  10761. logs.Error(err)
  10762. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10763. return
  10764. }
  10765. if !exist6 {
  10766. _, 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) `,
  10767. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10768. if err != nil {
  10769. logs.Error(err)
  10770. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10771. return
  10772. }
  10773. }
  10774. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10775. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10776. and pastureid = ? and times = ?`
  10777. var fpdargs1 []interface{}
  10778. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10779. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10780. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10781. if err != nil {
  10782. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10783. return
  10784. }
  10785. var fpdargs2 []interface{}
  10786. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10787. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10788. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10789. if err != nil {
  10790. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10791. return
  10792. }
  10793. var fpdargs3 []interface{}
  10794. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10795. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10796. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10797. if err != nil {
  10798. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10799. return
  10800. }
  10801. var fpdargs4 []interface{}
  10802. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10803. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10804. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10805. if err != nil {
  10806. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10807. return
  10808. }
  10809. var fpdargs5 []interface{}
  10810. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10811. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10812. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10813. if err != nil {
  10814. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10815. return
  10816. }
  10817. var fpdargs6 []interface{}
  10818. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10819. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10820. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10821. if err != nil {
  10822. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10823. return
  10824. }
  10825. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10826. 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()
  10827. if err != nil {
  10828. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10829. return
  10830. }
  10831. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10832. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10833. upFpdetailList := make([]*upFpdetail, 0)
  10834. for _, newfpd := range newList {
  10835. for _, oldfpd := range oldFpdList {
  10836. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10837. var oldweight, newweight float64
  10838. if oldfpd["weight"] != nil {
  10839. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10840. }
  10841. if newfpd["weight"] != nil {
  10842. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10843. }
  10844. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10845. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10846. Old: oldweight,
  10847. New: newweight,
  10848. Times: newfpd["times"].(int64),
  10849. Ptid: newfpd["ptid"].(int64),
  10850. Fweight: fweight,
  10851. Id: oldfpd["id"].(int64),
  10852. })
  10853. break
  10854. }
  10855. }
  10856. }
  10857. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10858. }
  10859. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10860. }
  10861. func FtImportExcel(c *gin.Context) {
  10862. appG := app.Gin{C: c}
  10863. inputdata := ""
  10864. c.Request.ParseForm()
  10865. params := c.Request.Form
  10866. file, _, err := c.Request.FormFile("file")
  10867. if err != nil {
  10868. appG.Response(http.StatusOK, e.ERROR, err)
  10869. return
  10870. }
  10871. sqlnamestrs := params.Get("name")
  10872. sheetname := params.Get("sheetname")
  10873. pastureid := params.Get("pastureid")
  10874. //importParams := params.Get("importParams")
  10875. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10876. // 必输项参数 (字符串格式 "field1,field2,field3")
  10877. requiredParams := params.Get("requiredParams")
  10878. // 日期参数
  10879. dateParams := params.Get("dateParams")
  10880. // 数字参数
  10881. numParams := params.Get("numParams")
  10882. //将字符串分割开
  10883. dateParamslist := strings.Split(dateParams, ",")
  10884. requiredParamslist := strings.Split(requiredParams, ",")
  10885. numParamslist := strings.Split(numParams, ",")
  10886. queryData := make([]interface{}, 0)
  10887. sqlslist := strings.Split(sqlnamestrs, ",")
  10888. xlsx1, err := excelize.OpenReader(file)
  10889. if err != nil {
  10890. fmt.Println(err)
  10891. return
  10892. }
  10893. ok := 0
  10894. error := 0
  10895. isdone := true
  10896. rows := xlsx1.GetRows(sheetname)
  10897. // 限制10000条,多余的截取掉
  10898. if len(rows) > 10000 {
  10899. rows = rows[:10000]
  10900. }
  10901. tx := restful.Engine.NewSession()
  10902. ftNameList := make(map[string]interface{})
  10903. var ftNames []interface{}
  10904. for i, row := range rows {
  10905. if i > 0 {
  10906. entry := make(map[string]interface{})
  10907. outentry := make(map[string]interface{})
  10908. for j, colCell := range rows[0] {
  10909. for k, colCell1 := range row {
  10910. if j == k {
  10911. outentry[colCell] = colCell1
  10912. entry[colCell] = colCell1
  10913. }
  10914. }
  10915. }
  10916. inputdata = ""
  10917. a := ""
  10918. fmt.Println(outentry, entry)
  10919. //校验日期格式
  10920. for _, v := range dateParamslist {
  10921. if v == "" {
  10922. continue
  10923. }
  10924. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10925. dtime, err := TransfTime(d.(string))
  10926. if err != nil {
  10927. a = strings.Trim(v, " ")
  10928. break
  10929. }
  10930. outentry[strings.Trim(v, " ")] = dtime
  10931. }
  10932. }
  10933. if a != "" {
  10934. outentry["error_msg"] = a + " 格式错误"
  10935. error++
  10936. queryData = append(queryData, outentry)
  10937. continue
  10938. }
  10939. a = ""
  10940. //校验必填格式
  10941. for _, v := range requiredParamslist {
  10942. if v == "" {
  10943. continue
  10944. }
  10945. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10946. a = strings.Trim(v, " ")
  10947. break
  10948. }
  10949. }
  10950. if a != "" {
  10951. outentry["error_msg"] = a + " 未填或格式错误"
  10952. error++
  10953. queryData = append(queryData, outentry)
  10954. continue
  10955. }
  10956. a = ""
  10957. //校验数字格式
  10958. for _, v := range numParamslist {
  10959. if v == "" {
  10960. continue
  10961. }
  10962. d, ok := outentry[strings.Trim(v, " ")]
  10963. if !ok || d == "" {
  10964. outentry[strings.Trim(v, " ")] = 0
  10965. } else {
  10966. var fl float64
  10967. switch d.(type) {
  10968. case string:
  10969. fl, err = strconv.ParseFloat(d.(string), 64)
  10970. }
  10971. if err != nil || fl < 0 {
  10972. a = strings.Trim(v, " ")
  10973. break
  10974. }
  10975. }
  10976. }
  10977. if a != "" {
  10978. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10979. error++
  10980. queryData = append(queryData, outentry)
  10981. continue
  10982. }
  10983. err := tx.Begin()
  10984. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10985. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10986. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10987. }
  10988. for _, sqlnamestr := range sqlslist {
  10989. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  10990. paramslist := strings.Split(paramslists, ",")
  10991. if len(paramslist) > 0 {
  10992. s_params := make([]interface{}, 0)
  10993. for _, value := range paramslist {
  10994. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  10995. if tempv, exists := c.Get("jwt_username"); exists {
  10996. s_params = append(s_params, tempv.(string))
  10997. } else {
  10998. s_params = append(s_params, "")
  10999. }
  11000. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11001. s_params = append(s_params, pastureid)
  11002. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11003. ids, err := setting.SnowIds.NextId()
  11004. if err != nil {
  11005. ids = time.Now().UnixNano()
  11006. logging.Info("create SnowIds err", err)
  11007. }
  11008. s_params = append(s_params, ids)
  11009. } else {
  11010. if outentry[strings.Trim(value, " ")] == nil {
  11011. s_params = append(s_params, "")
  11012. } else {
  11013. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11014. }
  11015. }
  11016. }
  11017. outentry["input"] = inputdata
  11018. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11019. if err != nil {
  11020. if tx != nil {
  11021. tx.Rollback()
  11022. }
  11023. if tx != nil {
  11024. tx.Close()
  11025. }
  11026. msg := geterrmsg(err.Error())
  11027. outentry["error_msg"] = msg
  11028. error++
  11029. queryData = append(queryData, outentry)
  11030. isdone = true
  11031. break
  11032. } else {
  11033. if len(returnmsgmap1) > 0 {
  11034. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11035. if tx != nil {
  11036. tx.Rollback()
  11037. }
  11038. if tx != nil {
  11039. tx.Close()
  11040. }
  11041. msg := geterrmsg(va.(string))
  11042. outentry["error_msg"] = msg
  11043. error++
  11044. queryData = append(queryData, outentry)
  11045. isdone = true
  11046. break
  11047. }
  11048. }
  11049. isdone = false
  11050. }
  11051. }
  11052. }
  11053. ftNames = append(ftNames, outentry["配方名称"])
  11054. switch {
  11055. case err != nil:
  11056. if tx != nil {
  11057. tx.Rollback()
  11058. }
  11059. default:
  11060. if tx != nil {
  11061. err = tx.Commit()
  11062. }
  11063. }
  11064. if tx != nil {
  11065. tx.Close()
  11066. }
  11067. }
  11068. if !isdone {
  11069. ok++
  11070. isdone = true
  11071. }
  11072. }
  11073. go ftSync(ftNames, pastureid)
  11074. data := make(map[string]interface{})
  11075. data["result"] = queryData
  11076. data["success"] = ok
  11077. data["err_count"] = error
  11078. appG.Response(http.StatusOK, e.SUCCESS, data)
  11079. }
  11080. func ftSync(ftNameList []interface{}, pastureId string) {
  11081. tx := restful.Engine.NewSession()
  11082. defer tx.Close()
  11083. for _, ftName := range ftNameList {
  11084. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11085. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11086. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11087. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11088. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11089. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11090. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11091. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11092. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11093. FpdBatchEditGrfd(pastureId, values1)
  11094. }
  11095. }
  11096. func CopyFeedtemplet(c *gin.Context) {
  11097. appG := app.Gin{C: c}
  11098. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11099. fsion := gofasion.NewFasion(string(dataByte))
  11100. pastureid := fsion.Get("pastureid").ValueStr()
  11101. newName := fsion.Get("newName").ValueStr()
  11102. id := fsion.Get("id").ValueStr()
  11103. tx := restful.Engine.NewSession()
  11104. defer tx.Close()
  11105. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11106. if err != nil {
  11107. appG.Response(http.StatusOK, e.ERROR, err)
  11108. return
  11109. }
  11110. if count > 0 {
  11111. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11112. return
  11113. }
  11114. type ftCode struct {
  11115. Tcode string `xorm:"tcode"`
  11116. }
  11117. code := new(ftCode)
  11118. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11119. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11120. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11121. if err != nil {
  11122. appG.Response(http.StatusOK, e.ERROR, err)
  11123. return
  11124. }
  11125. if code.Tcode == "" {
  11126. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11127. return
  11128. }
  11129. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11130. remark,enable,sort,volume,autozone)
  11131. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11132. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11133. if err != nil {
  11134. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11135. return
  11136. }
  11137. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11138. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11139. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11140. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11141. from ftdetail where ftid = ? `, code.Tcode, id)
  11142. if err != nil {
  11143. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11144. return
  11145. }
  11146. appG.Response(http.StatusOK, e.SUCCESS, true)
  11147. }
  11148. func Test(c *gin.Context) {
  11149. appG := app.Gin{C: c}
  11150. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11151. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11152. }
  11153. func GetPlanDry(c *gin.Context) {
  11154. appG := app.Gin{C: c}
  11155. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11156. fsion := gofasion.NewFasion(string(dataByte))
  11157. date := fsion.Get("date").ValueStr()
  11158. tx := restful.Engine.NewSession()
  11159. defer tx.Close()
  11160. dataList, err := tx.SQL(`SELECT
  11161. t.feedtempletName,
  11162. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11163. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11164. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11165. t.tmrno,
  11166. t.bname,
  11167. t.barid,
  11168. t.dry,
  11169. t.actualweightminus,
  11170. t.mydate,
  11171. t.pasturename,
  11172. t.endDate,
  11173. t.startDate,
  11174. t.times,
  11175. -- 计算startDate和endDate的中间时间
  11176. ifnull(DATE_FORMAT(
  11177. DATE_ADD(
  11178. t.startDate,
  11179. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11180. ),
  11181. '%Y-%m-%d %H:%i:%s'
  11182. ),'') AS midTime
  11183. FROM (
  11184. SELECT
  11185. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11186. b.bname,
  11187. b.id barid,
  11188. 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
  11189. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11190. JOIN feednur fn ON fn.fid = dd1.fid
  11191. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11192. 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,
  11193. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11194. p.pasture_name pastureName,
  11195. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11196. DATE_FORMAT(IFNULL(
  11197. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11198. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11199. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11200. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11201. ), '%Y-%m-%d %H:%i:%s') startDate,
  11202. d.times ,
  11203. ( SELECT
  11204. round(SUM(
  11205. IF(ftd.preftid<>0,
  11206. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11207. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11208. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11209. ftd.fweight*f.dry/100)) ,2)
  11210. dryweight
  11211. FROM ftdetaildate ftd
  11212. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11213. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11214. select
  11215. sum(ftd.fweight)
  11216. FROM ftdetaildate ftd
  11217. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11218. ( SELECT
  11219. round(SUM(
  11220. IF(ftd.preftid<>0,
  11221. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11222. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11223. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11224. ftd.fweight*f.uprice)) ,2)
  11225. dryweight
  11226. FROM ftdetaildate ftd
  11227. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11228. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11229. feedtempletPrice,d.templetname feedtempletName
  11230. FROM downloadedplan d
  11231. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11232. JOIN bar b ON b.id = d2.fbarid
  11233. JOIN pasture p ON p.pastureid = d.pastureid
  11234. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11235. AND d2.type = 0
  11236. AND d.havebutton = 1
  11237. ) t
  11238. WHERE 1=1 `, date).QueryString()
  11239. if err != nil {
  11240. logs.Error(err)
  11241. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11242. return
  11243. }
  11244. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11245. }
  11246. func GetBar(c *gin.Context) {
  11247. appG := app.Gin{C: c}
  11248. tx := restful.Engine.NewSession()
  11249. defer tx.Close()
  11250. pastureinfo := new(udPastureInfo)
  11251. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11252. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11253. if err != nil {
  11254. logs.Error(err)
  11255. return
  11256. }
  11257. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).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 GetHomepage(c *gin.Context) {
  11266. appG := app.Gin{C: c}
  11267. tx := restful.Engine.NewSession()
  11268. defer tx.Close()
  11269. dataList, err := tx.SQL(` SELECT
  11270. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11271. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11272. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11273. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11274. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11275. 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日混料准确率
  11276. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11277. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11278. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11279. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11280. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11281. 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日撒料准确率
  11282. 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),'%') -- 正确率
  11283. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11284. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11285. (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),'%') -- 正确率
  11286. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11287. WHERE dt.pastureid = d.pastureid
  11288. 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日正确率
  11289. (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,
  11290. (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,
  11291. 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,
  11292. 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,
  11293. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11294. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11295. FROM
  11296. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11297. 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()
  11298. if err != nil {
  11299. logs.Error(err)
  11300. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11301. return
  11302. }
  11303. dataList1, err := tx.SQL(`select
  11304. 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
  11305. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11306. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11307. if err != nil {
  11308. logs.Error(err)
  11309. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11310. return
  11311. }
  11312. for _, data := range dataList {
  11313. for _, data1 := range dataList1 {
  11314. data["totalCost"] = data1["totalCost"]
  11315. data["cost"] = data1["cost"]
  11316. }
  11317. }
  11318. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11319. }
  11320. func GetFeedingManagement(c *gin.Context) {
  11321. appG := app.Gin{C: c}
  11322. typea := c.Query("typea") // 0 栏舍 1 日期
  11323. startDate := c.Query("startdate")
  11324. endDate := c.Query("enddate")
  11325. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11326. // fsion := gofasion.NewFasion(string(dataByte))
  11327. tx := restful.Engine.NewSession()
  11328. defer tx.Close()
  11329. if typea == "0" {
  11330. 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
  11331. SUM(
  11332. 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 ,
  11333. 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)*
  11334. 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 )),
  11335. 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)*
  11336. 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 ))
  11337. )
  11338. )actualweightminus ,
  11339. SUM(
  11340. 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 ,
  11341. 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)*
  11342. 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 )),
  11343. 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)*
  11344. 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 ))
  11345. ) * ifnull(fn.dry,0)
  11346. ) dryweight , SUM(
  11347. 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 ,
  11348. 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)*
  11349. 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 )),
  11350. 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)*
  11351. 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 ))
  11352. ) * ifnull(f.uprice,0)
  11353. ) priceweight
  11354. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11355. FROM
  11356. downloadedplan d
  11357. JOIN downloadplandtl2 d2
  11358. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11359. JOIN downloadplandtl1 d1
  11360. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11361. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11362. 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
  11363. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11364. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11365. left join feednur fn on fn.fid = f.id
  11366. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11367. if err != nil {
  11368. logs.Error(err)
  11369. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11370. return
  11371. }
  11372. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11373. } else {
  11374. 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
  11375. SUM(
  11376. 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 ,
  11377. 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)*
  11378. 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 )),
  11379. 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)*
  11380. 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 ))
  11381. )
  11382. )actualweightminus ,
  11383. SUM(
  11384. 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 ,
  11385. 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)*
  11386. 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 )),
  11387. 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)*
  11388. 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 ))
  11389. ) * ifnull(fn.dry,0)
  11390. ) dryweight , SUM(
  11391. 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 ,
  11392. 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)*
  11393. 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 )),
  11394. 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)*
  11395. 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 ))
  11396. ) * ifnull(f.uprice,0)
  11397. ) priceweight
  11398. ,(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
  11399. FROM
  11400. downloadedplan d
  11401. JOIN downloadplandtl2 d2
  11402. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11403. JOIN downloadplandtl1 d1
  11404. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11405. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11406. 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
  11407. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11408. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11409. left join feednur fn on fn.fid = f.id
  11410. WHERE d.mydate BETWEEN ? AND ?
  11411. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11412. if err != nil {
  11413. logs.Error(err)
  11414. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11415. return
  11416. }
  11417. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11418. }
  11419. }
  11420. func GetFpdetailFname(c *gin.Context) {
  11421. appG := app.Gin{C: c}
  11422. // id := c.Query("id")
  11423. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11424. fsion := gofasion.NewFasion(string(dataByte))
  11425. id := fsion.Get("id").ValueDefaultStr("")
  11426. tx := restful.Engine.NewSession()
  11427. defer tx.Close()
  11428. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11429. err := tx.SQL(` SELECT
  11430. TRIM(ftid)ftid,TRIM(fid)fid,
  11431. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11432. fweight,sort,
  11433. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11434. FROM
  11435. ftdetail
  11436. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11437. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11438. if err != nil {
  11439. logs.Error(err)
  11440. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11441. return
  11442. }
  11443. fpdetailList := make([]*models.Fpdetail, 0)
  11444. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11445. if err != nil {
  11446. logs.Error(err)
  11447. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11448. return
  11449. }
  11450. for _, f := range fpdetailFnameList {
  11451. f.FWeight = 0
  11452. for _, fpd := range fpdetailList {
  11453. value := f.SumFWeight * fpd.Weight
  11454. // 将其四舍五入到小数点后两位
  11455. roundedValue := math.Round(value*100) / 100
  11456. if fpd.Times == 1 {
  11457. f.TimesOne = roundedValue
  11458. } else if fpd.Times == 2 {
  11459. f.TimesTwo = roundedValue
  11460. } else if fpd.Times == 3 {
  11461. f.TimesThree = roundedValue
  11462. } else if fpd.Times == 4 {
  11463. f.TimesFour = roundedValue
  11464. } else if fpd.Times == 5 {
  11465. f.TimesFive = roundedValue
  11466. } else if fpd.Times == 6 {
  11467. f.TimesSix = roundedValue
  11468. }
  11469. f.FWeight += value
  11470. }
  11471. }
  11472. fpdetailFname := new(models.FpdetailFname)
  11473. fpdetailFname.FName = "合计"
  11474. for _, f := range fpdetailFnameList {
  11475. fpdetailFname.TimesOne += f.TimesOne
  11476. fpdetailFname.TimesTwo += f.TimesTwo
  11477. fpdetailFname.TimesThree += f.TimesThree
  11478. fpdetailFname.TimesFour += f.TimesFour
  11479. fpdetailFname.TimesFive += f.TimesFive
  11480. fpdetailFname.TimesSix += f.TimesSix
  11481. fpdetailFname.FWeight += f.FWeight
  11482. f.FWeight = RoundFloat(f.FWeight, 2)
  11483. }
  11484. // 在处理代码中
  11485. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11486. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11487. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11488. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11489. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11490. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11491. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11492. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11493. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11494. }
  11495. func RoundFloat(x float64, prec int) float64 {
  11496. output := math.Pow(10, float64(prec))
  11497. return math.Round(x*output) / output
  11498. }
  11499. func GetLyUdData(c *gin.Context) {
  11500. appG := app.Gin{C: c}
  11501. // id := c.Query("id")
  11502. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11503. fsion := gofasion.NewFasion(string(dataByte))
  11504. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11505. times := fsion.Get("Times").ValueDefaultStr("")
  11506. name := fsion.Get("name").ValueDefaultStr("")
  11507. tx := restful.Engine.NewSession()
  11508. defer tx.Close()
  11509. if name == "dateplanlist"{
  11510. 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
  11511. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11512. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11513. 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
  11514. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11515. 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
  11516. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11517. GROUP BY dl.id order by ProjName `,myDate,times,myDate,times).Query().List()
  11518. fmt.Println(err )
  11519. appG.Response(http.StatusOK, e.SUCCESS, data)
  11520. return
  11521. }else if name == "getAddFeed"{
  11522. 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,
  11523. 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,
  11524. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11525. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11526. 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
  11527. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11528. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11529. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11530. 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,
  11531. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11532. 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,
  11533. '' 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,
  11534. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11535. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11536. 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
  11537. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11538. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11539. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11540. 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()
  11541. appG.Response(http.StatusOK, e.SUCCESS, data)
  11542. return
  11543. }else if name == "getDeleteFeed"{
  11544. 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,
  11545. 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 ,
  11546. (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
  11547. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11548. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11549. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`,myDate,times,myDate,times).Query().List()
  11550. appG.Response(http.StatusOK, e.SUCCESS, data)
  11551. return
  11552. }
  11553. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11554. }