ops.go 410 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "path"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "tmr-watch/conf/setting"
  20. "tmr-watch/http/handle/jpud"
  21. "tmr-watch/http/handle/restful"
  22. "tmr-watch/models"
  23. "tmr-watch/module"
  24. "tmr-watch/pkg/app"
  25. "tmr-watch/pkg/e"
  26. "tmr-watch/pkg/logging"
  27. "github.com/360EntSecGroup-Skylar/excelize"
  28. "github.com/Anderson-Lu/gofasion/gofasion"
  29. "github.com/astaxie/beego/logs"
  30. "github.com/gin-gonic/gin"
  31. "github.com/qichengzx/coordtransform"
  32. "github.com/tealeg/xlsx"
  33. "github.com/xormplus/xorm"
  34. excelizexuri "github.com/xuri/excelize/v2"
  35. )
  36. // @Summary 根据SQL执行得到数据集
  37. // @Tags getData
  38. // @Accept json
  39. // @Produce json
  40. // @Param sql query string true "sql"
  41. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  42. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  43. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  44. // @Router /data/getdata [POST]
  45. func GetData(c *gin.Context) {
  46. appG := app.Gin{C: c}
  47. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  48. fsion := gofasion.NewFasion(string(dataByte))
  49. sqlstr := fsion.Get("sql").ValueStr()
  50. offset := fsion.Get("offset").ValueDefaultInt(0)
  51. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  52. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  53. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  54. if err != nil {
  55. appG.Response(http.StatusOK, e.ERROR, err.Error())
  56. } else {
  57. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  58. }
  59. }
  60. func Testpartitions(c *gin.Context) {
  61. appG := app.Gin{C: c}
  62. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  63. fsion := gofasion.NewFasion(string(dataByte))
  64. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  65. user := fsion.Get("user").ValueStr() //获取新数据库用户
  66. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  67. host := fsion.Get("host").ValueStr() //获取新数据库名称
  68. port := fsion.Get("port").ValueStr() //获取新数据库名称
  69. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  70. if sqls == nil || err1 != nil {
  71. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  72. }
  73. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  74. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  75. mydb, err := sql.Open("mysql", connecting) //连接新连接
  76. if err != nil {
  77. println("err1", err.Error())
  78. }
  79. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  80. if err != nil {
  81. println("err2", err.Error())
  82. }
  83. mydb.Close()
  84. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  85. mydb, err = sql.Open("mysql", connecting)
  86. if err != nil {
  87. println("err3", err.Error())
  88. }
  89. defer mydb.Close()
  90. if err == nil {
  91. mydb.SetMaxOpenConns(10)
  92. mydb.SetMaxIdleConns(10)
  93. }
  94. errmsg := ""
  95. if err == nil {
  96. //tx ,_ :=mydb.Begin()
  97. for _, sqlstr := range sqlstrs {
  98. //println("sqlstr---",sqlstr)
  99. if sqlstr == "" {
  100. continue
  101. }
  102. _, err = mydb.Exec(sqlstr)
  103. if err != nil {
  104. println("err4", err.Error())
  105. errmsg = err.Error()
  106. //err1 :=tx.Rollback()
  107. }
  108. }
  109. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  110. //err =tx.Commit()
  111. }
  112. if errmsg == "" {
  113. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  114. } else {
  115. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  116. }
  117. }
  118. func TestData(c *gin.Context) {
  119. appG := app.Gin{C: c}
  120. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  121. fsion := gofasion.NewFasion(string(dataByte))
  122. sqlstr := fsion.Get("sql").ValueStr()
  123. token := ""
  124. if tempv, exists := c.Get("jwt_username"); exists {
  125. token = tempv.(string)
  126. }
  127. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  128. }
  129. // @Summary 根据APISQL表中SQL执行得到数据集
  130. // @Tags GetDataByName
  131. // @Accept json
  132. // @Produce json
  133. // @Param sqlname body string true "sqlname"
  134. // @Param offset body int true "offset"
  135. // @Param pagecount body int true "pagecount"
  136. // @Param returntype body string true "returntype"
  137. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  138. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  139. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  140. // @Router /data/GetDataByName [POST]
  141. func GetDataByName(c *gin.Context) {
  142. appG := app.Gin{C: c}
  143. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  144. fsion := gofasion.NewFasion(string(dataByte))
  145. sqlnamestr := fsion.Get("name").ValueStr()
  146. offset := fsion.Get("offset").ValueDefaultInt(0)
  147. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  148. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  149. tx := restful.Engine.NewSession()
  150. err := tx.Begin()
  151. defer func() {
  152. switch {
  153. case err != nil:
  154. logging.Error("tx.Begin 事务启动失败__error:", err)
  155. if tx != nil {
  156. tx.Rollback()
  157. }
  158. default:
  159. if tx != nil {
  160. err = tx.Commit()
  161. }
  162. }
  163. if tx != nil {
  164. tx.Close()
  165. }
  166. }()
  167. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  168. if sql != "" {
  169. s_params := make([]interface{}, 0)
  170. if fsion.HasKey("parammaps") {
  171. parammaps := fsion.Get("parammaps")
  172. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  173. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  174. }
  175. paramslist := strings.Split(p, ",")
  176. if len(paramslist) > 0 && p != "" {
  177. for _, value := range paramslist {
  178. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  179. if tempv, exists := c.Get("jwt_username"); exists {
  180. s_params = append(s_params, tempv.(string))
  181. } else {
  182. s_params = append(s_params, "")
  183. }
  184. } else {
  185. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  186. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  187. // tmrNameList := []string{}
  188. // for _, tmr := range tmrArray {
  189. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  190. // }
  191. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  192. // } else {
  193. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  194. // }
  195. }
  196. }
  197. }
  198. } else if fsion.HasKey("params") {
  199. params := fsion.Get("params").Array()
  200. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  201. for _, v_params := range params {
  202. s_params = append(s_params, v_params.ValueStr())
  203. }
  204. }
  205. if returntype == "xlsx" {
  206. var xlsxfile *xlsx.File
  207. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  208. //c.File("c:/dd.xlsx")
  209. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  210. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  211. c.Header("Content-Transfer-Encoding", "binary")
  212. _ = xlsxfile.Write(c.Writer)
  213. } else {
  214. if sqlnamestr == "getHomepageStr" {
  215. parammaps := fsion.Get("parammaps")
  216. pastureid := parammaps.Get("pastureid").ValueStr()
  217. var montimeList []float64
  218. var montime float64
  219. var wg sync.WaitGroup
  220. now := time.Now()
  221. for i := 0; i < 30; i++ {
  222. wg.Add(1)
  223. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  224. go func(nowstr string) {
  225. defer wg.Done()
  226. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  227. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  228. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  229. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  230. montimeList = append(montimeList, m)
  231. }
  232. }(nowstr)
  233. }
  234. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  235. if err != nil {
  236. logging.Error("GetDataByName err: ", err)
  237. msg := geterrmsg(err.Error())
  238. appG.Response(http.StatusOK, e.ERROR, msg)
  239. }
  240. wg.Wait()
  241. for _, m := range montimeList {
  242. montime += m
  243. }
  244. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  245. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  246. return
  247. }
  248. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  249. if err != nil {
  250. logging.Error("GetDataByName err: ", err)
  251. msg := geterrmsg(err.Error())
  252. appG.Response(http.StatusOK, e.ERROR, msg)
  253. } else {
  254. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  255. }
  256. }
  257. } else {
  258. appG.Response(http.StatusOK, e.SUCCESS, nil)
  259. }
  260. }
  261. // @Summary 根据APISQL表中SQL执行得到数据集
  262. // @Tags GetDataByName
  263. // @Accept json
  264. // @Produce json
  265. // @Param sqlname body string true "sqlname"
  266. // @Param offset body int true "offset"
  267. // @Param pagecount body int true "pagecount"
  268. // @Param returntype body string true "returntype"
  269. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  270. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  271. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  272. // @Router /data/GetDataByName [POST]
  273. func GetDataBySqlIN(c *gin.Context) {
  274. appG := app.Gin{C: c}
  275. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  276. fsion := gofasion.NewFasion(string(dataByte))
  277. sqlnamestr := fsion.Get("name").ValueStr()
  278. offset := fsion.Get("offset").ValueDefaultInt(0)
  279. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  280. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  281. tx := restful.Engine.NewSession()
  282. err := tx.Begin()
  283. defer func() {
  284. switch {
  285. case err != nil:
  286. logging.Error("tx.Begin 事务启动失败__error:", err)
  287. if tx != nil {
  288. tx.Rollback()
  289. }
  290. default:
  291. if tx != nil {
  292. err = tx.Commit()
  293. }
  294. }
  295. if tx != nil {
  296. tx.Close()
  297. }
  298. }()
  299. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  300. if sql != "" {
  301. s_params := make([]interface{}, 0)
  302. if fsion.HasKey("parammaps") {
  303. parammaps := fsion.Get("parammaps")
  304. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  305. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  306. }
  307. paramslist := strings.Split(p, ",")
  308. if len(paramslist) > 0 && p != "" {
  309. for _, value := range paramslist {
  310. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  311. if tempv, exists := c.Get("jwt_username"); exists {
  312. s_params = append(s_params, tempv.(string))
  313. } else {
  314. s_params = append(s_params, "")
  315. }
  316. } else {
  317. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  318. }
  319. }
  320. }
  321. } else if fsion.HasKey("params") {
  322. params := fsion.Get("params").Array()
  323. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  324. for _, v_params := range params {
  325. s_params = append(s_params, v_params.ValueStr())
  326. }
  327. }
  328. if returntype == "xlsx" {
  329. var xlsxfile *xlsx.File
  330. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  331. //c.File("c:/dd.xlsx")
  332. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  333. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  334. c.Header("Content-Transfer-Encoding", "binary")
  335. _ = xlsxfile.Write(c.Writer)
  336. } else {
  337. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  338. if err != nil {
  339. logging.Error("GetDataByName err: ", err)
  340. msg := geterrmsg(err.Error())
  341. appG.Response(http.StatusOK, e.ERROR, msg)
  342. } else {
  343. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  344. }
  345. }
  346. } else {
  347. appG.Response(http.StatusOK, e.SUCCESS, nil)
  348. }
  349. }
  350. // 错误处理
  351. // 将报错信息处理成汉字
  352. func geterrmsg(errstr string) (msgstr string) {
  353. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  354. rs := []rune(errstr)
  355. if hzRegexp.MatchString(string(rs[0])) {
  356. msgstr = errstr
  357. return
  358. }
  359. if strings.Contains(errstr, "Duplicate entry") {
  360. strs := strings.Split(errstr, ` key '`)
  361. if len(strs) > 1 {
  362. if len(strs[len(strs)-1]) > 1 {
  363. errstr = "Duplicate entry :" + strs[len(strs)-1]
  364. }
  365. }
  366. }
  367. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  368. if err != nil {
  369. msgstr = errstr
  370. return
  371. }
  372. if msg == nil || len(msg) == 0 {
  373. var param []interface{}
  374. param = append(param, errstr, errstr)
  375. go func() {
  376. tx := restful.Engine.NewSession()
  377. err := tx.Begin()
  378. defer func() {
  379. switch {
  380. case err != nil:
  381. logging.Error("tx.Begin 事务启动失败__error:", err)
  382. if tx != nil {
  383. tx.Rollback()
  384. }
  385. default:
  386. if tx != nil {
  387. err = tx.Commit()
  388. }
  389. }
  390. if tx != nil {
  391. tx.Close()
  392. }
  393. }()
  394. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  395. if err != nil {
  396. logging.Error("insert into err_msg(err,msg) err", err)
  397. }
  398. }()
  399. msgstr = errstr
  400. } else {
  401. msgstr = msg[0]["msg"]
  402. }
  403. return
  404. }
  405. // @Summary 根据APISQL表中SQL执行得到数据集
  406. // @Tags GetDataByNameForm
  407. // @Accept json
  408. // @Produce json
  409. // @Param sqlname body json true "sqlname"
  410. // @Param offset query int true "offset"
  411. // @Param pagecount query int true "pagecount"
  412. // @Param returntype query string true "returntype"
  413. // @Param s formData json true "ss"
  414. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  415. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  416. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  417. // @Router /data/GetDataByNameForm [POST]
  418. func GetDataByNameForm(c *gin.Context) {
  419. appG := app.Gin{C: c}
  420. //sqlnamestr := c.PostForm("measureNumber")
  421. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  422. //fsion := gofasion.NewFasion(string(dataByte))
  423. //sqlnamestr := fsion.Get("name").ValueStr()
  424. //offset := fsion.Get("offset").ValueInt()
  425. //pagecount := fsion.Get("pagecount").ValueInt()
  426. //returntype := fsion.Get("returntype").ValueStr()
  427. //params := fsion.Get("params").Array()
  428. c.Request.ParseForm()
  429. params := c.Request.Form
  430. offset := 0
  431. pageSize_ := 0
  432. returntype := params.Get("page")
  433. if returntype == "" {
  434. returntype = "0"
  435. }
  436. if tempv, exists := c.Get("jwt_username"); exists {
  437. params.Set("JwtUserName", tempv.(string))
  438. } else {
  439. params.Set("JwtUserName", "")
  440. }
  441. sqlnamestr := params.Get("name")
  442. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  443. s_params := make([]interface{}, 0)
  444. if returntype == "1" {
  445. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  446. if error != nil {
  447. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  448. }
  449. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  450. if error != nil {
  451. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  452. }
  453. pageSize_ = pageSize
  454. offset = pageNum
  455. }
  456. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  457. paramslist := strings.Split(p, ",")
  458. if len(paramslist) > 0 && p != "" {
  459. for _, value := range paramslist {
  460. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  461. }
  462. }
  463. if sql != "" {
  464. if returntype == "xlsx" {
  465. var xlsxfile *xlsx.File
  466. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  467. c.Header("Content-Type", "application/octet-stream")
  468. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  469. c.Header("Content-Transfer-Encoding", "binary")
  470. _ = xlsxfile.Write(c.Writer)
  471. } else {
  472. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  473. if err != nil {
  474. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  475. } else {
  476. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  477. }
  478. }
  479. } else {
  480. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  481. }
  482. }
  483. // @Summary 递归获取所有
  484. // @Tags menu
  485. // @Accept json
  486. // @Produce json
  487. // @Param Ton query string true "Ton"
  488. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  489. // @Router /authdata/GetRoleMenus [GET]
  490. func GetRecuDataByName(c *gin.Context) {
  491. appG := app.Gin{C: c}
  492. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  493. fsion := gofasion.NewFasion(string(dataByte))
  494. sqlnamestr := fsion.Get("name").ValueStr()
  495. parentidname := fsion.Get("idname").ValueStr()
  496. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  497. params := make(map[string]interface{})
  498. s_params := make([]interface{}, 0)
  499. if fsion.HasKey("params") {
  500. for _, v_params := range fsion.Get("params").Array() {
  501. s_params = append(s_params, v_params.ValueStr())
  502. }
  503. params["params"] = s_params
  504. } else {
  505. jparams := fsion.Get("parammaps")
  506. paramslist := strings.Split(p, ",")
  507. if len(paramslist) > 0 && p != "" {
  508. for _, value := range paramslist {
  509. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  510. if tempv, exists := c.Get("jwt_username"); exists {
  511. params[value] = tempv.(string)
  512. } else {
  513. params[value] = ""
  514. }
  515. } else {
  516. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  517. }
  518. }
  519. }
  520. }
  521. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  522. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  523. if err != nil {
  524. appG.Response(http.StatusOK, e.ERROR, err.Error())
  525. }
  526. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  527. }
  528. // @Summary 根据APISQL表中SQL执行得到数据集
  529. // @Tags GetDataByNames
  530. // @Accept json
  531. // @Produce json
  532. // @RequestBody sqlname query string true "sqlname"
  533. // @Param offset query int true "offset"
  534. // @Param pagecount query int true "pagecount"
  535. // @Param returntype query string true "returntype"
  536. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  537. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  538. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  539. // @Router /data/GetDataByNames [POST]
  540. func GetDataByNames(c *gin.Context) {
  541. appG := app.Gin{C: c}
  542. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  543. fsion := gofasion.NewFasion(string(dataByte))
  544. sqlParams := fsion.Array()
  545. queryData := make(map[string]interface{})
  546. for _, v := range sqlParams {
  547. fsion2 := gofasion.NewFasion(v.Json())
  548. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  549. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  550. if sql == "" {
  551. errorm := make(map[string]interface{})
  552. errorm["code"] = e.ERROR
  553. errorm["message"] = "sql没找到"
  554. queryData[fsion2.Get("name").ValueStr()] = errorm
  555. continue
  556. } else if sql != "" {
  557. offset := fsion2.Get("offset").ValueInt()
  558. pagecount := fsion2.Get("pagecount").ValueInt()
  559. returntype := fsion2.Get("returntype").ValueStr()
  560. s_params := make([]interface{}, 0)
  561. if fsion2.HasKey("parammaps") {
  562. parammaps := fsion2.Get("parammaps")
  563. paramslist := strings.Split(p, ",")
  564. if len(paramslist) > 0 && p != "" {
  565. for _, value := range paramslist {
  566. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  567. if tempv, exists := c.Get("jwt_username"); exists {
  568. s_params = append(s_params, tempv.(string))
  569. } else {
  570. s_params = append(s_params, "")
  571. }
  572. } else {
  573. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  574. }
  575. }
  576. }
  577. } else if fsion2.HasKey("params") {
  578. params := fsion2.Get("params").Array()
  579. for _, v_params := range params {
  580. s_params = append(s_params, v_params.ValueStr())
  581. }
  582. }
  583. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  584. if err != nil {
  585. errorm := make(map[string]interface{})
  586. errorm["code"] = e.ERROR
  587. errorm["message"] = err.Error()
  588. queryData[fsion2.Get("name").ValueStr()] = errorm
  589. logging.Error("GetDataByNames err: ", err)
  590. continue
  591. } else {
  592. queryData[fsion2.Get("name").ValueStr()] = queryData1
  593. }
  594. }
  595. }
  596. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  597. }
  598. // @Summary 根据APISQL表中SQL执行得到数据集
  599. // @Tags PostDataByNameForm
  600. // @Accept json
  601. // @Produce json
  602. // @Param sqlname query string true "sqlname"
  603. // @Param offset query int true "offset"
  604. // @Param pagecount query int true "pagecount"
  605. // @Param returntype query string true "returntype"
  606. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  607. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  608. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  609. // @Router /data/PostDataByNameForm [POST]
  610. func PostDataByNameForm(c *gin.Context) {
  611. appG := app.Gin{C: c}
  612. c.Request.ParseForm()
  613. params := c.Request.Form
  614. sqlnamestr := params.Get("name")
  615. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  616. s_params := make([]interface{}, 0)
  617. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  618. paramslist := strings.Split(p, ",")
  619. if len(paramslist) > 0 {
  620. for _, value := range paramslist {
  621. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  622. }
  623. }
  624. if sql != "" {
  625. queryData, err := execDataBySql(sql, s_params)
  626. if err != nil {
  627. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  628. } else {
  629. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  630. }
  631. } else {
  632. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  633. }
  634. }
  635. // GetReportform 将数据集转换格式
  636. // @Tags PostDataByNameForm
  637. // @Accept json
  638. // @Produce json
  639. // @Param sqlname query string true "sqlname"
  640. // @Param offset query int true "offset"
  641. // @Param pagecount query int true "pagecount"
  642. // @Param returntype query string true "returntype"
  643. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  644. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  645. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  646. func GetReportform(c *gin.Context) {
  647. appG := app.Gin{C: c}
  648. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  649. fsion := gofasion.NewFasion(string(dataByte))
  650. sqlnamestr := fsion.Get("name").ValueStr()
  651. checked := fsion.Get("checked").ValueStr()
  652. offset := fsion.Get("offset").ValueDefaultInt(0)
  653. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  654. parammaps := fsion.Get("parammaps")
  655. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  656. mode := parammaps.Get("mode").ValueDefaultInt(0)
  657. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  658. tx := restful.Engine.NewSession()
  659. err := tx.Begin()
  660. defer func() {
  661. switch {
  662. case err != nil:
  663. if tx != nil {
  664. tx.Rollback()
  665. }
  666. default:
  667. if tx != nil {
  668. err = tx.Commit()
  669. }
  670. }
  671. if tx != nil {
  672. tx.Close()
  673. }
  674. }()
  675. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  676. if err != nil {
  677. appG.Response(http.StatusOK, e.ERROR, err.Error())
  678. } else {
  679. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  680. }
  681. }
  682. // GetUpkeepPlan 保养计划
  683. func GetUpkeepPlan(c *gin.Context) {
  684. appG := app.Gin{C: c}
  685. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  686. fsion := gofasion.NewFasion(string(dataByte))
  687. sqlnamestr := fsion.Get("name").ValueStr()
  688. offset := fsion.Get("offset").ValueDefaultInt(0)
  689. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  690. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  691. month := fsion.Get("month").ValueDefaultStr("map")
  692. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  693. tx := restful.Engine.NewSession()
  694. err := tx.Begin()
  695. defer func() {
  696. switch {
  697. case err != nil:
  698. if tx != nil {
  699. tx.Rollback()
  700. }
  701. default:
  702. if tx != nil {
  703. err = tx.Commit()
  704. }
  705. }
  706. if tx != nil {
  707. tx.Close()
  708. }
  709. }()
  710. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  711. if sql != "" {
  712. s_params := make([]interface{}, 0)
  713. if fsion.HasKey("parammaps") {
  714. parammaps := fsion.Get("parammaps")
  715. paramslist := strings.Split(p, ",")
  716. if len(paramslist) > 0 && p != "" {
  717. for _, value := range paramslist {
  718. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  719. if tempv, exists := c.Get("jwt_username"); exists {
  720. s_params = append(s_params, tempv.(string))
  721. } else {
  722. s_params = append(s_params, "")
  723. }
  724. } else {
  725. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  726. }
  727. }
  728. }
  729. } else if fsion.HasKey("params") {
  730. params := fsion.Get("params").Array()
  731. for _, v_params := range params {
  732. s_params = append(s_params, v_params.ValueStr())
  733. }
  734. }
  735. if returntype == "xlsx" {
  736. var xlsxfile *xlsx.File
  737. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  738. //c.File("c:/dd.xlsx")
  739. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  740. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  741. c.Header("Content-Transfer-Encoding", "binary")
  742. _ = xlsxfile.Write(c.Writer)
  743. } else {
  744. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  745. if err != nil {
  746. appG.Response(http.StatusOK, e.ERROR, err.Error())
  747. } else {
  748. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  749. if v, ok := value["id"]; ok {
  750. //month = "2020-03"
  751. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  752. if seviceplans != nil {
  753. for _, va := range seviceplans { //根据保养计划获取保养单
  754. //day,_ :=strconv.Atoi(va["day"])
  755. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  756. //buk := make(map[string]map[string]string)
  757. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  758. jstr := ""
  759. if bu["plantime"][8:9] == "0" {
  760. jstr = "m" + bu["plantime"][9:]
  761. } else {
  762. jstr = "m" + bu["plantime"][8:]
  763. }
  764. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  765. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  766. } else {
  767. if bu["flowCompeleted"] >= "2" {
  768. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  769. } else {
  770. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  771. }
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  779. }
  780. }
  781. } else {
  782. appG.Response(http.StatusOK, e.SUCCESS, nil)
  783. }
  784. }
  785. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  786. // todo 优化性能 children统一查询
  787. // @Tags PostDataByNameForm
  788. // @Accept json
  789. // @Produce json
  790. // @Param sqlname query string true "sqlname"
  791. // @Param offset query int true "offset"
  792. // @Param pagecount query int true "pagecount"
  793. // @Param returntype query string true "returntype"
  794. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  795. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  796. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  797. func GetArrList(c *gin.Context) {
  798. appG := app.Gin{C: c}
  799. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  800. fsion := gofasion.NewFasion(string(dataByte))
  801. sqlnamestr := fsion.Get("name").ValueStr()
  802. sqlnamestr1 := fsion.Get("name1").ValueStr()
  803. offset := fsion.Get("offset").ValueDefaultInt(0)
  804. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  805. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  806. month := fsion.Get("month").ValueDefaultStr("map")
  807. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  808. tx := restful.Engine.NewSession()
  809. err := tx.Begin()
  810. defer func() {
  811. switch {
  812. case err != nil:
  813. if tx != nil {
  814. tx.Rollback()
  815. }
  816. default:
  817. if tx != nil {
  818. err = tx.Commit()
  819. }
  820. }
  821. if tx != nil {
  822. tx.Close()
  823. }
  824. }()
  825. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  826. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  827. if sql != "" {
  828. s_params := make([]interface{}, 0)
  829. if fsion.HasKey("parammaps") {
  830. parammaps := fsion.Get("parammaps")
  831. paramslist := strings.Split(p, ",")
  832. if len(paramslist) > 0 && p != "" {
  833. for _, value := range paramslist {
  834. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  835. if tempv, exists := c.Get("jwt_username"); exists {
  836. s_params = append(s_params, tempv.(string))
  837. } else {
  838. s_params = append(s_params, "")
  839. }
  840. } else {
  841. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  842. }
  843. }
  844. }
  845. }
  846. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  847. if err != nil {
  848. appG.Response(http.StatusOK, e.ERROR, err.Error())
  849. } else {
  850. paramslist1 := strings.Split(p1, ",")
  851. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  852. s_params1 := make([]interface{}, 0)
  853. if len(paramslist1) > 0 && p1 != "" {
  854. for _, v := range paramslist1 {
  855. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  856. }
  857. }
  858. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  859. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  860. }
  861. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  862. }
  863. } else {
  864. appG.Response(http.StatusOK, e.SUCCESS, nil)
  865. }
  866. }
  867. func GetAccount(c *gin.Context) {
  868. appG := app.Gin{C: c}
  869. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  870. fsion := gofasion.NewFasion(string(dataByte))
  871. sqlnamestr := fsion.Get("name").ValueStr()
  872. offset := fsion.Get("offset").ValueDefaultInt(0)
  873. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  874. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  875. tx := restful.Engine.NewSession()
  876. err := tx.Begin()
  877. defer func() {
  878. switch {
  879. case err != nil:
  880. logging.Error("tx.Begin 事务启动失败__error:", err)
  881. if tx != nil {
  882. tx.Rollback()
  883. }
  884. default:
  885. if tx != nil {
  886. err = tx.Commit()
  887. }
  888. }
  889. if tx != nil {
  890. tx.Close()
  891. }
  892. }()
  893. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  894. if sql != "" {
  895. s_params := make([]interface{}, 0)
  896. if fsion.HasKey("parammaps") {
  897. parammaps := fsion.Get("parammaps")
  898. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  899. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  900. }
  901. paramslist := strings.Split(p, ",")
  902. if len(paramslist) > 0 && p != "" {
  903. for _, value := range paramslist {
  904. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  905. if tempv, exists := c.Get("jwt_username"); exists {
  906. s_params = append(s_params, tempv.(string))
  907. } else {
  908. s_params = append(s_params, "")
  909. }
  910. } else {
  911. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  912. }
  913. }
  914. }
  915. } else if fsion.HasKey("params") {
  916. params := fsion.Get("params").Array()
  917. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  918. for _, v_params := range params {
  919. s_params = append(s_params, v_params.ValueStr())
  920. }
  921. }
  922. if returntype == "xlsx" {
  923. var xlsxfile *xlsx.File
  924. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  925. //c.File("c:/dd.xlsx")
  926. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  927. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  928. c.Header("Content-Transfer-Encoding", "binary")
  929. _ = xlsxfile.Write(c.Writer)
  930. } else {
  931. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  932. if err != nil {
  933. logging.Error("GetDataByName err: ", err)
  934. msg := geterrmsg(err.Error())
  935. appG.Response(http.StatusOK, e.ERROR, msg)
  936. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  937. } else {
  938. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  939. }
  940. }
  941. } else {
  942. appG.Response(http.StatusOK, e.SUCCESS, nil)
  943. }
  944. }
  945. // PostDataByName 根据APISQL表中SQL执行得到数据集
  946. // @Accept json
  947. // @Produce json
  948. // @Param sqlname query string true "sqlname"
  949. // @Param offset query int true "offset"
  950. // @Param pagecount query int true "pagecount"
  951. // @Param returntype query string true "returntype"
  952. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  953. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  954. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  955. // @Router /data/PostDataByName [POST]
  956. func PostDataByName(c *gin.Context) {
  957. appG := app.Gin{C: c}
  958. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  959. fsion := gofasion.NewFasion(string(dataByte))
  960. var err error
  961. queryData, err := module.PostDataByName(c, fsion)
  962. if err != nil {
  963. appG.Response(http.StatusOK, e.ERROR, err.Error())
  964. return
  965. }
  966. var (
  967. keyWord string
  968. )
  969. switch fsion.Get("name").ValueStr() {
  970. case "insertFeedclass":
  971. keyWord = "feed"
  972. err = module.GroupCategorySync(keyWord, fsion)
  973. case "deleteFeedclass":
  974. keyWord = "feed_delete"
  975. err = module.GroupCategoryDelete(keyWord, fsion)
  976. case "insertCowclass":
  977. keyWord = "cow"
  978. err = module.GroupCategorySync(keyWord, fsion)
  979. case "deleteCowclass":
  980. keyWord = "cow_delete"
  981. err = module.GroupCategoryDelete(keyWord, fsion)
  982. // case "updateFT":
  983. // FtdetailSurplus(fsion)
  984. // case "updateFeed":
  985. // FeedSurplus(fsion)
  986. default:
  987. }
  988. if err != nil {
  989. logging.Error(keyWord, err)
  990. }
  991. if queryData != nil {
  992. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  993. return
  994. }
  995. appG.Response(http.StatusOK, e.SUCCESS, nil)
  996. }
  997. //人脸识别/格润富德接口
  998. func GetRJSBData(c *gin.Context) {
  999. appG := app.Gin{C: c}
  1000. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1001. fsion := gofasion.NewFasion(string(dataByte))
  1002. sqlnamestr := fsion.Get("name").ValueStr()
  1003. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1004. offset := fsion.Get("offset").ValueDefaultInt(0)
  1005. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1006. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1007. month := fsion.Get("month").ValueDefaultStr("map")
  1008. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1009. pagecount = 1
  1010. tx := restful.Engine.NewSession()
  1011. err := tx.Begin()
  1012. defer func() {
  1013. switch {
  1014. case err != nil:
  1015. if tx != nil {
  1016. tx.Rollback()
  1017. }
  1018. default:
  1019. if tx != nil {
  1020. err = tx.Commit()
  1021. }
  1022. }
  1023. if tx != nil {
  1024. tx.Close()
  1025. }
  1026. }()
  1027. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1028. _, 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 )
  1029. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1030. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1031. and lpplantype in(0,1)) `).Execute()
  1032. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1033. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1034. if sql != "" {
  1035. s_params := make([]interface{}, 0)
  1036. if fsion.HasKey("parammaps") {
  1037. parammaps := fsion.Get("parammaps")
  1038. paramslist := strings.Split(p, ",")
  1039. if len(paramslist) > 0 && p != "" {
  1040. for _, value := range paramslist {
  1041. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1042. if tempv, exists := c.Get("jwt_username"); exists {
  1043. s_params = append(s_params, tempv.(string))
  1044. } else {
  1045. s_params = append(s_params, "")
  1046. }
  1047. } else {
  1048. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1049. }
  1050. }
  1051. }
  1052. }
  1053. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1054. if err != nil {
  1055. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1056. } else {
  1057. paramslist1 := strings.Split(p1, ",")
  1058. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1059. s_params1 := make([]interface{}, 0)
  1060. if len(paramslist1) > 0 && p1 != "" {
  1061. for _, v := range paramslist1 {
  1062. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1063. }
  1064. }
  1065. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1066. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1067. }
  1068. var wg sync.WaitGroup
  1069. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1070. wg.Add(1)
  1071. go func(value map[string]interface{}) {
  1072. defer wg.Done()
  1073. // ,havebutton = 1
  1074. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1075. }(value)
  1076. }
  1077. wg.Wait()
  1078. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1079. }
  1080. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1081. } else {
  1082. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1083. }
  1084. }
  1085. func PostRJSBData(c *gin.Context) {
  1086. appG := app.Gin{C: c}
  1087. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1088. fsion := gofasion.NewFasion(string(dataByte))
  1089. logging.Info("PostRJSBData err: ", string(dataByte))
  1090. s_params := make([]interface{}, 0)
  1091. tx := restful.Engine.NewSession()
  1092. err := tx.Begin()
  1093. defer func() {
  1094. switch {
  1095. case err != nil:
  1096. if tx != nil {
  1097. tx.Rollback()
  1098. }
  1099. default:
  1100. if tx != nil {
  1101. err = tx.Commit()
  1102. }
  1103. }
  1104. if tx != nil {
  1105. tx.Close()
  1106. }
  1107. }()
  1108. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1109. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1110. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1111. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1112. if !fsion.HasKey("parammaps") {
  1113. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1114. return
  1115. }
  1116. parammaps := fsion.Get("parammaps")
  1117. paramslist := strings.Split(p, ",")
  1118. if len(paramslist) > 0 && p != "" {
  1119. for _, value := range paramslist {
  1120. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1121. }
  1122. }
  1123. projuctid := parammaps.Get("projuctid").ValueStr()
  1124. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1125. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1126. and lpplantype in(0,1)) where id = (select tmrid 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)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1129. if err != nil {
  1130. logging.Error("PostRJSBData-0 err: ", err)
  1131. msg := geterrmsg(err.Error())
  1132. // appG.Response(http.StatusOK, e.ERROR, msg)
  1133. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1134. return
  1135. }
  1136. _, err = tx.SQL(sql, s_params...).Execute()
  1137. if err != nil {
  1138. logging.Error("PostRJSBData err: ", err)
  1139. msg := geterrmsg(err.Error())
  1140. // appG.Response(http.StatusOK, e.ERROR, msg)
  1141. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1142. return
  1143. }
  1144. s_params = make([]interface{}, 0)
  1145. paramslist = strings.Split(p1, ",")
  1146. if len(paramslist) > 0 && p1 != "" {
  1147. for _, value := range paramslist {
  1148. // if value == "ID" {
  1149. // id := parammaps.Get("ID").ValueStr()
  1150. // pastureid := parammaps.Get("pastureid").ValueStr()
  1151. // 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
  1152. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1153. // if err != nil {
  1154. // logging.Error("PostRJSBData err: ", err)
  1155. // msg := geterrmsg(err.Error())
  1156. // appG.Response(http.StatusOK, e.ERROR, msg)
  1157. // return
  1158. // }
  1159. // for _, item := range datalist {
  1160. // id = item["id"]
  1161. // }
  1162. // s_params = append(s_params, id)
  1163. // } else {
  1164. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1165. // }
  1166. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1167. }
  1168. }
  1169. _, err = tx.SQL(sql1, s_params...).Execute()
  1170. if err != nil {
  1171. logging.Error("PostRJSBData1 err: ", err)
  1172. msg := geterrmsg(err.Error())
  1173. appG.Response(http.StatusOK, e.ERROR, msg)
  1174. return
  1175. }
  1176. s_params = make([]interface{}, 0)
  1177. paramslist = strings.Split(p2, ",")
  1178. if len(paramslist) > 0 && p2 != "" {
  1179. for _, value := range paramslist {
  1180. if value == "ID" {
  1181. id := parammaps.Get("ID").ValueStr()
  1182. pastureid := parammaps.Get("pastureid").ValueStr()
  1183. 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
  1184. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1185. if err != nil {
  1186. logging.Error("PostRJSBData err: ", err)
  1187. msg := geterrmsg(err.Error())
  1188. appG.Response(http.StatusOK, e.ERROR, msg)
  1189. return
  1190. }
  1191. for _, item := range datalist {
  1192. id = item["id"]
  1193. }
  1194. s_params = append(s_params, id)
  1195. } else {
  1196. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1197. }
  1198. }
  1199. }
  1200. _, err = tx.SQL(sql2, s_params...).Execute()
  1201. if err != nil {
  1202. logging.Error("PostRJSBData2 err: ", err)
  1203. msg := geterrmsg(err.Error())
  1204. appG.Response(http.StatusOK, e.ERROR, msg)
  1205. return
  1206. }
  1207. s_params = make([]interface{}, 0)
  1208. paramslist = strings.Split(p3, ",")
  1209. if len(paramslist) > 0 && p3 != "" {
  1210. for _, value := range paramslist {
  1211. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1212. }
  1213. }
  1214. _, err = tx.SQL(sql3, s_params...).Execute()
  1215. if err != nil {
  1216. logging.Error("PostRJSBData3 err: ", err)
  1217. msg := geterrmsg(err.Error())
  1218. appG.Response(http.StatusOK, e.ERROR, msg)
  1219. return
  1220. }
  1221. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1222. }
  1223. func PostRJSBDatas(c *gin.Context) {
  1224. appG := app.Gin{C: c}
  1225. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1226. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1227. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1228. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1229. tx := restful.Engine.NewSession()
  1230. err := tx.Begin()
  1231. defer func() {
  1232. switch {
  1233. case err != nil:
  1234. if tx != nil {
  1235. tx.Rollback()
  1236. }
  1237. default:
  1238. if tx != nil {
  1239. err = tx.Commit()
  1240. }
  1241. }
  1242. if tx != nil {
  1243. tx.Close()
  1244. }
  1245. }()
  1246. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1247. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1248. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1249. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1250. for _, fsion := range fsions {
  1251. if !fsion.HasKey("parammaps") {
  1252. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1253. return
  1254. }
  1255. parammaps := fsion.Get("parammaps")
  1256. ID := parammaps.Get("ID").ValueStr()
  1257. if ID == "" {
  1258. continue
  1259. }
  1260. s_params := make([]interface{}, 0)
  1261. paramslist := strings.Split(p, ",")
  1262. if len(paramslist) > 0 && p != "" {
  1263. for _, value := range paramslist {
  1264. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1265. }
  1266. }
  1267. _, err := tx.SQL(sql, s_params...).Execute()
  1268. if err != nil {
  1269. logging.Error("PostRJSBData err: ", err)
  1270. msg := geterrmsg(err.Error())
  1271. // appG.Response(http.StatusOK, e.ERROR, msg)
  1272. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1273. return
  1274. }
  1275. s_params = make([]interface{}, 0)
  1276. paramslist = strings.Split(p1, ",")
  1277. if len(paramslist) > 0 && p1 != "" {
  1278. for _, value := range paramslist {
  1279. // if value == "ID" {
  1280. // id := parammaps.Get("ID").ValueStr()
  1281. // pastureid := parammaps.Get("pastureid").ValueStr()
  1282. // 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
  1283. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1284. // if err != nil {
  1285. // logging.Error("PostRJSBData err: ", err)
  1286. // msg := geterrmsg(err.Error())
  1287. // appG.Response(http.StatusOK, e.ERROR, msg)
  1288. // return
  1289. // }
  1290. // for _, item := range datalist {
  1291. // id = item["id"]
  1292. // }
  1293. // s_params = append(s_params, id)
  1294. // } else {
  1295. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1296. // }
  1297. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1298. }
  1299. }
  1300. _, err = tx.SQL(sql1, s_params...).Execute()
  1301. if err != nil {
  1302. logging.Error("PostRJSBData1 err: ", err)
  1303. msg := geterrmsg(err.Error())
  1304. appG.Response(http.StatusOK, e.ERROR, msg)
  1305. return
  1306. }
  1307. s_params = make([]interface{}, 0)
  1308. paramslist = strings.Split(p2, ",")
  1309. if len(paramslist) > 0 && p2 != "" {
  1310. for _, value := range paramslist {
  1311. if value == "ID" {
  1312. id := parammaps.Get("ID").ValueStr()
  1313. pastureid := parammaps.Get("pastureid").ValueStr()
  1314. 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
  1315. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1316. if err != nil {
  1317. logging.Error("PostRJSBData err: ", err)
  1318. msg := geterrmsg(err.Error())
  1319. appG.Response(http.StatusOK, e.ERROR, msg)
  1320. return
  1321. }
  1322. for _, item := range datalist {
  1323. id = item["id"]
  1324. }
  1325. s_params = append(s_params, id)
  1326. } else {
  1327. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1328. }
  1329. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1330. }
  1331. }
  1332. _, err = tx.SQL(sql2, s_params...).Execute()
  1333. if err != nil {
  1334. logging.Error("PostRJSBData2 err: ", err)
  1335. msg := geterrmsg(err.Error())
  1336. appG.Response(http.StatusOK, e.ERROR, msg)
  1337. return
  1338. }
  1339. s_params = make([]interface{}, 0)
  1340. paramslist = strings.Split(p3, ",")
  1341. if len(paramslist) > 0 && p3 != "" {
  1342. for _, value := range paramslist {
  1343. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1344. }
  1345. }
  1346. _, err = tx.SQL(sql3, s_params...).Execute()
  1347. if err != nil {
  1348. logging.Error("PostRJSBData3 err: ", err)
  1349. msg := geterrmsg(err.Error())
  1350. appG.Response(http.StatusOK, e.ERROR, msg)
  1351. return
  1352. }
  1353. // ALTER TABLE `tmr`
  1354. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1355. projuctid := parammaps.Get("projuctid").ValueStr()
  1356. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1357. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1358. and lpplantype in(0,1)) where id = (select tmrid 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)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1361. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1362. if err != nil {
  1363. logging.Error("PostRJSBData-0 err: ", err)
  1364. msg := geterrmsg(err.Error())
  1365. // appG.Response(http.StatusOK, e.ERROR, msg)
  1366. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1367. return
  1368. }
  1369. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1370. if count == 0 {
  1371. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1372. }
  1373. }
  1374. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1375. }
  1376. // @Summary 根据APISQL表中SQL执行得到数据集
  1377. // @Tags ExecDataByConfig
  1378. // @Accept json
  1379. // @Produce json
  1380. // @Param sqlname query string true "sqlname"
  1381. // @Param offset query int true "offset"
  1382. // @Param pagecount query int true "pagecount"
  1383. // @Param returntype query string true "returntype"
  1384. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1385. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1386. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1387. // @Router /data/PostDataByName [POST]
  1388. func ExecDataByConfig(c *gin.Context) {
  1389. appG := app.Gin{C: c}
  1390. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1391. tempval_ := make(map[string]interface{})
  1392. tempCommon := make(map[string]interface{})
  1393. tempval := make([]map[string]interface{}, 0)
  1394. err := json.Unmarshal(dataByte, &tempval_)
  1395. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1396. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1397. if err != nil {
  1398. } else {
  1399. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1400. tempCommon = v
  1401. }
  1402. if v, ok := tempval_["data"].([]interface{}); ok {
  1403. for _, Tvalue := range v {
  1404. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1405. tempval = append(tempval, v1)
  1406. }
  1407. }
  1408. }
  1409. tx := restful.Engine.NewSession()
  1410. err := tx.Begin()
  1411. if err != nil {
  1412. logging.Error("tx.Begin 事务启动失败__error:", err)
  1413. }
  1414. defer func() {
  1415. switch {
  1416. case err != nil:
  1417. if tx != nil {
  1418. tx.Rollback()
  1419. }
  1420. default:
  1421. if tx != nil {
  1422. err = tx.Commit()
  1423. }
  1424. }
  1425. if tx != nil {
  1426. tx.Close()
  1427. }
  1428. }()
  1429. if err == nil {
  1430. if tempv, exists := c.Get("jwt_username"); exists {
  1431. tempCommon["jwt_username"] = tempv.(string)
  1432. }
  1433. for _, paramvalue := range tempval {
  1434. fmt.Println(paramvalue["name"])
  1435. if paramvalue["name"].(string) == "updateBigFP" {
  1436. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1437. if err != nil {
  1438. msg := geterrmsg(err.Error())
  1439. appG.Response(http.StatusOK, e.ERROR, msg)
  1440. return
  1441. }
  1442. }
  1443. }
  1444. for _, paramvalue := range tempval {
  1445. if _, ok := paramvalue["resultname"]; !ok {
  1446. paramvalue["resultname"] = paramvalue["name"]
  1447. }
  1448. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1449. if err != nil {
  1450. logging.Error("ExecDataParam error:", err)
  1451. break
  1452. }
  1453. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1454. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1455. // }
  1456. }
  1457. if err == nil {
  1458. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1459. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1460. } else {
  1461. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1462. }
  1463. } else {
  1464. msg := geterrmsg(err.Error())
  1465. appG.Response(http.StatusOK, e.ERROR, msg)
  1466. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1467. }
  1468. }
  1469. }
  1470. if err != nil {
  1471. msg := geterrmsg(err.Error())
  1472. appG.Response(http.StatusOK, e.ERROR, msg)
  1473. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1474. }
  1475. }
  1476. func interfacetostring(val interface{}) string {
  1477. switch val.(type) {
  1478. case string:
  1479. ss := val.(string)
  1480. return ss
  1481. break
  1482. case int:
  1483. ss := val.(int)
  1484. return strconv.Itoa(ss)
  1485. break
  1486. case int64:
  1487. ss := val.(int64)
  1488. return strconv.FormatInt(ss, 10)
  1489. break
  1490. case float64:
  1491. ss := val.(float64)
  1492. return strconv.FormatFloat(ss, 'E', -1, 32)
  1493. break
  1494. }
  1495. return ""
  1496. }
  1497. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1498. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1499. tempstrb := strings.IndexAny(valuestring, "@")
  1500. tempstre := strings.IndexAny(valuestring, ".")
  1501. if tempstrb > -1 && tempstre > -1 {
  1502. for _, ParamMapList := range ParamMap {
  1503. if v, ok := ParamMapList["resultname"]; ok {
  1504. if v == valuestring[tempstrb+1:tempstre] {
  1505. if v1, ok := ParamMapList["resultmaps"]; ok {
  1506. if newA, ok := v1.([]map[string]interface{}); ok {
  1507. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1508. } else if newA, ok := v1.(map[string]interface{}); ok {
  1509. return interfacetostring(newA[valuestring[tempstre+1:]])
  1510. }
  1511. }
  1512. }
  1513. }
  1514. }
  1515. } else {
  1516. return valuestring
  1517. }
  1518. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1519. return fmt.Sprintf("%f", valuestring)
  1520. }
  1521. return ""
  1522. }
  1523. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1524. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1525. tempstrb := strings.IndexAny(valuestring, "@")
  1526. tempstre := strings.IndexAny(valuestring, ".")
  1527. if tempstrb > -1 && tempstre > -1 {
  1528. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1529. if s, ok := v.(string); ok {
  1530. return s
  1531. } else if s, ok := v.(float64); ok {
  1532. return strconv.FormatFloat(s, 'f', -1, 64)
  1533. // return strconv.FormatInt(int64(s), 10)
  1534. }
  1535. }
  1536. }
  1537. }
  1538. return ""
  1539. }
  1540. 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) {
  1541. sqlname := fasion["name"].(string)
  1542. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1543. if v, ok := fasion["type"]; ok {
  1544. sqltype = v.(string)
  1545. }
  1546. sql := ""
  1547. p := ""
  1548. s_params := make([]interface{}, 0)
  1549. if sqltype != "" {
  1550. sql, p = restful.GetSqlByName(sqlname, tx)
  1551. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1552. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1553. paramslist := strings.Split(p, ",")
  1554. if len(paramslist) > 0 && p != "" {
  1555. for _, value := range paramslist {
  1556. ss := ""
  1557. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1558. ids, err := setting.SnowIds.NextId()
  1559. if err != nil {
  1560. ids = time.Now().UnixNano()
  1561. logging.Info("create SnowIds err", err)
  1562. }
  1563. s_params = append(s_params, ids)
  1564. } else {
  1565. if ss == "" && CommonParamMap != nil {
  1566. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1567. ss = valuestring
  1568. tempstrb := strings.IndexAny(valuestring, "@")
  1569. tempstre := strings.IndexAny(valuestring, ".")
  1570. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1571. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1572. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1573. }
  1574. } else {
  1575. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1576. ss = ""
  1577. }
  1578. }
  1579. }
  1580. }
  1581. if ss == "" && ParentParamMap != nil {
  1582. ss = getParamValue_(v, value, ParentParamMap)
  1583. }
  1584. if ss == "" && sameParamMap != nil {
  1585. ss = getParamValue(v, value, sameParamMap)
  1586. }
  1587. if ss == "" && ParamMap != nil {
  1588. ss = getParamValue(v, value, ParamMap)
  1589. }
  1590. s_params = append(s_params, ss)
  1591. }
  1592. }
  1593. }
  1594. }
  1595. }
  1596. if sql == "" {
  1597. sqltype = ""
  1598. }
  1599. if sqltype == "s1" {
  1600. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1601. if v, ok := tempValParam.(map[string]interface{}); ok {
  1602. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1603. }
  1604. if err != nil {
  1605. return nil, err
  1606. }
  1607. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1608. if err != nil {
  1609. return nil, err
  1610. }
  1611. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1612. } else if sqltype == "sm" {
  1613. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1614. if v, ok := tempValParam.(map[string]interface{}); ok {
  1615. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1616. } else {
  1617. }
  1618. if err != nil {
  1619. return nil, err
  1620. }
  1621. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1622. if err != nil {
  1623. return nil, err
  1624. }
  1625. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1626. } else if sqltype == "v" {
  1627. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1628. if v, ok := tempValParam.(map[string]interface{}); ok {
  1629. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1630. } else {
  1631. }
  1632. if err != nil {
  1633. return nil, err
  1634. }
  1635. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1636. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1637. }
  1638. } else if sqltype == "e" {
  1639. tempVal_arrary := make([]map[string]interface{}, 0)
  1640. tempVal_map := make(map[string]interface{})
  1641. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1642. if err == nil {
  1643. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1644. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1645. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1646. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1647. return tempVal_arrary, err
  1648. }
  1649. return nil, err
  1650. } else {
  1651. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1652. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1653. if err != nil {
  1654. return nil, err
  1655. }
  1656. return nil, err
  1657. }
  1658. }
  1659. return nil, nil
  1660. }
  1661. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1662. var err error
  1663. subarray, ok := fasion["children"]
  1664. if ok {
  1665. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1666. tempVal_arrary := make([]map[string]interface{}, 0)
  1667. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1668. tempVal_ := make(map[string]interface{})
  1669. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1670. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1671. } else {
  1672. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1673. }
  1674. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1675. if err != nil {
  1676. return err
  1677. }
  1678. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1679. }
  1680. v.(map[string]interface{})["children"] = tempVal_arrary
  1681. }
  1682. }
  1683. return nil
  1684. }
  1685. // @Summary 删除图片
  1686. // @Tags RemovePicByName
  1687. // @Accept json
  1688. // @Produce json
  1689. // @Param sqlname query string true "sqlname"
  1690. // @Param offset query int true "offset"
  1691. // @Param pagecount query int true "pagecount"
  1692. // @Param returntype query string true "returntype"
  1693. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1694. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1695. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1696. // @Router /data/PostDataByName [POST]
  1697. func RemovePicByName(c *gin.Context) {
  1698. logging.Info("RemovePicByName ", c.Keys)
  1699. appG := app.Gin{C: c}
  1700. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1701. fsion := gofasion.NewFasion(string(dataByte))
  1702. sqlnamestr := fsion.Get("name").ValueStr()
  1703. picname := fsion.Get("picname").ValueStr()
  1704. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1705. params := fsion.Get("params").Array()
  1706. s_params := make([]interface{}, 0)
  1707. for _, v_params := range params {
  1708. s_params = append(s_params, v_params.ValueStr())
  1709. }
  1710. if sql != "" {
  1711. queryData, err := execDataBySql(sql, s_params)
  1712. if picname != "" {
  1713. // Destination
  1714. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1715. err := os.Remove(distPath) //删除文件test.txt
  1716. if err != nil {
  1717. //如果删除失败则输出 file remove Error!
  1718. fmt.Println("file remove Error!")
  1719. //输出错误详细信息
  1720. fmt.Printf("%s", err)
  1721. } else {
  1722. //如果删除成功则输出 file remove OK!
  1723. fmt.Print("file remove OK!")
  1724. }
  1725. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1726. err = os.Remove(distPath) //删除文件test.txt
  1727. if err != nil {
  1728. //如果删除失败则输出 file remove Error!
  1729. fmt.Println("file remove Error!")
  1730. //输出错误详细信息
  1731. fmt.Printf("%s", err)
  1732. } else {
  1733. //如果删除成功则输出 file remove OK!
  1734. fmt.Print("file remove OK!")
  1735. }
  1736. }
  1737. if err != nil {
  1738. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1739. } else {
  1740. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1741. }
  1742. } else {
  1743. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1744. }
  1745. }
  1746. // @Summary 删除文件
  1747. // @Tags RemoveFileByName
  1748. // @Accept json
  1749. // @Produce json
  1750. // @Param sqlname query string true "sqlname"
  1751. // @Param offset query int true "offset"
  1752. // @Param pagecount query int true "pagecount"
  1753. // @Param returntype query string true "returntype"
  1754. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1755. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1756. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1757. // @Router /data/PostDataByName [POST]
  1758. func RemoveFileByName(c *gin.Context) {
  1759. appG := app.Gin{C: c}
  1760. id := c.Param("id")
  1761. logging.Info("DownloadFile ", c.Keys, id)
  1762. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1763. if eqdoc == nil {
  1764. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1765. return
  1766. }
  1767. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1768. err = os.Remove(distPath) //删除文件test.txt
  1769. if err != nil {
  1770. //如果删除失败则输出 file remove Error!
  1771. fmt.Println("file remove Error!")
  1772. //输出错误详细信息
  1773. fmt.Printf("%s", err)
  1774. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1775. return
  1776. }
  1777. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1778. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1779. }
  1780. // @Summary 根据APISQL表中SQL执行得到数据集
  1781. // @Tags PostDataByName
  1782. // @Accept json
  1783. // @Produce json
  1784. // @Param sqlname query string true "sqlname"
  1785. // @Param offset query int true "offset"
  1786. // @Param pagecount query int true "pagecount"
  1787. // @Param returntype query string true "returntype"
  1788. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1789. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1790. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1791. // @Router /data/PostDataByName [POST]
  1792. func UpdateDataRelation(c *gin.Context) {
  1793. appG := app.Gin{C: c}
  1794. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1795. fsion := gofasion.NewFasion(string(dataByte))
  1796. tablename := fsion.Get("name").ValueStr()
  1797. dataname := fsion.Get("dataname").ValueStr()
  1798. datavalue := fsion.Get("datavalue").ValueStr()
  1799. valuename := fsion.Get("valuename").ValueStr()
  1800. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1801. values := fsion.Get("values").Array()
  1802. tx := restful.Engine.NewSession()
  1803. err := tx.Begin()
  1804. defer func() {
  1805. switch {
  1806. case err != nil:
  1807. if tx != nil {
  1808. tx.Rollback()
  1809. }
  1810. default:
  1811. if tx != nil {
  1812. err = tx.Commit()
  1813. }
  1814. }
  1815. if tx != nil {
  1816. tx.Close()
  1817. }
  1818. }()
  1819. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1820. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1821. d_params := make([]interface{}, 4)
  1822. d_params[0] = datavalue
  1823. s_params := ""
  1824. for _, v_values := range values {
  1825. d_params[1] = v_values.ValueStr()
  1826. if s_params == "" {
  1827. s_params = v_values.ValueStr()
  1828. } else {
  1829. s_params = s_params + "," + v_values.ValueStr()
  1830. }
  1831. d_params[2] = d_params[1]
  1832. d_params[3] = d_params[0]
  1833. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1834. if err != nil {
  1835. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1836. break
  1837. }
  1838. }
  1839. if s_params != "" {
  1840. deleteSqlstr := "delete from " + tablename + " " +
  1841. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1842. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1843. if err != nil {
  1844. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1845. } else if err == nil {
  1846. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1847. }
  1848. } else {
  1849. deleteSqlstr := "delete from " + tablename + " " +
  1850. " where " + dataname + " = " + datavalue
  1851. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1852. if err != nil {
  1853. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1854. } else if err == nil {
  1855. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1856. }
  1857. }
  1858. }
  1859. // @Summary 根据APISQL表中SQL执行得到数据集
  1860. // @Tags PostDatasByName
  1861. // @Accept json
  1862. // @Produce json
  1863. // @Param sqlname query string true "sqlname"
  1864. // @Param offset query int true "offset"
  1865. // @Param pagecount query int true "pagecount"
  1866. // @Param returntype query string true "returntype"
  1867. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1868. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1869. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1870. // @Router /data/PostDatasByName [POST]
  1871. func PostDataByNames(c *gin.Context) {
  1872. appG := app.Gin{C: c}
  1873. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1874. fsion := gofasion.NewFasion(string(dataByte))
  1875. sqlParams := fsion.Get("array").Array()
  1876. queryData := make(map[string]interface{})
  1877. for _, v := range sqlParams {
  1878. fsion2 := gofasion.NewFasion(v.Json())
  1879. ss := fsion2.Get("name")
  1880. aa := fsion2.Get("params")
  1881. fmt.Println(ss, aa)
  1882. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1883. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1884. if sql == "" {
  1885. errorm := make(map[string]interface{})
  1886. errorm["code"] = e.ERROR
  1887. errorm["message"] = "sql没有找到"
  1888. errorm["param"] = ""
  1889. queryData[fsion2.Get("name").ValueStr()] = errorm
  1890. continue
  1891. } else if sql != "" {
  1892. s_params := make([]interface{}, 0)
  1893. if fsion2.HasKey("parammaps") {
  1894. parammaps := fsion2.Get("parammaps")
  1895. paramslist := strings.Split(p, ",")
  1896. if len(paramslist) > 0 && p != "" {
  1897. for _, value := range paramslist {
  1898. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1899. if tempv, exists := c.Get("jwt_username"); exists {
  1900. s_params = append(s_params, tempv.(string))
  1901. } else {
  1902. s_params = append(s_params, "")
  1903. }
  1904. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1905. ids, err := setting.SnowIds.NextId()
  1906. if err != nil {
  1907. ids = time.Now().UnixNano()
  1908. logging.Info("create SnowIds err", err)
  1909. }
  1910. s_params = append(s_params, ids)
  1911. } else {
  1912. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1913. }
  1914. }
  1915. }
  1916. } else if fsion2.HasKey("params") {
  1917. params := fsion2.Get("params").Array()
  1918. //ids,err := setting.SnowIds.NextId()
  1919. //if err !=nil{
  1920. // ids = time.Now().UnixNano()
  1921. // logging.Info("create SnowIds err",err)
  1922. //}
  1923. //s_params = append(s_params, ids)
  1924. for _, v_params := range params {
  1925. s_params = append(s_params, v_params.ValueStr())
  1926. }
  1927. }
  1928. _, err := execDataBySql(sql, s_params)
  1929. if err != nil {
  1930. logging.Error("PostDataByName err: ", err)
  1931. errorm := make(map[string]interface{})
  1932. errorm["code"] = e.ERROR
  1933. errorm["message"] = err.Error()
  1934. errorm["param"] = s_params
  1935. queryData[fsion2.Get("name").ValueStr()] = errorm
  1936. continue
  1937. } else {
  1938. errorm := make(map[string]interface{})
  1939. errorm["code"] = e.SUCCESS
  1940. errorm["message"] = "success"
  1941. queryData[fsion2.Get("name").ValueStr()] = errorm
  1942. continue
  1943. }
  1944. } else {
  1945. errorm := make(map[string]interface{})
  1946. errorm["code"] = e.ERROR
  1947. errorm["message"] = "NO SQL"
  1948. errorm["param"] = ""
  1949. queryData[fsion2.Get("name").ValueStr()] = errorm
  1950. }
  1951. }
  1952. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1953. }
  1954. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1955. if offset > 0 {
  1956. offset = offset - 1
  1957. }
  1958. //if pagecount == 0 {
  1959. // pagecount = setting.AppSetting.PageSize
  1960. //}else if pagecount>setting.AppSetting.PageSize{
  1961. // pagecount = setting.AppSetting.PageSize
  1962. //}
  1963. if returntype == "list" {
  1964. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1965. return queryData, err
  1966. } else if returntype == "listlist" {
  1967. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1968. return queryData, err
  1969. } else {
  1970. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1971. return queryData, err
  1972. }
  1973. }
  1974. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1975. if offset > 0 {
  1976. offset = offset - 1
  1977. }
  1978. //if pagecount == 0 {
  1979. // pagecount = setting.AppSetting.PageSize
  1980. //}else if pagecount>setting.AppSetting.PageSize{
  1981. // pagecount = setting.AppSetting.PageSize
  1982. //}
  1983. if returntype == "list" {
  1984. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1985. return queryData, err
  1986. } else if returntype == "listlist" {
  1987. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1988. return queryData, err
  1989. } else {
  1990. fmt.Println(params)
  1991. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1992. return queryData, err
  1993. }
  1994. }
  1995. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1996. paramslist := strings.Split(Params, ",")
  1997. s_params := make([]interface{}, 0)
  1998. if isList {
  1999. for _, v_params := range thisParams["params"].([]interface{}) {
  2000. s_params = append(s_params, v_params)
  2001. }
  2002. } else {
  2003. paramslist := strings.Split(Params, ",")
  2004. if len(paramslist) > 0 && Params != "" {
  2005. for _, value := range paramslist {
  2006. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2007. }
  2008. }
  2009. }
  2010. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2011. for _, queryData_ := range queryData {
  2012. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2013. if isList {
  2014. if queryData_[idname] != nil {
  2015. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2016. }
  2017. } else {
  2018. if queryData_[idname] != nil {
  2019. thisParams[idname] = queryData_[idname].(interface{})
  2020. }
  2021. if len(paramslist) > 0 && Params != "" {
  2022. s_params = make([]interface{}, 0)
  2023. for _, value := range paramslist {
  2024. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2025. }
  2026. }
  2027. }
  2028. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2029. } else {
  2030. }
  2031. }
  2032. return queryData, err
  2033. }
  2034. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2035. queryData, err := restful.ExecQuery(sqlstr, params)
  2036. return queryData, err
  2037. }
  2038. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2039. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2040. return queryData, err
  2041. }
  2042. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2043. queryData, err := restful.ExecQuery(sqlstr, params)
  2044. return queryData, err
  2045. }
  2046. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2047. // @Tags ImportExcel
  2048. // @Accept json
  2049. // @Produce json
  2050. // @Param file query string true "文件名"
  2051. // @Param name header string true "执行sql的名字"
  2052. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2053. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2054. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2055. // @Router /data/ImportExcel [POST]
  2056. func ImportExcel(c *gin.Context) {
  2057. appG := app.Gin{C: c}
  2058. inputdata := ""
  2059. c.Request.ParseForm()
  2060. params := c.Request.Form
  2061. file, _, err := c.Request.FormFile("file")
  2062. if err != nil {
  2063. appG.Response(http.StatusOK, e.ERROR, err)
  2064. return
  2065. }
  2066. sqlnamestrs := params.Get("name")
  2067. sheetname := params.Get("sheetname")
  2068. pastureid := params.Get("pastureid")
  2069. //importParams := params.Get("importParams")
  2070. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2071. // 必输项参数 (字符串格式 "field1,field2,field3")
  2072. requiredParams := params.Get("requiredParams")
  2073. // 日期参数
  2074. dateParams := params.Get("dateParams")
  2075. // 数字参数
  2076. numParams := params.Get("numParams")
  2077. //将字符串分割开
  2078. dateParamslist := strings.Split(dateParams, ",")
  2079. requiredParamslist := strings.Split(requiredParams, ",")
  2080. numParamslist := strings.Split(numParams, ",")
  2081. queryData := make([]interface{}, 0)
  2082. sqlslist := strings.Split(sqlnamestrs, ",")
  2083. xlsx1, err := excelize.OpenReader(file)
  2084. if err != nil {
  2085. fmt.Println(err)
  2086. return
  2087. }
  2088. ok := 0
  2089. error := 0
  2090. isdone := true
  2091. rows := xlsx1.GetRows(sheetname)
  2092. // 限制10000条,多余的截取掉
  2093. if len(rows) > 10000 {
  2094. rows = rows[:10000]
  2095. }
  2096. for i, row := range rows {
  2097. if i > 0 {
  2098. entry := make(map[string]interface{})
  2099. outentry := make(map[string]interface{})
  2100. for j, colCell := range rows[0] {
  2101. for k, colCell1 := range row {
  2102. if j == k {
  2103. outentry[colCell] = colCell1
  2104. entry[colCell] = colCell1
  2105. }
  2106. }
  2107. }
  2108. inputdata = ""
  2109. a := ""
  2110. fmt.Println(outentry, entry)
  2111. //校验日期格式
  2112. for _, v := range dateParamslist {
  2113. if v == "" {
  2114. continue
  2115. }
  2116. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2117. dtime, err := TransfTime(d.(string))
  2118. if err != nil {
  2119. a = strings.Trim(v, " ")
  2120. break
  2121. }
  2122. outentry[strings.Trim(v, " ")] = dtime
  2123. }
  2124. }
  2125. if a != "" {
  2126. outentry["error_msg"] = a + " 格式错误"
  2127. error++
  2128. queryData = append(queryData, outentry)
  2129. continue
  2130. }
  2131. a = ""
  2132. //校验必填格式
  2133. for _, v := range requiredParamslist {
  2134. if v == "" {
  2135. continue
  2136. }
  2137. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2138. a = strings.Trim(v, " ")
  2139. break
  2140. }
  2141. }
  2142. if a != "" {
  2143. outentry["error_msg"] = a + " 未填或格式错误"
  2144. error++
  2145. queryData = append(queryData, outentry)
  2146. continue
  2147. }
  2148. a = ""
  2149. //校验数字格式
  2150. for _, v := range numParamslist {
  2151. if v == "" {
  2152. continue
  2153. }
  2154. d, ok := outentry[strings.Trim(v, " ")]
  2155. if !ok || d == "" {
  2156. outentry[strings.Trim(v, " ")] = 0
  2157. } else {
  2158. var fl float64
  2159. switch d.(type) {
  2160. case string:
  2161. fl, err = strconv.ParseFloat(d.(string), 64)
  2162. }
  2163. if err != nil || fl < 0 {
  2164. a = strings.Trim(v, " ")
  2165. break
  2166. }
  2167. }
  2168. }
  2169. if a != "" {
  2170. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2171. error++
  2172. queryData = append(queryData, outentry)
  2173. continue
  2174. }
  2175. tx := restful.Engine.NewSession()
  2176. err := tx.Begin()
  2177. for _, sqlnamestr := range sqlslist {
  2178. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2179. paramslist := strings.Split(paramslists, ",")
  2180. if len(paramslist) > 0 {
  2181. s_params := make([]interface{}, 0)
  2182. for _, value := range paramslist {
  2183. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2184. if tempv, exists := c.Get("jwt_username"); exists {
  2185. s_params = append(s_params, tempv.(string))
  2186. } else {
  2187. s_params = append(s_params, "")
  2188. }
  2189. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2190. s_params = append(s_params, pastureid)
  2191. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2192. ids, err := setting.SnowIds.NextId()
  2193. if err != nil {
  2194. ids = time.Now().UnixNano()
  2195. logging.Info("create SnowIds err", err)
  2196. }
  2197. s_params = append(s_params, ids)
  2198. } else {
  2199. if outentry[strings.Trim(value, " ")] == nil {
  2200. s_params = append(s_params, "")
  2201. } else {
  2202. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2203. }
  2204. }
  2205. }
  2206. outentry["input"] = inputdata
  2207. fmt.Println(sql, s_params)
  2208. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2209. if err != nil {
  2210. if tx != nil {
  2211. tx.Rollback()
  2212. }
  2213. if tx != nil {
  2214. tx.Close()
  2215. }
  2216. msg := geterrmsg(err.Error())
  2217. outentry["error_msg"] = msg
  2218. error++
  2219. queryData = append(queryData, outentry)
  2220. isdone = true
  2221. break
  2222. } else {
  2223. if len(returnmsgmap1) > 0 {
  2224. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2225. if tx != nil {
  2226. tx.Rollback()
  2227. }
  2228. if tx != nil {
  2229. tx.Close()
  2230. }
  2231. msg := geterrmsg(va.(string))
  2232. outentry["error_msg"] = msg
  2233. error++
  2234. queryData = append(queryData, outentry)
  2235. isdone = true
  2236. break
  2237. }
  2238. }
  2239. isdone = false
  2240. }
  2241. }
  2242. }
  2243. switch {
  2244. case err != nil:
  2245. if tx != nil {
  2246. tx.Rollback()
  2247. }
  2248. default:
  2249. if tx != nil {
  2250. err = tx.Commit()
  2251. }
  2252. }
  2253. if tx != nil {
  2254. tx.Close()
  2255. }
  2256. }
  2257. if !isdone {
  2258. ok++
  2259. isdone = true
  2260. }
  2261. }
  2262. data := make(map[string]interface{})
  2263. data["result"] = queryData
  2264. data["success"] = ok
  2265. data["err_count"] = error
  2266. appG.Response(http.StatusOK, e.SUCCESS, data)
  2267. }
  2268. func TransfTime(timestr string) (string, error) {
  2269. if timestr == "" {
  2270. return time.Now().Format("2006-01-02"), nil
  2271. }
  2272. days, err := strconv.Atoi(timestr)
  2273. if err != nil {
  2274. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2275. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2276. }
  2277. _, err := time.Parse("2006-01-02", timestr)
  2278. if err != nil {
  2279. t, 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. return "", err
  2284. } else {
  2285. return t.Format("2006-01-02"), nil
  2286. }
  2287. } else {
  2288. return t.Format("2006-01-02"), nil
  2289. }
  2290. } else {
  2291. return timestr, nil
  2292. }
  2293. }
  2294. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2295. times = times.AddDate(0, 0, days)
  2296. return times.Format("2006-01-02"), nil
  2297. }
  2298. func Createchart(c *gin.Context) {
  2299. appG := app.Gin{C: c}
  2300. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2301. fsion := gofasion.NewFasion(string(dataByte))
  2302. chart_name := fsion.Get("chart_name").ValueStr()
  2303. desc := fsion.Get("desc").ValueStr()
  2304. pastureid := fsion.Get("pastureid").ValueStr()
  2305. source_id := fsion.Get("source_id").ValueStr()
  2306. emp := fsion.Get("emp").ValueStr()
  2307. content := fsion.Get("content").Json()
  2308. var mapResult map[string]interface{}
  2309. err1 := json.Unmarshal([]byte(content), &mapResult)
  2310. if err1 != nil {
  2311. fmt.Println("JsonToMapDemo err: ", err1)
  2312. }
  2313. tx := restful.Engine.NewSession()
  2314. err := tx.Begin()
  2315. defer func() {
  2316. switch {
  2317. case err != nil:
  2318. logging.Error("tx.Begin 事务启动失败__error:", err)
  2319. if tx != nil {
  2320. tx.Rollback()
  2321. }
  2322. default:
  2323. if tx != nil {
  2324. err = tx.Commit()
  2325. }
  2326. }
  2327. if tx != nil {
  2328. tx.Close()
  2329. }
  2330. }()
  2331. ids, err := setting.SnowIds.NextId()
  2332. if err != nil {
  2333. ids = time.Now().UnixNano()
  2334. logging.Info("create SnowIds err", err)
  2335. }
  2336. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2337. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2338. if err != nil {
  2339. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2340. } else {
  2341. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2342. }
  2343. }
  2344. func Updatedashboard(c *gin.Context) {
  2345. appG := app.Gin{C: c}
  2346. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2347. fsion := gofasion.NewFasion(string(dataByte))
  2348. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2349. pastureid := fsion.Get("pastureid").ValueStr()
  2350. content := fsion.Get("content").Json()
  2351. var mapResult map[string]interface{}
  2352. err1 := json.Unmarshal([]byte(content), &mapResult)
  2353. if err1 != nil {
  2354. fmt.Println("JsonToMapDemo err: ", err1)
  2355. }
  2356. layout := mapResult["layout"]
  2357. tx := restful.Engine.NewSession()
  2358. err := tx.Begin()
  2359. defer func() {
  2360. switch {
  2361. case err != nil:
  2362. logging.Error("tx.Begin 事务启动失败__error:", err)
  2363. if tx != nil {
  2364. tx.Rollback()
  2365. }
  2366. default:
  2367. if tx != nil {
  2368. err = tx.Commit()
  2369. }
  2370. }
  2371. if tx != nil {
  2372. tx.Close()
  2373. }
  2374. }()
  2375. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2376. if err != nil {
  2377. println("2", err.Error())
  2378. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2379. } else {
  2380. if exec != nil {
  2381. if exec[0]["content"] == nil {
  2382. mapR := make(map[string]interface{})
  2383. mapR["layout"] = layout
  2384. mjson, _ := json.Marshal(mapR)
  2385. mString := string(mjson)
  2386. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2387. if err3 != nil {
  2388. println("3", err3.Error())
  2389. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2390. } else {
  2391. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2392. }
  2393. } else {
  2394. var mapR map[string]interface{}
  2395. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2396. if err1 != nil {
  2397. fmt.Println("JsonToMapDemo err: ", err2)
  2398. }
  2399. mapR["layout"] = layout
  2400. mjson, _ := json.Marshal(mapR)
  2401. mString := string(mjson)
  2402. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2403. if err3 != nil {
  2404. println("3", err3.Error())
  2405. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2406. } else {
  2407. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2408. }
  2409. }
  2410. } else {
  2411. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2412. }
  2413. }
  2414. }
  2415. func ExecSQL(c *gin.Context) {
  2416. appG := app.Gin{C: c}
  2417. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2418. fsion := gofasion.NewFasion(string(dataByte))
  2419. content := fsion.Get("content").Json()
  2420. pastureid := fsion.Get("pastureid").ValueStr()
  2421. var mapResult map[string]interface{}
  2422. err1 := json.Unmarshal([]byte(content), &mapResult)
  2423. if err1 != nil {
  2424. fmt.Println("JsonToMapDemo err: ", err1)
  2425. }
  2426. sqlstr := "select "
  2427. groupstr := " GROUP BY "
  2428. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2429. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2430. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2431. }
  2432. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2433. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2434. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2435. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2436. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2437. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2438. sqlstr = sqlstr + tem + ","
  2439. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2440. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2441. sqlstr = sqlstr + tem + ","
  2442. } else {
  2443. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2444. sqlstr = sqlstr + tem + ","
  2445. }
  2446. }
  2447. if _, ok := mapResult["selectedCalcul2"]; ok {
  2448. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2449. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2450. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2451. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2452. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2453. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2454. sqlstr = sqlstr + tem + ","
  2455. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2456. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2457. sqlstr = sqlstr + tem + ","
  2458. } else {
  2459. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2460. sqlstr = sqlstr + tem + ","
  2461. }
  2462. }
  2463. }
  2464. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2465. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2466. sqlstr = sqlstr + " where pastureid=" + pastureid
  2467. if len(mapResult["filters"].([]interface{})) > 0 {
  2468. sqlstr = sqlstr + " and "
  2469. }
  2470. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2471. for _, value := range mapResult["filters"].([]interface{}) {
  2472. switch value.(map[string]interface{})["filterOperator"].(string) {
  2473. case ">", "=", "<", ">=", "<=", "!=", "like":
  2474. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + value.(map[string]interface{})["filterOperator"].(string) + " " + value.(map[string]interface{})["value"].(map[string]interface{})["value1"].(string) + " AND "
  2475. case "IN":
  2476. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2477. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2478. sqlstr = sqlstr + value1.(string) + ","
  2479. }
  2480. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2481. sqlstr = sqlstr + ")" + " AND "
  2482. case "BETWEEN":
  2483. 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 "
  2484. }
  2485. }
  2486. if len(mapResult["filters"].([]interface{})) > 0 {
  2487. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2488. }
  2489. //
  2490. groupstr = groupstr[0 : len(groupstr)-1]
  2491. sqlstr = sqlstr + groupstr + " "
  2492. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2493. sqlstr = sqlstr + " order by "
  2494. }
  2495. //
  2496. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2497. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2498. sqlstr = sqlstr + value.(string) + " "
  2499. } else {
  2500. sqlstr = sqlstr + value.(string) + ","
  2501. }
  2502. }
  2503. //
  2504. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2505. tx := restful.Engine.NewSession()
  2506. err := tx.Begin()
  2507. defer func() {
  2508. switch {
  2509. case err != nil:
  2510. logging.Error("tx.Begin 事务启动失败__error:", err)
  2511. if tx != nil {
  2512. tx.Rollback()
  2513. }
  2514. default:
  2515. if tx != nil {
  2516. err = tx.Commit()
  2517. }
  2518. }
  2519. if tx != nil {
  2520. tx.Close()
  2521. }
  2522. }()
  2523. exec, err := tx.SQL(sqlstr).Query().List()
  2524. if err != nil {
  2525. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2526. } else {
  2527. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2528. }
  2529. }
  2530. func Dashboards(c *gin.Context) {
  2531. appG := app.Gin{C: c}
  2532. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2533. fsion := gofasion.NewFasion(string(dataByte))
  2534. sqlnamestr := fsion.Get("name").ValueStr()
  2535. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2536. offset := fsion.Get("offset").ValueDefaultInt(0)
  2537. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2538. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2539. month := fsion.Get("month").ValueDefaultStr("map")
  2540. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2541. tx := restful.Engine.NewSession()
  2542. err := tx.Begin()
  2543. defer func() {
  2544. switch {
  2545. case err != nil:
  2546. if tx != nil {
  2547. tx.Rollback()
  2548. }
  2549. default:
  2550. if tx != nil {
  2551. err = tx.Commit()
  2552. }
  2553. }
  2554. if tx != nil {
  2555. tx.Close()
  2556. }
  2557. }()
  2558. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2559. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2560. if sql != "" {
  2561. s_params := make([]interface{}, 0)
  2562. if fsion.HasKey("parammaps") {
  2563. parammaps := fsion.Get("parammaps")
  2564. paramslist := strings.Split(p, ",")
  2565. if len(paramslist) > 0 && p != "" {
  2566. for _, value := range paramslist {
  2567. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2568. if tempv, exists := c.Get("jwt_username"); exists {
  2569. s_params = append(s_params, tempv.(string))
  2570. } else {
  2571. s_params = append(s_params, "")
  2572. }
  2573. } else {
  2574. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2575. }
  2576. }
  2577. }
  2578. }
  2579. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2580. if err != nil {
  2581. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2582. } else {
  2583. //paramslist1 := strings.Split(p1, ",")
  2584. dids := make([]interface{}, 0)
  2585. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2586. var mapResult map[string]interface{}
  2587. dids = append(dids, value["dashboard_id"])
  2588. if value["content"] != nil {
  2589. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2590. if err1 != nil {
  2591. println("JsonToMapDemo1 err: ", err1)
  2592. }
  2593. temap := make(map[string]interface{})
  2594. tem := mapResult["layout"].([]interface{})
  2595. if v, ok := value["chartids"]; ok {
  2596. chartids := strings.Split(v.(string), ",")
  2597. for _, va := range chartids {
  2598. a := false
  2599. for _, v2 := range tem {
  2600. if v2.(map[string]interface{})["id"].(string) == va {
  2601. a = true
  2602. //println("va1======",va)
  2603. }
  2604. }
  2605. if !a {
  2606. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2607. va + "\",\"id\":\"" + va +
  2608. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2609. var mapTem map[string]interface{}
  2610. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2611. if err1 != nil {
  2612. println("JsonToMapDemo err: ", err1)
  2613. }
  2614. tem = append(tem, mapTem)
  2615. }
  2616. }
  2617. temap["layout"] = tem
  2618. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2619. }
  2620. } else {
  2621. temap := make(map[string]interface{})
  2622. tem := make([]interface{}, 0)
  2623. if v, ok := value["chartids"]; ok {
  2624. chartids := strings.Split(v.(string), ",")
  2625. for _, va := range chartids {
  2626. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2627. va + "\",\"id\":\"" + va +
  2628. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2629. var mapTem map[string]interface{}
  2630. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2631. if err1 != nil {
  2632. println("JsonToMapDemo err: ", err1)
  2633. }
  2634. tem = append(tem, mapTem)
  2635. }
  2636. temap["layout"] = tem
  2637. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2638. }
  2639. }
  2640. }
  2641. queryData.(map[string]interface{})["order"] = dids
  2642. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2643. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2644. }
  2645. } else {
  2646. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2647. }
  2648. }
  2649. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2650. fsion := gofasion.NewFasion(parammaps)
  2651. sqlnamestr := fsion.Get("name").ValueStr()
  2652. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2653. offset := fsion.Get("offset").ValueDefaultInt(0)
  2654. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2655. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2656. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2657. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2658. body := []byte("")
  2659. if sql != "" {
  2660. s_params := make([]interface{}, 0)
  2661. if fsion.HasKey("parammaps") {
  2662. parammaps := fsion.Get("parammaps")
  2663. paramslist := strings.Split(p, ",")
  2664. if len(paramslist) > 0 && p != "" {
  2665. for _, value := range paramslist {
  2666. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2667. }
  2668. }
  2669. }
  2670. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2671. if err != nil {
  2672. } else {
  2673. paramslist1 := strings.Split(p1, ",")
  2674. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2675. s_params1 := make([]interface{}, 0)
  2676. if len(paramslist1) > 0 && p1 != "" {
  2677. for _, v := range paramslist1 {
  2678. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2679. }
  2680. }
  2681. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2682. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2683. body, _ = json.Marshal(queryData)
  2684. }
  2685. }
  2686. }
  2687. bs := bytes.NewBuffer(body)
  2688. client := &http.Client{}
  2689. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2690. req, err := http.NewRequest(RequestMethod,
  2691. url,
  2692. bs,
  2693. )
  2694. if err != nil {
  2695. }
  2696. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2697. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2698. if err != nil {
  2699. // handle error
  2700. }
  2701. resp, err := client.Do(req)
  2702. if err != nil {
  2703. return ""
  2704. }
  2705. defer resp.Body.Close()
  2706. result_body, err := ioutil.ReadAll(resp.Body)
  2707. if err != nil {
  2708. return ""
  2709. }
  2710. fmt.Println(string(result_body))
  2711. return ""
  2712. }
  2713. func GetSummary(c *gin.Context) {
  2714. appG := app.Gin{C: c}
  2715. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2716. fsion := gofasion.NewFasion(string(dataByte))
  2717. offset := fsion.Get("offset").ValueDefaultInt(0)
  2718. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2719. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2720. parammaps := fsion.Get("parammaps")
  2721. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2722. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2723. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2724. tx := restful.Engine.NewSession()
  2725. defer tx.Close()
  2726. sqlnamestr := ""
  2727. if genre == "0" {
  2728. if status == "0" {
  2729. sqlnamestr = "getAccuracyJSY"
  2730. } else if status == "1" {
  2731. sqlnamestr = "getAccuracyHFT"
  2732. } else if status == "2" {
  2733. sqlnamestr = "getAccuracyHNS"
  2734. } else if status == "3" {
  2735. sqlnamestr = "getAccuracyHSC"
  2736. } else if status == "4" {
  2737. sqlnamestr = "getAccuracyHCC"
  2738. } else if status == "5" {
  2739. sqlnamestr = "getAccuracyMC"
  2740. } else if status == "6" {
  2741. sqlnamestr = "getAccuracyFeedHL"
  2742. } else if status == "7" {
  2743. sqlnamestr = "getAccuracyRT"
  2744. }
  2745. } else {
  2746. if status == "0" {
  2747. sqlnamestr = "getAccuracySCCJSY"
  2748. } else if status == "1" {
  2749. sqlnamestr = "getAccuracySFT"
  2750. } else if status == "2" {
  2751. sqlnamestr = "getAccuracySNS"
  2752. } else if status == "3" {
  2753. sqlnamestr = "getAccuracySSC"
  2754. } else if status == "4" {
  2755. sqlnamestr = "getAccuracySCC"
  2756. } else if status == "5" {
  2757. sqlnamestr = "getAccuracySLCL"
  2758. } else if status == "7" {
  2759. sqlnamestr = "getAccuracySCCRT"
  2760. }
  2761. }
  2762. if isDate == "1" {
  2763. sqlnamestr += "Date"
  2764. }
  2765. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2766. // fmt.Println(sqlnamestr, sql)
  2767. if sql != "" {
  2768. s_params := make([]interface{}, 0)
  2769. // if fsion.HasKey("parammaps") {
  2770. fmt.Println(s_params, "222", p)
  2771. paramslist := strings.Split(p, ",")
  2772. if len(paramslist) > 0 && p != "" {
  2773. for _, value := range paramslist {
  2774. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2775. if tempv, exists := c.Get("jwt_username"); exists {
  2776. s_params = append(s_params, tempv.(string))
  2777. } else {
  2778. s_params = append(s_params, "")
  2779. }
  2780. } else {
  2781. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2782. }
  2783. }
  2784. }
  2785. if returntype == "xlsx" {
  2786. var xlsxfile *xlsx.File
  2787. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2788. //c.File("c:/dd.xlsx")
  2789. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2790. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2791. c.Header("Content-Transfer-Encoding", "binary")
  2792. _ = xlsxfile.Write(c.Writer)
  2793. } else {
  2794. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2795. if err != nil {
  2796. logging.Error("GetDataByName err: ", err)
  2797. msg := geterrmsg(err.Error())
  2798. appG.Response(http.StatusOK, e.ERROR, msg)
  2799. } else {
  2800. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2801. }
  2802. }
  2803. } else {
  2804. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2805. }
  2806. }
  2807. // type lpplanStruct struct {
  2808. // Id int64 `xorm:"id"`
  2809. // Tmrname string `xorm:"tmrname"`
  2810. // Tmrid int64 `xorm:"tmrid"`
  2811. // Sort int64 `xorm:"sort"`
  2812. // Sel int64 `xorm:"sel"`
  2813. // Times int64 `xorm:"times"`
  2814. // Ftname string `xorm:"ftname"`
  2815. // Ftid int64 `xorm:"ftid"`
  2816. // Maxweight float64 `xorm:"maxweight"`
  2817. // Sumweight float64 `xorm:"sumweight"`
  2818. // Sumcowcount int64 `xorm:"sumcowcount"`
  2819. // Pastureid string `xorm:"pastureid"`
  2820. // Display string `xorm:"display"`
  2821. // Issplit int64 `xorm:"issplit"`
  2822. // BeginTime string `xorm:"begintime"`
  2823. // }
  2824. func UpdateFTdetail(c *gin.Context) {
  2825. appG := app.Gin{C: c}
  2826. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2827. tempval_ := make(map[string]interface{})
  2828. tempCommon := make(map[string]interface{})
  2829. tempval := make([]map[string]interface{}, 0)
  2830. fTChange := make(map[string]interface{}, 0)
  2831. // fpdOldDataList := make([]map[string]interface{}, 0)
  2832. // fpdDataList := make([]map[string]interface{}, 0)
  2833. fsion := gofasion.NewFasion(string(dataByte))
  2834. // parammaps := fsion.Get("parammaps")
  2835. createdate := time.Now().Format("2006-01-02 15:04:05")
  2836. err := json.Unmarshal(dataByte, &tempval_)
  2837. if err != nil {
  2838. appG.Response(http.StatusOK, e.ERROR, false)
  2839. return
  2840. }
  2841. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2842. tx := restful.Engine.NewSession()
  2843. if v, ok := tempval_["data"].([]interface{}); ok {
  2844. for _, Tvalue := range v {
  2845. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2846. if v1["name"] == "updateFPbyFTChange" {
  2847. fTChange = v1
  2848. continue
  2849. }
  2850. tempval = append(tempval, v1)
  2851. }
  2852. }
  2853. }
  2854. parammaps := fTChange["parammaps"].(map[string]interface{})
  2855. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2856. // if err != nil {
  2857. // logs.Error(err)
  2858. // appG.Response(http.StatusOK, e.ERROR, false)
  2859. // return
  2860. // }
  2861. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2862. // if err != nil {
  2863. // logs.Error(err)
  2864. // appG.Response(http.StatusOK, e.ERROR, false)
  2865. // return
  2866. // }
  2867. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2868. // if err != nil {
  2869. // logs.Error(err)
  2870. // appG.Response(http.StatusOK, e.ERROR, false)
  2871. // return
  2872. // }
  2873. err = tx.Begin()
  2874. if err != nil {
  2875. logging.Error("tx.Begin 事务启动失败__error:", err)
  2876. }
  2877. defer func() {
  2878. if err != nil {
  2879. if tx != nil {
  2880. tx.Rollback()
  2881. }
  2882. }
  2883. if tx != nil {
  2884. tx.Close()
  2885. }
  2886. }()
  2887. if err != nil {
  2888. } else {
  2889. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2890. tempCommon = v
  2891. }
  2892. // 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 ,
  2893. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2894. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2895. // UNION
  2896. // 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 ,
  2897. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2898. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2899. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2900. if err == nil {
  2901. if tempv, exists := c.Get("jwt_username"); exists {
  2902. tempCommon["jwt_username"] = tempv.(string)
  2903. }
  2904. for _, paramvalue := range tempval {
  2905. if _, ok := paramvalue["resultname"]; !ok {
  2906. paramvalue["resultname"] = paramvalue["name"]
  2907. }
  2908. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2909. if err != nil {
  2910. logging.Error("ExecDataParam error:", err)
  2911. break
  2912. }
  2913. }
  2914. if err != nil {
  2915. msg := geterrmsg(err.Error())
  2916. appG.Response(http.StatusOK, e.ERROR, msg)
  2917. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2918. }
  2919. }
  2920. }
  2921. tx.Commit()
  2922. // go func() {
  2923. if fTChange != nil {
  2924. parammaps := fTChange["parammaps"].(map[string]interface{})
  2925. if parammaps["type"].(float64) == 1 {
  2926. _, err = tx.SQL(`UPDATE feedp fp
  2927. set
  2928. ccountratio = ccount *(ratio /100 ),
  2929. fp.ftweight= IFNULL(IF(
  2930. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2931. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2932. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2933. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2934. ),0),fp.feedweight = IFNULL(IF(
  2935. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2936. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2937. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2938. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2939. ),0) +ifnull(fp.supplyweight,0)
  2940. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2941. _, err = tx.SQL(`UPDATE fpdetail fpd
  2942. INNER JOIN feedp fp
  2943. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2944. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2945. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2946. } else {
  2947. _, err = tx.SQL(`UPDATE feedp fp
  2948. SET ccountratio = ccount *(ratio /100 ),
  2949. fp.supplyweight= IFNULL(IF(
  2950. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2951. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2952. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2953. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2954. ),0),fp.feedweight = IFNULL(IF(
  2955. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2956. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2957. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2958. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2959. ),0) +ifnull(fp.supplyweight,0)
  2960. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2961. _, err = tx.SQL(`UPDATE fpdetail fpd
  2962. INNER JOIN feedp fp
  2963. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2964. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2965. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2966. }
  2967. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2968. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2969. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2970. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2971. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2972. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2973. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2974. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2975. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2976. // fmt.Println(ftId)
  2977. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2978. // 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 ,
  2979. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2980. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2981. // UNION
  2982. // 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 ,
  2983. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2984. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2985. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2986. // lpplanList := make([]*lpplanStruct, 0)
  2987. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2988. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2989. // (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)
  2990. // if err != nil {
  2991. // logs.Error(err, 1)
  2992. // return
  2993. // }
  2994. // lppidlist := []string{}
  2995. // for _, lpp := range lpplanList {
  2996. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2997. // }
  2998. // if len(lppidlist) <= 0 {
  2999. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3000. // return
  3001. // }
  3002. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3003. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3004. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3005. // if err != nil {
  3006. // // tx.Rollback()
  3007. // logs.Error(err, 2, parammaps["pastureid"])
  3008. // return
  3009. // }
  3010. // for _, lpp := range lpplandtl1AllList {
  3011. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3012. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3013. // if err != nil {
  3014. // logs.Error(err)
  3015. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3016. // return
  3017. // }
  3018. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3019. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3020. // if err != nil {
  3021. // logs.Error(err)
  3022. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3023. // return
  3024. // }
  3025. // }
  3026. // var wg sync.WaitGroup
  3027. // for _, old := range fpdOldDataList {
  3028. // for _, fpd := range fpdDataList {
  3029. // wg.Add(1)
  3030. // go func(old, fpd map[string]interface{}) {
  3031. // updateLppandList := make([]*lpplandtl1, 0)
  3032. // defer wg.Done()
  3033. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3034. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3035. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3036. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3037. // // if weight > oldweight {
  3038. // // return
  3039. // // }
  3040. // var w float64
  3041. // var status int
  3042. // if weight < oldweight {
  3043. // if weight >= 0 {
  3044. // return
  3045. // }
  3046. // w = weight
  3047. // status = 0
  3048. // } else {
  3049. // if oldweight > 0 {
  3050. // return
  3051. // }
  3052. // w = weight
  3053. // status = 1
  3054. // }
  3055. // // fweight = w
  3056. // for _, lpp := range lpplanList {
  3057. // var fweight float64
  3058. // var lweight float64
  3059. // lpplandtl1List := make([]*lpplandtl1, 0)
  3060. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3061. // for _, lppland := range lpplandtl1AllList {
  3062. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3063. // lpplandtl1List = append(lpplandtl1List, lppland)
  3064. // }
  3065. // }
  3066. // if len(lpplandtl1List) == 0 {
  3067. // continue
  3068. // }
  3069. // for _, lppland := range lpplandtl1List {
  3070. // lweight += lppland.Lweight
  3071. // }
  3072. // if status == 0 {
  3073. // if lweight <= 0 {
  3074. // continue
  3075. // }
  3076. // } else {
  3077. // if lpp.Maxweight <= lweight {
  3078. // continue
  3079. // }
  3080. // }
  3081. // for _, lppland := range lpplandtl1List {
  3082. // if fpdid == lppland.Fpdid {
  3083. // if status == 1 {
  3084. // // if w <= lppland.Lweight {
  3085. // if lpp.Maxweight <= lweight {
  3086. // continue
  3087. // }
  3088. // if w+lweight <= lpp.Maxweight {
  3089. // lppland.Lweight += w
  3090. // lweight += w
  3091. // fweight += w
  3092. // w = 0
  3093. // } else {
  3094. // w = w - (lpp.Maxweight - lweight)
  3095. // n := (lpp.Maxweight - lweight)
  3096. // lppland.Lweight = lppland.Lweight + n
  3097. // lweight += n
  3098. // fweight += n
  3099. // }
  3100. // } else {
  3101. // if lppland.Lweight == 0 {
  3102. // continue
  3103. // }
  3104. // if w+lppland.Lweight >= 0 {
  3105. // lppland.Lweight = lppland.Lweight + w
  3106. // lweight = lweight + w
  3107. // fweight = fweight + w
  3108. // w = 0
  3109. // } else {
  3110. // w = w + lppland.Lweight
  3111. // lweight = lweight - lppland.Lweight
  3112. // fweight = fweight - lppland.Lweight
  3113. // lppland.Lweight = 0
  3114. // }
  3115. // }
  3116. // updateLppandList = append(updateLppandList, lppland)
  3117. // break
  3118. // }
  3119. // }
  3120. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3121. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3122. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3123. // if err != nil {
  3124. // // tx.Rollback()
  3125. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3126. // return
  3127. // }
  3128. // for _, lppland := range updateLppandList {
  3129. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3130. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3131. // if err != nil {
  3132. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3133. // // tx.Rollback()
  3134. // logs.Error(err, 3)
  3135. // return
  3136. // }
  3137. // // defer wg.Done()
  3138. // }
  3139. // updateLppandList = []*lpplandtl1{}
  3140. // if w == 0 {
  3141. // break
  3142. // }
  3143. // }
  3144. // }
  3145. // }(old, fpd)
  3146. // }
  3147. // }
  3148. // wg.Wait()
  3149. }
  3150. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3151. if err != nil {
  3152. logs.Error(err)
  3153. appG.Response(http.StatusOK, e.ERROR, false)
  3154. return
  3155. }
  3156. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3157. if err != nil {
  3158. logs.Error(err)
  3159. appG.Response(http.StatusOK, e.ERROR, false)
  3160. return
  3161. }
  3162. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3163. if err != nil {
  3164. logs.Error(err)
  3165. appG.Response(http.StatusOK, e.ERROR, false)
  3166. return
  3167. }
  3168. now := createdate
  3169. // for _, oldFpd := range oldFpdDataList {
  3170. for _, newFpd := range newFpdDataList {
  3171. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3172. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3173. // go func() {
  3174. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3175. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3176. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3177. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3178. if err != nil {
  3179. logs.Error(err)
  3180. appG.Response(http.StatusOK, e.ERROR, false)
  3181. return
  3182. }
  3183. // }()
  3184. }
  3185. // break
  3186. // }
  3187. // }
  3188. // }
  3189. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3190. for _, newLpplandtl1 := range newLpplandtl1List {
  3191. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3192. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3193. // go func() {
  3194. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3195. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3196. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3197. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3198. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3199. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3200. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3201. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3202. if err != nil {
  3203. logs.Error(err)
  3204. appG.Response(http.StatusOK, e.ERROR, false)
  3205. return
  3206. }
  3207. // }()
  3208. // }
  3209. // break
  3210. // }
  3211. // }
  3212. }
  3213. // for _, oldFeedp := range oldFeedpList {
  3214. for _, newFeedp := range newFeedpList {
  3215. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3216. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3217. // go func() {
  3218. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3219. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3220. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3221. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3222. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3223. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3224. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3225. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3226. if err != nil {
  3227. logs.Error(err)
  3228. appG.Response(http.StatusOK, e.ERROR, false)
  3229. return
  3230. }
  3231. }
  3232. // ,,parammaps["ftid"])
  3233. // surplus, surplusId, id, pastureId string
  3234. // FtdetailSurplusFt(parammaps["ftid"].)
  3235. ftList1, err := tx.SQL(` SELECT
  3236. f.id,
  3237. f.surplus surplusId,
  3238. f.pastureid,
  3239. s.surplus
  3240. FROM
  3241. feedtemplet f
  3242. JOIN surplus s ON s.id = f.surplus
  3243. WHERE
  3244. f.id = ?`, parammaps["ftid"]).QueryString()
  3245. for _, ft := range ftList1 {
  3246. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3247. }
  3248. appG.Response(http.StatusOK, e.SUCCESS, true)
  3249. }
  3250. type lpplandtlInfo struct {
  3251. Id int64 `xorm:"id"`
  3252. Pastureid int64 `xorm:"pastureid"`
  3253. Lppid int64 `xorm:"lppid"`
  3254. Barid int64 `xorm:"barid"`
  3255. Barname string `xorm:"barname"`
  3256. Fpdid int64 `xorm:"fpdid"`
  3257. Fttype int64 `xorm:"fttype"`
  3258. Lweight float64 `xorm:"lweight"`
  3259. Sort int64 `xorm:"sort"`
  3260. Tmrid int64 `xorm:"tmrid"`
  3261. Tmrname string `xorm:"tmrname"`
  3262. Cowcount int64 `xorm:"cowcount"`
  3263. Ccountradio float64 `xorm:"ccountradio"`
  3264. Background string `xorm:"background"`
  3265. Lweighthis float64 `xorm:"lweighthis"`
  3266. Maxweight float64 `xorm:"maxweight"`
  3267. }
  3268. func UpdateFpdetailBar(c *gin.Context) {
  3269. appG := app.Gin{C: c}
  3270. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3271. fsion := gofasion.NewFasion(string(dataByte))
  3272. pastureid := fsion.Get("pastureid").ValueStr()
  3273. id := fsion.Get("id").ValueStr()
  3274. tx := restful.Engine.NewSession()
  3275. tx.Begin()
  3276. 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 `,
  3277. pastureid, id).Query().List()
  3278. if err != nil {
  3279. logs.Error(err)
  3280. }
  3281. for _, fpd := range fpdList {
  3282. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3283. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3284. pastureid, fpd["id"]).Query().List()
  3285. if err != nil {
  3286. tx.Rollback()
  3287. logs.Error(err)
  3288. appG.Response(http.StatusOK, e.ERROR, false)
  3289. return
  3290. }
  3291. var lweight float64
  3292. for _, lppland := range lpplandList {
  3293. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3294. lweight += lweight1
  3295. }
  3296. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3297. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3298. if fpdweight >= ptuse && lweight == ptuse {
  3299. continue
  3300. } else {
  3301. if lweight <= fpdweight {
  3302. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3303. if err != nil {
  3304. tx.Rollback()
  3305. logs.Error(err)
  3306. appG.Response(http.StatusOK, e.ERROR, false)
  3307. return
  3308. }
  3309. } else {
  3310. weight := fpdweight - lweight
  3311. for _, lppland := range lpplandList {
  3312. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3313. if weight >= lpplandlweight {
  3314. weight = weight - lpplandlweight
  3315. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3316. if err != nil {
  3317. tx.Rollback()
  3318. logs.Error(err)
  3319. appG.Response(http.StatusOK, e.ERROR, false)
  3320. return
  3321. }
  3322. } else {
  3323. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3324. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3325. // if err != nil {
  3326. // tx.Rollback()
  3327. // logs.Error(err)
  3328. // appG.Response(http.StatusOK, e.ERROR, false)
  3329. // return
  3330. // }
  3331. weight = 0
  3332. break
  3333. }
  3334. }
  3335. }
  3336. }
  3337. }
  3338. fsionData := fsion.Get("data").Array()
  3339. for _, list := range fsionData {
  3340. ftmap := make(map[string]interface{})
  3341. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3342. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3343. ftmap["times"] = list.Get("times").ValueInt64()
  3344. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3345. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3346. // fmt.Println(ftmap)
  3347. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3348. // and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3349. // if count == 1 {
  3350. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 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 = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3352. // if err != nil {
  3353. // tx.Rollback()
  3354. // logs.Error(err)
  3355. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3356. // return
  3357. // }
  3358. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3359. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3360. // if err != nil {
  3361. // tx.Rollback()
  3362. // logs.Error(err)
  3363. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3364. // return
  3365. // }
  3366. // }
  3367. fpdDataList, err := tx.SQL(`
  3368. 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 ,
  3369. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3370. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3371. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3372. if err != nil {
  3373. tx.Rollback()
  3374. logs.Error(err)
  3375. }
  3376. for _, fpd := range fpdDataList {
  3377. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3378. fttype := -1
  3379. if fpd["fttype"].(string) == "1" {
  3380. fttype = 1
  3381. }
  3382. var fweight float64
  3383. var lweight float64
  3384. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3385. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3386. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3387. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3388. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3389. join tmr t on t.id = lpp.tmrid
  3390. where lppland.fpdid =?
  3391. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3392. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3393. if err != nil {
  3394. tx.Rollback()
  3395. logs.Error(err)
  3396. }
  3397. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3398. var w float64
  3399. var status int
  3400. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3401. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3402. if weight >= 0 {
  3403. continue
  3404. }
  3405. w = weight
  3406. status = 0
  3407. } else {
  3408. // continue
  3409. if weight <= 0 {
  3410. continue
  3411. }
  3412. w = weight
  3413. status = 1
  3414. }
  3415. // for _, lppland := range lpplandtl1List {
  3416. // lweight += lppland.Lweight
  3417. // }
  3418. for _, lppland := range lpplandtl1List {
  3419. lpplandInfo := new(lpplandtlInfo)
  3420. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3421. lweight = lpplandInfo.Lweight
  3422. if status == 1 {
  3423. // if w <= lppland.Lweight {
  3424. if lppland.Maxweight <= lweight {
  3425. continue
  3426. }
  3427. if w+lweight <= lppland.Maxweight {
  3428. lppland.Lweight += w
  3429. lweight += w
  3430. fweight += w
  3431. w = 0
  3432. } else {
  3433. w = w - (lppland.Maxweight - lweight)
  3434. n := (lppland.Maxweight - lweight)
  3435. lppland.Lweight = lppland.Lweight + n
  3436. lweight += n
  3437. fweight += n
  3438. }
  3439. } else {
  3440. if lppland.Lweight == 0 {
  3441. continue
  3442. }
  3443. if w+lppland.Lweight >= 0 {
  3444. lppland.Lweight = lppland.Lweight + w
  3445. lweight = lweight + w
  3446. fweight = fweight + w
  3447. w = 0
  3448. } else {
  3449. w = w + lppland.Lweight
  3450. lweight = lweight - lppland.Lweight
  3451. fweight = fweight - lppland.Lweight
  3452. lppland.Lweight = 0
  3453. }
  3454. }
  3455. if lppland.Lweight > 0 {
  3456. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3457. if err != nil {
  3458. tx.Rollback()
  3459. logs.Error(err)
  3460. return
  3461. }
  3462. } else {
  3463. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3464. if err != nil {
  3465. tx.Rollback()
  3466. logs.Error(err)
  3467. return
  3468. }
  3469. }
  3470. if w == 0 {
  3471. break
  3472. }
  3473. // break
  3474. }
  3475. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3476. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3477. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3478. if err != nil {
  3479. tx.Rollback()
  3480. logs.Error(err)
  3481. }
  3482. if w == 0 {
  3483. break
  3484. }
  3485. }
  3486. }
  3487. }
  3488. tx.Commit()
  3489. now := time.Now()
  3490. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3491. if err != nil {
  3492. logs.Error(err)
  3493. appG.Response(http.StatusOK, e.ERROR, false)
  3494. return
  3495. }
  3496. for _, newLpplandtl1 := range newLpplandtl1List {
  3497. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3498. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3499. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3500. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3501. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3502. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3503. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3504. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3505. if err != nil {
  3506. logs.Error(err)
  3507. appG.Response(http.StatusOK, e.ERROR, false)
  3508. return
  3509. }
  3510. }
  3511. appG.Response(http.StatusOK, e.SUCCESS, true)
  3512. }
  3513. func GetProcessAnalysis(c *gin.Context) {
  3514. appG := app.Gin{C: c}
  3515. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3516. fsion := gofasion.NewFasion(string(dataByte))
  3517. sqlnamestr := fsion.Get("name").ValueStr()
  3518. offset := fsion.Get("offset").ValueDefaultInt(0)
  3519. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3520. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3521. parammaps := fsion.Get("parammaps")
  3522. tx := restful.Engine.NewSession()
  3523. err := tx.Begin()
  3524. defer func() {
  3525. switch {
  3526. case err != nil:
  3527. logging.Error("tx.Begin 事务启动失败__error:", err)
  3528. if tx != nil {
  3529. tx.Rollback()
  3530. }
  3531. default:
  3532. if tx != nil {
  3533. err = tx.Commit()
  3534. }
  3535. }
  3536. if tx != nil {
  3537. tx.Close()
  3538. }
  3539. }()
  3540. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3541. s_params := make([]interface{}, 0)
  3542. paramslist := strings.Split(p, ",")
  3543. if len(paramslist) > 0 && p != "" {
  3544. for _, value := range paramslist {
  3545. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3546. if tempv, exists := c.Get("jwt_username"); exists {
  3547. s_params = append(s_params, tempv.(string))
  3548. } else {
  3549. s_params = append(s_params, "")
  3550. }
  3551. } else {
  3552. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3553. }
  3554. }
  3555. }
  3556. tmrtnameStr := ""
  3557. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3558. if len(tmrtnameStr) == 0 {
  3559. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3560. } else {
  3561. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3562. }
  3563. }
  3564. if len(tmrtnameStr) > 0 {
  3565. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3566. }
  3567. sql += " ORDER BY d.intime"
  3568. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3569. if err != nil {
  3570. logging.Error("GetDataByName err: ", err)
  3571. msg := geterrmsg(err.Error())
  3572. appG.Response(http.StatusOK, e.ERROR, msg)
  3573. } else {
  3574. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3575. }
  3576. }
  3577. func UpdateFeedtempletStatus(c *gin.Context) {
  3578. appG := app.Gin{C: c}
  3579. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3580. fsion := gofasion.NewFasion(string(dataByte))
  3581. parammaps := fsion.Get("parammaps")
  3582. tx := restful.Engine.NewSession()
  3583. tx.Begin()
  3584. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3585. if err != nil {
  3586. tx.Rollback()
  3587. logs.Error(err)
  3588. appG.Response(http.StatusOK, e.ERROR, err)
  3589. return
  3590. }
  3591. tx.Commit()
  3592. appG.Response(http.StatusOK, e.SUCCESS, true)
  3593. }
  3594. func AddFtdry(c *gin.Context) {
  3595. appG := app.Gin{C: c}
  3596. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3597. fsion := gofasion.NewFasion(string(dataByte))
  3598. sqlnamestr := fsion.Get("name").ValueStr()
  3599. s_params := make([]interface{}, 0)
  3600. tx := restful.Engine.NewSession()
  3601. err := tx.Begin()
  3602. defer func() {
  3603. switch {
  3604. case err != nil:
  3605. if tx != nil {
  3606. tx.Rollback()
  3607. }
  3608. default:
  3609. if tx != nil {
  3610. err = tx.Commit()
  3611. }
  3612. }
  3613. if tx != nil {
  3614. tx.Close()
  3615. }
  3616. }()
  3617. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3618. if sql != "" {
  3619. parammaps := fsion.Get("parammaps")
  3620. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3621. paramslist := strings.Split(p, ",")
  3622. if len(paramslist) > 0 && p != "" {
  3623. for _, value := range paramslist {
  3624. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3625. if tempv, exists := c.Get("jwt_username"); exists {
  3626. s_params = append(s_params, tempv.(string))
  3627. } else {
  3628. s_params = append(s_params, "")
  3629. }
  3630. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3631. ids, err := setting.SnowIds.NextId()
  3632. if err != nil {
  3633. ids = time.Now().UnixNano()
  3634. logging.Info("create SnowIds err", err)
  3635. }
  3636. s_params = append(s_params, ids)
  3637. } else {
  3638. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3639. }
  3640. }
  3641. }
  3642. var actweight float64
  3643. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3644. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3645. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3646. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3647. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3648. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3649. 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()
  3650. if err != nil {
  3651. logging.Error("AddFtdry err: ", err)
  3652. msg := geterrmsg(err.Error())
  3653. appG.Response(http.StatusOK, e.ERROR, msg)
  3654. }
  3655. if len(actweightList) > 0 {
  3656. for _, item := range actweightList {
  3657. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3658. if err != nil {
  3659. logging.Error("AddFtdry err: ", err)
  3660. msg := geterrmsg(err.Error())
  3661. appG.Response(http.StatusOK, e.ERROR, msg)
  3662. }
  3663. actweight = fl
  3664. }
  3665. } else {
  3666. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3667. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3668. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3669. if err != nil {
  3670. logging.Error("AddFtdry err: ", err)
  3671. msg := geterrmsg(err.Error())
  3672. appG.Response(http.StatusOK, e.ERROR, msg)
  3673. }
  3674. for _, item := range dryList {
  3675. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3676. if err != nil {
  3677. logging.Error("AddFtdry err: ", err)
  3678. msg := geterrmsg(err.Error())
  3679. appG.Response(http.StatusOK, e.ERROR, msg)
  3680. }
  3681. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3682. }
  3683. }
  3684. if sqlnamestr == "insertFtdry" {
  3685. s_params = append(s_params, actweight)
  3686. } else if sqlnamestr == "updateFtdry" {
  3687. sql = fmt.Sprintf(sql, actweight)
  3688. }
  3689. queryData, err := execDataBySqlT(sql, s_params, tx)
  3690. if err != nil {
  3691. logging.Error("AddFtdry err: ", err)
  3692. msg := geterrmsg(err.Error())
  3693. appG.Response(http.StatusOK, e.ERROR, msg)
  3694. } else {
  3695. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3696. }
  3697. } else {
  3698. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3699. }
  3700. }
  3701. func CheckDates(c *gin.Context) {
  3702. tx := restful.Engine.NewSession()
  3703. defer tx.Close()
  3704. appG := app.Gin{C: c}
  3705. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3706. tempval_ := make(map[string]interface{})
  3707. tempCommon := make(map[string]interface{})
  3708. tempval := make([]map[string]interface{}, 0)
  3709. err := json.Unmarshal(dataByte, &tempval_)
  3710. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3711. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3712. if err != nil {
  3713. } else {
  3714. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3715. tempCommon = v
  3716. }
  3717. if v, ok := tempval_["data"].([]interface{}); ok {
  3718. for _, Tvalue := range v {
  3719. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3720. tempval = append(tempval, v1)
  3721. }
  3722. }
  3723. }
  3724. if err == nil {
  3725. if tempv, exists := c.Get("jwt_username"); exists {
  3726. tempCommon["jwt_username"] = tempv.(string)
  3727. }
  3728. for _, paramvalue := range tempval {
  3729. if _, ok := paramvalue["resultname"]; !ok {
  3730. paramvalue["resultname"] = paramvalue["name"]
  3731. }
  3732. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3733. if err != nil {
  3734. logging.Error("ExecDataParam error:", err)
  3735. }
  3736. }
  3737. if err == nil {
  3738. vmsg := ""
  3739. for _, item := range tempval {
  3740. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3741. for _, childrenList := range list.([]interface{}) {
  3742. for k, children := range childrenList.(map[string]interface{}) {
  3743. if k != "children" {
  3744. continue
  3745. }
  3746. for _, v := range children.([]map[string]interface{}) {
  3747. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3748. if k1 == "list" {
  3749. for _, v2 := range v1.([]map[string]interface{}) {
  3750. if v2["vmsg"].(string) != "1" {
  3751. if len(vmsg) == 0 {
  3752. vmsg = v2["vmsg"].(string)
  3753. } else {
  3754. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3755. }
  3756. }
  3757. }
  3758. }
  3759. }
  3760. }
  3761. }
  3762. }
  3763. }
  3764. }
  3765. if len(vmsg) > 0 {
  3766. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3767. } else {
  3768. appG.Response(http.StatusOK, e.SUCCESS, true)
  3769. }
  3770. } else {
  3771. msg := geterrmsg(err.Error())
  3772. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3773. }
  3774. }
  3775. }
  3776. if err != nil {
  3777. msg := geterrmsg(err.Error())
  3778. appG.Response(http.StatusOK, e.ERROR, msg)
  3779. }
  3780. }
  3781. 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) {
  3782. sqlname := fasion["name"].(string)
  3783. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3784. if v, ok := fasion["type"]; ok {
  3785. sqltype = v.(string)
  3786. }
  3787. sql := ""
  3788. p := ""
  3789. s_params := make([]interface{}, 0)
  3790. if sqltype != "" {
  3791. sql, p = restful.GetSqlByName(sqlname, tx)
  3792. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3793. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3794. paramslist := strings.Split(p, ",")
  3795. if len(paramslist) > 0 && p != "" {
  3796. for _, value := range paramslist {
  3797. ss := ""
  3798. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3799. ids, err := setting.SnowIds.NextId()
  3800. if err != nil {
  3801. ids = time.Now().UnixNano()
  3802. logging.Info("create SnowIds err", err)
  3803. }
  3804. s_params = append(s_params, ids)
  3805. } else {
  3806. if ss == "" && CommonParamMap != nil {
  3807. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3808. ss = valuestring
  3809. tempstrb := strings.IndexAny(valuestring, "@")
  3810. tempstre := strings.IndexAny(valuestring, ".")
  3811. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3812. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3813. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3814. }
  3815. } else {
  3816. ss = ""
  3817. }
  3818. }
  3819. }
  3820. if ss == "" && ParentParamMap != nil {
  3821. ss = getParamValue_(v, value, ParentParamMap)
  3822. }
  3823. if ss == "" && sameParamMap != nil {
  3824. ss = getParamValue(v, value, sameParamMap)
  3825. }
  3826. if ss == "" && ParamMap != nil {
  3827. ss = getParamValue(v, value, ParamMap)
  3828. }
  3829. s_params = append(s_params, ss)
  3830. }
  3831. }
  3832. }
  3833. }
  3834. }
  3835. if sql == "" {
  3836. sqltype = ""
  3837. }
  3838. if sql != "" {
  3839. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3840. if err != nil {
  3841. return nil, err
  3842. }
  3843. // fmt.Println(tempValParam)
  3844. return tempValParam.(map[string]interface{}), nil
  3845. } else {
  3846. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3847. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3848. if err != nil {
  3849. return nil, err
  3850. }
  3851. return nil, err
  3852. }
  3853. }
  3854. return nil, nil
  3855. }
  3856. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3857. var err error
  3858. subarray, ok := fasion["children"]
  3859. if ok {
  3860. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3861. tempVal_arrary := make([]map[string]interface{}, 0)
  3862. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3863. tempVal_ := make(map[string]interface{})
  3864. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3865. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3866. } else {
  3867. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3868. }
  3869. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3870. if err != nil {
  3871. return err
  3872. }
  3873. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3874. }
  3875. v.(map[string]interface{})["children"] = tempVal_arrary
  3876. }
  3877. }
  3878. return nil
  3879. }
  3880. func FpdImportExcel(c *gin.Context) {
  3881. appG := app.Gin{C: c}
  3882. inputdata := ""
  3883. c.Request.ParseForm()
  3884. params := c.Request.Form
  3885. file, _, err := c.Request.FormFile("file")
  3886. if err != nil {
  3887. appG.Response(http.StatusOK, e.ERROR, err)
  3888. return
  3889. }
  3890. sqlnamestrs := params.Get("name")
  3891. sheetname := params.Get("sheetname")
  3892. pastureid := params.Get("pastureid")
  3893. // importParams := params.Get("importParams")
  3894. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3895. // 必输项参数 (字符串格式 "field1,field2,field3")
  3896. requiredParams := params.Get("requiredParams")
  3897. // 日期参数
  3898. dateParams := params.Get("dateParams")
  3899. // 数字参数
  3900. numParams := params.Get("numParams")
  3901. //将字符串分割开
  3902. dateParamslist := strings.Split(dateParams, ",")
  3903. requiredParamslist := strings.Split(requiredParams, ",")
  3904. numParamslist := strings.Split(numParams, ",")
  3905. queryData := make([]interface{}, 0)
  3906. sqlslist := strings.Split(sqlnamestrs, ",")
  3907. xlsx1, err := excelize.OpenReader(file)
  3908. if err != nil {
  3909. fmt.Println(err)
  3910. return
  3911. }
  3912. ok := 0
  3913. error := 0
  3914. isdone := true
  3915. tx := restful.Engine.NewSession()
  3916. defer tx.Close()
  3917. languageStatus := GetLanguageStatus()
  3918. if languageStatus == "0" {
  3919. 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
  3920. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3921. if err != nil {
  3922. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3923. return
  3924. }
  3925. rows := xlsx1.GetRows(sheetname)
  3926. // 限制10000条,多余的截取掉
  3927. if len(rows) > 10000 {
  3928. rows = rows[:10000]
  3929. }
  3930. dataList := make(map[string][]*upFpdetail, 0)
  3931. for i, row := range rows {
  3932. if i > 0 {
  3933. entry := make(map[string]interface{})
  3934. outentry := make(map[string]interface{})
  3935. for j, colCell := range rows[0] {
  3936. for k, colCell1 := range row {
  3937. if j == k {
  3938. outentry[colCell] = colCell1
  3939. entry[colCell] = colCell1
  3940. }
  3941. }
  3942. }
  3943. inputdata = ""
  3944. a := ""
  3945. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3946. //校验日期格式
  3947. for _, v := range dateParamslist {
  3948. if v == "" {
  3949. continue
  3950. }
  3951. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3952. dtime, err := TransfTime(d.(string))
  3953. if err != nil {
  3954. a = strings.Trim(v, " ")
  3955. break
  3956. }
  3957. outentry[strings.Trim(v, " ")] = dtime
  3958. }
  3959. }
  3960. if a != "" {
  3961. outentry["error_msg"] = a + " 格式错误"
  3962. error++
  3963. queryData = append(queryData, outentry)
  3964. continue
  3965. }
  3966. a = ""
  3967. //校验必填格式
  3968. for _, v := range requiredParamslist {
  3969. if v == "" {
  3970. continue
  3971. }
  3972. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3973. a = strings.Trim(v, " ")
  3974. break
  3975. }
  3976. }
  3977. if a != "" {
  3978. outentry["error_msg"] = a + " 未填或格式错误"
  3979. error++
  3980. queryData = append(queryData, outentry)
  3981. continue
  3982. }
  3983. a = ""
  3984. //校验数字格式
  3985. for _, v := range numParamslist {
  3986. if v == "" {
  3987. continue
  3988. }
  3989. d, ok := outentry[strings.Trim(v, " ")]
  3990. if !ok || d == "" {
  3991. outentry[strings.Trim(v, " ")] = 0
  3992. } else {
  3993. var fl float64
  3994. switch d.(type) {
  3995. case string:
  3996. fl, err = strconv.ParseFloat(d.(string), 64)
  3997. }
  3998. if err != nil || fl < 0 {
  3999. a = strings.Trim(v, " ")
  4000. break
  4001. }
  4002. }
  4003. }
  4004. if a != "" {
  4005. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4006. error++
  4007. queryData = append(queryData, outentry)
  4008. continue
  4009. }
  4010. errExist := false
  4011. for _, sqlnamestr := range sqlslist {
  4012. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4013. paramslist := strings.Split(paramslists, ",")
  4014. if len(paramslist) > 0 {
  4015. s_params := make([]interface{}, 0)
  4016. for _, value := range paramslist {
  4017. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4018. if tempv, exists := c.Get("jwt_username"); exists {
  4019. s_params = append(s_params, tempv.(string))
  4020. } else {
  4021. s_params = append(s_params, "")
  4022. }
  4023. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4024. s_params = append(s_params, pastureid)
  4025. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4026. ids, err := setting.SnowIds.NextId()
  4027. if err != nil {
  4028. ids = time.Now().UnixNano()
  4029. logging.Info("create SnowIds err", err)
  4030. }
  4031. s_params = append(s_params, ids)
  4032. } else {
  4033. if outentry[strings.Trim(value, " ")] == nil {
  4034. s_params = append(s_params, "")
  4035. } else {
  4036. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4037. }
  4038. }
  4039. }
  4040. outentry["input"] = inputdata
  4041. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4042. if err != nil {
  4043. errExist = true
  4044. // if tx != nil {
  4045. // tx.Rollback()
  4046. // }
  4047. // if tx != nil {
  4048. // tx.Close()
  4049. // }
  4050. msg := geterrmsg(err.Error())
  4051. outentry["error_msg"] = msg
  4052. error++
  4053. queryData = append(queryData, outentry)
  4054. isdone = true
  4055. break
  4056. } else {
  4057. if len(returnmsgmap1) > 0 {
  4058. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4059. // if tx != nil {
  4060. // tx.Rollback()
  4061. // }
  4062. // if tx != nil {
  4063. // tx.Close()
  4064. // }
  4065. msg := geterrmsg(va.(string))
  4066. outentry["error_msg"] = msg
  4067. error++
  4068. queryData = append(queryData, outentry)
  4069. isdone = true
  4070. break
  4071. }
  4072. }
  4073. isdone = false
  4074. }
  4075. }
  4076. }
  4077. fmt.Println(outentry["栏舍名称"])
  4078. if !errExist {
  4079. dataexcel := make(map[string]interface{}, 0)
  4080. if _, ok := outentry["栏舍名称"]; ok {
  4081. dataexcel["barname"] = outentry["栏舍名称"]
  4082. }
  4083. if _, ok := outentry["实际牛头数"]; ok {
  4084. dataexcel["ccount"] = outentry["实际牛头数"]
  4085. }
  4086. if _, ok := outentry["系数(%)"]; ok {
  4087. dataexcel["ratio"] = outentry["系数(%)"]
  4088. }
  4089. if _, ok := outentry["配方模板"]; ok {
  4090. dataexcel["ftname"] = outentry["配方模板"]
  4091. }
  4092. if _, ok := outentry["补料配方"]; ok {
  4093. dataexcel["ptsfname"] = outentry["补料配方"]
  4094. }
  4095. if _, ok := outentry["第一班比例(%)"]; ok {
  4096. dataexcel["1"] = outentry["第一班比例(%)"]
  4097. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4098. dataexcel["1"] = 0
  4099. }
  4100. } else {
  4101. dataexcel["1"] = 0
  4102. }
  4103. if _, ok := outentry["第二班比例(%)"]; ok {
  4104. dataexcel["2"] = outentry["第二班比例(%)"]
  4105. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4106. dataexcel["2"] = 0
  4107. }
  4108. } else {
  4109. dataexcel["2"] = 0
  4110. }
  4111. if _, ok := outentry["第三班比例(%)"]; ok {
  4112. dataexcel["3"] = outentry["第三班比例(%)"]
  4113. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4114. dataexcel["3"] = 0
  4115. }
  4116. } else {
  4117. dataexcel["3"] = 0
  4118. }
  4119. if _, ok := outentry["第四班比例(%)"]; ok {
  4120. dataexcel["4"] = outentry["第四班比例(%)"]
  4121. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4122. dataexcel["4"] = 0
  4123. }
  4124. } else {
  4125. dataexcel["4"] = 0
  4126. }
  4127. if _, ok := outentry["第五班比例(%)"]; ok {
  4128. dataexcel["5"] = outentry["第五班比例(%)"]
  4129. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4130. dataexcel["5"] = 0
  4131. }
  4132. } else {
  4133. dataexcel["5"] = 0
  4134. }
  4135. if _, ok := outentry["第六班比例(%)"]; ok {
  4136. dataexcel["6"] = outentry["第六班比例(%)"]
  4137. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4138. dataexcel["6"] = 0
  4139. }
  4140. } else {
  4141. dataexcel["6"] = 0
  4142. }
  4143. dataWeight := new(models.FpdetailEdit)
  4144. // dataWeightMap := make(map[string]interface{}, 0)
  4145. if _, ok := outentry["第一班重量"]; ok {
  4146. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4147. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4148. }
  4149. if _, ok := outentry["第二班重量"]; ok {
  4150. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4151. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4152. }
  4153. if _, ok := outentry["第三班重量"]; ok {
  4154. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4155. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4156. }
  4157. if _, ok := outentry["第四班重量"]; ok {
  4158. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4159. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4160. }
  4161. if _, ok := outentry["第五班重量"]; ok {
  4162. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4163. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4164. }
  4165. if _, ok := outentry["第六班重量"]; ok {
  4166. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4167. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4168. }
  4169. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4170. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4171. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4172. // fmt.Println(err)
  4173. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4174. dataWeight.Weight1 = 0
  4175. dataWeight.Weight2 = 0
  4176. dataWeight.Weight3 = 0
  4177. dataWeight.Weight4 = 0
  4178. dataWeight.Weight5 = 0
  4179. dataWeight.Weight6 = 0
  4180. }
  4181. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4182. if weight > 0 {
  4183. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4184. if err != nil {
  4185. logs.Error(err)
  4186. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4187. return
  4188. }
  4189. if !existbar {
  4190. continue
  4191. }
  4192. _, 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()
  4193. if err != nil {
  4194. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4195. return
  4196. }
  4197. _, 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()
  4198. if err != nil {
  4199. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4200. return
  4201. }
  4202. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4203. if err != nil {
  4204. logs.Error(err)
  4205. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4206. return
  4207. }
  4208. if !existft {
  4209. continue
  4210. }
  4211. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4212. if err != nil {
  4213. logs.Error(err)
  4214. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4215. return
  4216. }
  4217. if !ftexist {
  4218. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4219. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4220. if err != nil {
  4221. logs.Error(err)
  4222. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4223. return
  4224. }
  4225. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4226. if err != nil {
  4227. logs.Error(err)
  4228. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4229. return
  4230. }
  4231. }
  4232. exist, err := tx.SQL(` select id from feedp 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. if !exist {
  4239. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4240. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4241. if err != nil {
  4242. logs.Error(err)
  4243. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4244. return
  4245. }
  4246. }
  4247. var feedpargs []interface{}
  4248. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4249. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4250. if _, ok := dataexcel["ftname"]; ok {
  4251. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4252. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4253. // upFeedpSql += `,ftweight = ? `
  4254. // feedpargs = append(feedpargs, weight)
  4255. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4256. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4257. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4258. } else {
  4259. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4260. }
  4261. if _, ok := dataexcel["ptsfname"]; ok {
  4262. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4263. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4264. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4265. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4266. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4267. } else {
  4268. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4269. }
  4270. upFeedpSql += " where barname = ? and pastureid = ? "
  4271. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4272. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4273. if err != nil {
  4274. logs.Error(err)
  4275. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4276. return
  4277. }
  4278. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4279. if err != nil {
  4280. logs.Error(err)
  4281. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4282. return
  4283. }
  4284. if !exist1 {
  4285. _, 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) `,
  4286. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4287. if err != nil {
  4288. logs.Error(err)
  4289. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4290. return
  4291. }
  4292. }
  4293. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4294. if err != nil {
  4295. logs.Error(err)
  4296. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4297. return
  4298. }
  4299. if !exist2 {
  4300. _, 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) `,
  4301. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4302. if err != nil {
  4303. logs.Error(err)
  4304. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4305. return
  4306. }
  4307. }
  4308. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4309. if err != nil {
  4310. logs.Error(err)
  4311. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4312. return
  4313. }
  4314. if !exist3 {
  4315. _, 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) `,
  4316. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4317. if err != nil {
  4318. logs.Error(err)
  4319. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4320. return
  4321. }
  4322. }
  4323. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4324. if err != nil {
  4325. logs.Error(err)
  4326. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4327. return
  4328. }
  4329. if !exist4 {
  4330. _, 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) `,
  4331. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4332. if err != nil {
  4333. logs.Error(err)
  4334. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4335. return
  4336. }
  4337. }
  4338. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4339. if err != nil {
  4340. logs.Error(err)
  4341. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4342. return
  4343. }
  4344. if !exist5 {
  4345. _, 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) `,
  4346. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4347. if err != nil {
  4348. logs.Error(err)
  4349. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4350. return
  4351. }
  4352. }
  4353. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4354. if err != nil {
  4355. logs.Error(err)
  4356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4357. return
  4358. }
  4359. if !exist6 {
  4360. _, 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) `,
  4361. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4362. if err != nil {
  4363. logs.Error(err)
  4364. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4365. return
  4366. }
  4367. }
  4368. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4369. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4370. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4371. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4372. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4373. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4374. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4375. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4376. and pastureid = ? and times = ?`
  4377. var fpdargs1 []interface{}
  4378. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4379. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4380. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4381. if err != nil {
  4382. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4383. return
  4384. }
  4385. var fpdargs2 []interface{}
  4386. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4387. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4388. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4389. if err != nil {
  4390. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4391. return
  4392. }
  4393. var fpdargs3 []interface{}
  4394. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4395. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4396. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4397. if err != nil {
  4398. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4399. return
  4400. }
  4401. var fpdargs4 []interface{}
  4402. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4403. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4404. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4405. if err != nil {
  4406. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4407. return
  4408. }
  4409. var fpdargs5 []interface{}
  4410. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4411. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4412. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4413. if err != nil {
  4414. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4415. return
  4416. }
  4417. var fpdargs6 []interface{}
  4418. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4419. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4420. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4421. if err != nil {
  4422. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4423. return
  4424. }
  4425. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4426. 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()
  4427. if err != nil {
  4428. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4429. return
  4430. }
  4431. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4432. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4433. upFpdetailList := make([]*upFpdetail, 0)
  4434. for _, newfpd := range newList {
  4435. for _, oldfpd := range oldFpdList {
  4436. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4437. var oldweight, newweight float64
  4438. if oldfpd["weight"] != nil {
  4439. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4440. }
  4441. if newfpd["weight"] != nil {
  4442. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4443. }
  4444. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4445. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4446. Old: oldweight,
  4447. New: newweight,
  4448. Times: newfpd["times"].(int64),
  4449. Ptid: newfpd["ptid"].(int64),
  4450. Fweight: fweight,
  4451. Id: oldfpd["id"].(int64),
  4452. })
  4453. break
  4454. }
  4455. }
  4456. }
  4457. // fmt.Println(dataexcel["barname"])
  4458. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4459. } else {
  4460. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4461. if err != nil {
  4462. logs.Error(err)
  4463. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4464. return
  4465. }
  4466. if !existbar {
  4467. continue
  4468. }
  4469. _, 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()
  4470. if err != nil {
  4471. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4472. return
  4473. }
  4474. _, 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()
  4475. if err != nil {
  4476. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4477. return
  4478. }
  4479. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4480. if err != nil {
  4481. logs.Error(err)
  4482. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4483. return
  4484. }
  4485. if !existft {
  4486. continue
  4487. }
  4488. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4489. if err != nil {
  4490. logs.Error(err)
  4491. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4492. return
  4493. }
  4494. if !ftexist {
  4495. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4496. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4497. if err != nil {
  4498. logs.Error(err)
  4499. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4500. return
  4501. }
  4502. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4503. if err != nil {
  4504. logs.Error(err)
  4505. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4506. return
  4507. }
  4508. }
  4509. exist, err := tx.SQL(` select id from feedp 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. if !exist {
  4516. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4517. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4518. if err != nil {
  4519. logs.Error(err)
  4520. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4521. return
  4522. }
  4523. }
  4524. var feedpargs []interface{}
  4525. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4526. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4527. if _, ok := dataexcel["ftname"]; ok {
  4528. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4529. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4530. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4531. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4532. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4533. } else {
  4534. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4535. }
  4536. if _, ok := dataexcel["ptsfname"]; ok {
  4537. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4538. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4539. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4540. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4541. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4542. } else {
  4543. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4544. }
  4545. upFeedpSql += " where barname = ? and pastureid = ? "
  4546. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4547. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4548. if err != nil {
  4549. logs.Error(err)
  4550. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4551. return
  4552. }
  4553. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4554. if err != nil {
  4555. logs.Error(err)
  4556. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4557. return
  4558. }
  4559. if !exist1 {
  4560. _, 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) `,
  4561. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4562. if err != nil {
  4563. logs.Error(err)
  4564. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4565. return
  4566. }
  4567. }
  4568. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4569. if err != nil {
  4570. logs.Error(err)
  4571. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4572. return
  4573. }
  4574. if !exist2 {
  4575. _, 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) `,
  4576. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4577. if err != nil {
  4578. logs.Error(err)
  4579. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4580. return
  4581. }
  4582. }
  4583. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4584. if err != nil {
  4585. logs.Error(err)
  4586. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4587. return
  4588. }
  4589. if !exist3 {
  4590. _, 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) `,
  4591. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4592. if err != nil {
  4593. logs.Error(err)
  4594. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4595. return
  4596. }
  4597. }
  4598. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4599. if err != nil {
  4600. logs.Error(err)
  4601. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4602. return
  4603. }
  4604. if !exist4 {
  4605. _, 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) `,
  4606. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4607. if err != nil {
  4608. logs.Error(err)
  4609. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4610. return
  4611. }
  4612. }
  4613. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4614. if err != nil {
  4615. logs.Error(err)
  4616. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4617. return
  4618. }
  4619. if !exist5 {
  4620. _, 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) `,
  4621. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4622. if err != nil {
  4623. logs.Error(err)
  4624. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4625. return
  4626. }
  4627. }
  4628. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4629. if err != nil {
  4630. logs.Error(err)
  4631. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4632. return
  4633. }
  4634. if !exist6 {
  4635. _, 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) `,
  4636. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4637. if err != nil {
  4638. logs.Error(err)
  4639. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4640. return
  4641. }
  4642. }
  4643. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4644. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4645. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4646. and pastureid = ? and times = ?`
  4647. var fpdargs1 []interface{}
  4648. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4649. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4650. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4651. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4652. if err != nil {
  4653. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4654. return
  4655. }
  4656. var fpdargs2 []interface{}
  4657. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4658. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4659. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4660. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4661. if err != nil {
  4662. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4663. return
  4664. }
  4665. var fpdargs3 []interface{}
  4666. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4667. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4668. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4669. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4670. if err != nil {
  4671. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4672. return
  4673. }
  4674. var fpdargs4 []interface{}
  4675. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4676. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4677. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4678. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4679. if err != nil {
  4680. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4681. return
  4682. }
  4683. var fpdargs5 []interface{}
  4684. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4685. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4686. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4687. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4688. if err != nil {
  4689. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4690. return
  4691. }
  4692. var fpdargs6 []interface{}
  4693. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4694. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4695. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4696. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4697. if err != nil {
  4698. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4699. return
  4700. }
  4701. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4702. 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()
  4703. if err != nil {
  4704. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4705. return
  4706. }
  4707. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4708. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4709. upFpdetailList := make([]*upFpdetail, 0)
  4710. for _, newfpd := range newList {
  4711. for _, oldfpd := range oldFpdList {
  4712. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4713. var oldweight, newweight float64
  4714. if oldfpd["weight"] != nil {
  4715. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4716. }
  4717. if newfpd["weight"] != nil {
  4718. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4719. }
  4720. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4721. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4722. Old: oldweight,
  4723. New: newweight,
  4724. Times: newfpd["times"].(int64),
  4725. Ptid: newfpd["ptid"].(int64),
  4726. Fweight: fweight,
  4727. Id: oldfpd["id"].(int64),
  4728. })
  4729. break
  4730. }
  4731. }
  4732. }
  4733. // fmt.Println(dataexcel["barname"])
  4734. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4735. }
  4736. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4737. }
  4738. }
  4739. if !isdone {
  4740. ok++
  4741. isdone = true
  4742. }
  4743. }
  4744. for barname, v := range dataList {
  4745. // for _, v1 := range v {
  4746. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4747. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4748. // if count == 1 {
  4749. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4750. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4751. // if err != nil {
  4752. // logs.Error(err)
  4753. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4754. // return
  4755. // }
  4756. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4757. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4758. // if err != nil {
  4759. // logs.Error(err)
  4760. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4761. // return
  4762. // }
  4763. // }
  4764. // }
  4765. updateFpdetailByBar(pastureid, barname, v)
  4766. }
  4767. } else {
  4768. 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
  4769. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4770. if err != nil {
  4771. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4772. return
  4773. }
  4774. rows := xlsx1.GetRows(sheetname)
  4775. // 限制10000条,多余的截取掉
  4776. if len(rows) > 10000 {
  4777. rows = rows[:10000]
  4778. }
  4779. dataList := make(map[string][]*upFpdetail, 0)
  4780. for i, row := range rows {
  4781. if i > 0 {
  4782. entry := make(map[string]interface{})
  4783. outentry := make(map[string]interface{})
  4784. for j, colCell := range rows[0] {
  4785. for k, colCell1 := range row {
  4786. if j == k {
  4787. outentry[colCell] = colCell1
  4788. entry[colCell] = colCell1
  4789. }
  4790. }
  4791. }
  4792. inputdata = ""
  4793. a := ""
  4794. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4795. //校验日期格式
  4796. for _, v := range dateParamslist {
  4797. if v == "" {
  4798. continue
  4799. }
  4800. if d, ok := outentry[v]; ok {
  4801. dtime, err := TransfTime(d.(string))
  4802. if err != nil {
  4803. a = v
  4804. break
  4805. }
  4806. outentry[v] = dtime
  4807. }
  4808. }
  4809. if a != "" {
  4810. outentry["error_msg"] = a + " format error"
  4811. error++
  4812. queryData = append(queryData, outentry)
  4813. continue
  4814. }
  4815. a = ""
  4816. //校验必填格式
  4817. for _, v := range requiredParamslist {
  4818. if v == "" {
  4819. continue
  4820. }
  4821. if d, ok := outentry[v]; !ok || d == "" {
  4822. a = v
  4823. break
  4824. }
  4825. }
  4826. if a != "" {
  4827. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4828. error++
  4829. queryData = append(queryData, outentry)
  4830. continue
  4831. }
  4832. a = ""
  4833. //校验数字格式
  4834. for _, v := range numParamslist {
  4835. if v == "" {
  4836. continue
  4837. }
  4838. d, ok := outentry[v]
  4839. if !ok || d == "" {
  4840. outentry[v] = 0
  4841. } else {
  4842. var fl float64
  4843. switch d.(type) {
  4844. case string:
  4845. fl, err = strconv.ParseFloat(d.(string), 64)
  4846. }
  4847. if err != nil || fl < 0 {
  4848. a = v
  4849. break
  4850. }
  4851. }
  4852. }
  4853. if a != "" {
  4854. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4855. error++
  4856. queryData = append(queryData, outentry)
  4857. continue
  4858. }
  4859. errExist := false
  4860. for _, sqlnamestr := range sqlslist {
  4861. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4862. paramslist := strings.Split(paramslists, ",")
  4863. if len(paramslist) > 0 {
  4864. s_params := make([]interface{}, 0)
  4865. for _, value := range paramslist {
  4866. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4867. if tempv, exists := c.Get("jwt_username"); exists {
  4868. s_params = append(s_params, tempv.(string))
  4869. } else {
  4870. s_params = append(s_params, "")
  4871. }
  4872. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4873. s_params = append(s_params, pastureid)
  4874. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4875. ids, err := setting.SnowIds.NextId()
  4876. if err != nil {
  4877. ids = time.Now().UnixNano()
  4878. logging.Info("create SnowIds err", err)
  4879. }
  4880. s_params = append(s_params, ids)
  4881. } else {
  4882. if outentry[strings.Trim(value, " ")] == nil {
  4883. s_params = append(s_params, "")
  4884. } else {
  4885. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4886. }
  4887. }
  4888. }
  4889. outentry["input"] = inputdata
  4890. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4891. if err != nil {
  4892. errExist = true
  4893. // if tx != nil {
  4894. // tx.Rollback()
  4895. // }
  4896. // if tx != nil {
  4897. // tx.Close()
  4898. // }
  4899. msg := geterrmsg(err.Error())
  4900. outentry["error_msg"] = msg
  4901. error++
  4902. queryData = append(queryData, outentry)
  4903. isdone = true
  4904. break
  4905. } else {
  4906. if len(returnmsgmap1) > 0 {
  4907. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4908. // if tx != nil {
  4909. // tx.Rollback()
  4910. // }
  4911. // if tx != nil {
  4912. // tx.Close()
  4913. // }
  4914. msg := geterrmsg(va.(string))
  4915. outentry["error_msg"] = msg
  4916. error++
  4917. queryData = append(queryData, outentry)
  4918. isdone = true
  4919. break
  4920. }
  4921. }
  4922. isdone = false
  4923. }
  4924. }
  4925. }
  4926. if !errExist {
  4927. dataexcel := make(map[string]interface{}, 0)
  4928. if _, ok := outentry["Pen Name"]; ok {
  4929. dataexcel["barname"] = outentry["Pen Name"]
  4930. }
  4931. if _, ok := outentry["Actual Cattle Number"]; ok {
  4932. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4933. }
  4934. if _, ok := outentry["Coefficient(%)"]; ok {
  4935. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4936. }
  4937. if _, ok := outentry["Formula Template"]; ok {
  4938. dataexcel["ftname"] = outentry["Formula Template"]
  4939. }
  4940. if _, ok := outentry["Supplement Formula"]; ok {
  4941. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4942. }
  4943. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4944. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4945. }
  4946. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4947. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4948. }
  4949. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4950. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4951. }
  4952. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4953. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4954. }
  4955. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4956. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4957. }
  4958. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4959. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4960. }
  4961. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4962. if err != nil {
  4963. logs.Error(err)
  4964. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4965. return
  4966. }
  4967. if !existbar {
  4968. continue
  4969. }
  4970. _, 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()
  4971. if err != nil {
  4972. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4973. return
  4974. }
  4975. _, 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()
  4976. if err != nil {
  4977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4978. return
  4979. }
  4980. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4981. if err != nil {
  4982. logs.Error(err)
  4983. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4984. return
  4985. }
  4986. if !existft {
  4987. continue
  4988. }
  4989. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4990. if err != nil {
  4991. logs.Error(err)
  4992. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4993. return
  4994. }
  4995. if !ftexist {
  4996. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4997. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4998. if err != nil {
  4999. logs.Error(err)
  5000. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5001. return
  5002. }
  5003. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5004. if err != nil {
  5005. logs.Error(err)
  5006. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5007. return
  5008. }
  5009. }
  5010. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5011. if err != nil {
  5012. logs.Error(err)
  5013. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5014. return
  5015. }
  5016. if !exist {
  5017. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5018. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5019. if err != nil {
  5020. logs.Error(err)
  5021. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5022. return
  5023. }
  5024. }
  5025. var feedpargs []interface{}
  5026. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5027. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5028. if _, ok := dataexcel["ftname"]; ok {
  5029. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5030. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5031. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5032. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5033. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5034. } else {
  5035. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5036. }
  5037. if _, ok := dataexcel["ptsfname"]; ok {
  5038. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5039. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5040. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5041. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5042. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5043. } else {
  5044. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5045. }
  5046. upFeedpSql += " where barname = ? and pastureid = ? "
  5047. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5048. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5049. if err != nil {
  5050. logs.Error(err)
  5051. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5052. return
  5053. }
  5054. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5055. if err != nil {
  5056. logs.Error(err)
  5057. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5058. return
  5059. }
  5060. if !exist1 {
  5061. _, 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) `,
  5062. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5063. if err != nil {
  5064. logs.Error(err)
  5065. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5066. return
  5067. }
  5068. }
  5069. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5070. if err != nil {
  5071. logs.Error(err)
  5072. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5073. return
  5074. }
  5075. if !exist2 {
  5076. _, 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) `,
  5077. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5078. if err != nil {
  5079. logs.Error(err)
  5080. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5081. return
  5082. }
  5083. }
  5084. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5085. if err != nil {
  5086. logs.Error(err)
  5087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5088. return
  5089. }
  5090. if !exist3 {
  5091. _, 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) `,
  5092. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5093. if err != nil {
  5094. logs.Error(err)
  5095. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5096. return
  5097. }
  5098. }
  5099. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5100. if err != nil {
  5101. logs.Error(err)
  5102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5103. return
  5104. }
  5105. if !exist4 {
  5106. _, 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) `,
  5107. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5108. if err != nil {
  5109. logs.Error(err)
  5110. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5111. return
  5112. }
  5113. }
  5114. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5115. if err != nil {
  5116. logs.Error(err)
  5117. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5118. return
  5119. }
  5120. if !exist5 {
  5121. _, 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) `,
  5122. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5123. if err != nil {
  5124. logs.Error(err)
  5125. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5126. return
  5127. }
  5128. }
  5129. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5130. if err != nil {
  5131. logs.Error(err)
  5132. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5133. return
  5134. }
  5135. if !exist6 {
  5136. _, 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) `,
  5137. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5138. if err != nil {
  5139. logs.Error(err)
  5140. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5141. return
  5142. }
  5143. }
  5144. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5145. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5146. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5147. and pastureid = ? and times = ?`
  5148. var fpdargs1 []interface{}
  5149. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5150. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5151. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5152. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5153. if err != nil {
  5154. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5155. return
  5156. }
  5157. var fpdargs2 []interface{}
  5158. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5159. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5160. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5161. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5162. if err != nil {
  5163. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5164. return
  5165. }
  5166. var fpdargs3 []interface{}
  5167. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5168. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5169. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5170. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5171. if err != nil {
  5172. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5173. return
  5174. }
  5175. var fpdargs4 []interface{}
  5176. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5177. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5178. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5179. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5180. if err != nil {
  5181. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5182. return
  5183. }
  5184. var fpdargs5 []interface{}
  5185. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5186. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5187. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5188. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5189. if err != nil {
  5190. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5191. return
  5192. }
  5193. var fpdargs6 []interface{}
  5194. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5195. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5196. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5197. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5198. if err != nil {
  5199. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5200. return
  5201. }
  5202. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5203. 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()
  5204. if err != nil {
  5205. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5206. return
  5207. }
  5208. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5209. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5210. upFpdetailList := make([]*upFpdetail, 0)
  5211. for _, newfpd := range newList {
  5212. for _, oldfpd := range oldFpdList {
  5213. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5214. var oldweight, newweight float64
  5215. if oldfpd["weight"] != nil {
  5216. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5217. }
  5218. if newfpd["weight"] != nil {
  5219. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5220. }
  5221. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5222. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5223. Old: oldweight,
  5224. New: newweight,
  5225. Times: newfpd["times"].(int64),
  5226. Ptid: newfpd["ptid"].(int64),
  5227. Fweight: fweight,
  5228. Id: oldfpd["id"].(int64),
  5229. })
  5230. break
  5231. }
  5232. }
  5233. }
  5234. // fmt.Println(dataexcel["barname"])
  5235. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5236. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5237. }
  5238. }
  5239. if !isdone {
  5240. ok++
  5241. isdone = true
  5242. }
  5243. }
  5244. for barname, v := range dataList {
  5245. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5246. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5247. if err != nil {
  5248. logs.Error(err)
  5249. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5250. return
  5251. }
  5252. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5253. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5254. if err != nil {
  5255. logs.Error(err)
  5256. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5257. return
  5258. }
  5259. updateFpdetailByBar(pastureid, barname, v)
  5260. }
  5261. }
  5262. data := make(map[string]interface{})
  5263. data["result"] = queryData
  5264. data["success"] = ok
  5265. data["err_count"] = error
  5266. appG.Response(http.StatusOK, e.SUCCESS, data)
  5267. }
  5268. type upFpdetail struct {
  5269. Old float64
  5270. New float64
  5271. Times int64
  5272. Ptid int64
  5273. Fweight float64
  5274. Id int64
  5275. // Ptsid string
  5276. }
  5277. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5278. tx := restful.Engine.NewSession()
  5279. defer tx.Close()
  5280. tx.Begin()
  5281. 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 `,
  5282. pastureid, barname).Query().List()
  5283. if err != nil {
  5284. logs.Error(err)
  5285. }
  5286. for _, fpd := range fpdList {
  5287. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5288. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5289. pastureid, fpd["id"], fpd["times"]).Query().List()
  5290. if err != nil {
  5291. tx.Rollback()
  5292. logs.Error(err)
  5293. return err
  5294. }
  5295. var lweight float64
  5296. for _, lppland := range lpplandList {
  5297. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5298. lweight += lweight1
  5299. }
  5300. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5301. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5302. if fpdweight >= ptuse && lweight == ptuse {
  5303. continue
  5304. } else {
  5305. if lweight <= fpdweight {
  5306. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5307. if err != nil {
  5308. tx.Rollback()
  5309. logs.Error(err)
  5310. return err
  5311. }
  5312. } else {
  5313. weight := lweight - fpdweight
  5314. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5315. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5316. if err != nil {
  5317. tx.Rollback()
  5318. logs.Error(err)
  5319. return err
  5320. }
  5321. for _, lppland := range lpplandList {
  5322. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5323. if weight >= lpplandlweight {
  5324. weight = weight - lpplandlweight
  5325. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5326. if err != nil {
  5327. tx.Rollback()
  5328. logs.Error(err)
  5329. return err
  5330. }
  5331. } else {
  5332. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5333. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5334. if err != nil {
  5335. tx.Rollback()
  5336. logs.Error(err)
  5337. return err
  5338. }
  5339. weight = 0
  5340. break
  5341. }
  5342. }
  5343. }
  5344. }
  5345. }
  5346. for _, list := range dataList {
  5347. ftmap := make(map[string]interface{})
  5348. ftmap["old"] = list.Old
  5349. ftmap["new"] = list.New
  5350. ftmap["times"] = list.Times
  5351. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5352. ftmap["ptsid"] = ""
  5353. // fmt.Println(ftmap)
  5354. // 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 ,
  5355. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5356. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5357. // UNION
  5358. fpdDataList, err := tx.SQL(`
  5359. 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 ,
  5360. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5361. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5362. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5363. if err != nil {
  5364. tx.Rollback()
  5365. logs.Error(err)
  5366. }
  5367. for _, fpd := range fpdDataList {
  5368. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5369. // fttype := -1
  5370. // if fpd["fttype"].(string) == "1" {
  5371. fttype := 1
  5372. // }
  5373. var fweight float64
  5374. var lweight float64
  5375. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5376. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5377. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5378. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5379. join tmr t on t.id = lpp.tmrid
  5380. where lppland.fpdid =?
  5381. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5382. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5383. if err != nil {
  5384. tx.Rollback()
  5385. logs.Error(err)
  5386. }
  5387. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5388. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5389. // 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
  5390. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5391. var w float64
  5392. var status int
  5393. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5394. if weight >= 0 {
  5395. continue
  5396. }
  5397. w = weight
  5398. status = 0
  5399. } else {
  5400. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5401. // continue
  5402. // }
  5403. w = weight
  5404. status = 1
  5405. }
  5406. // for _, lppland := range lpplandtl1List {
  5407. // lweight += lppland.Lweight
  5408. // }
  5409. for _, lppland := range lpplandtl1List {
  5410. lpplandInfo := new(lpplandtlInfo)
  5411. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5412. lweight = lpplandInfo.Lweight
  5413. if status == 1 {
  5414. // if w <= lppland.Lweight {
  5415. if lppland.Maxweight <= lweight {
  5416. continue
  5417. }
  5418. if w+lweight <= lppland.Maxweight {
  5419. lppland.Lweight += w
  5420. lweight += w
  5421. fweight += w
  5422. w = 0
  5423. } else {
  5424. w = w - (lppland.Maxweight - lweight)
  5425. n := (lppland.Maxweight - lweight)
  5426. lppland.Lweight = lppland.Lweight + n
  5427. lweight += n
  5428. fweight += n
  5429. }
  5430. } else {
  5431. if lppland.Lweight == 0 {
  5432. continue
  5433. }
  5434. if w+lppland.Lweight >= 0 {
  5435. lppland.Lweight = lppland.Lweight + w
  5436. lweight = lweight + w
  5437. fweight = fweight + w
  5438. w = 0
  5439. } else {
  5440. w = w + lppland.Lweight
  5441. lweight = lweight - lppland.Lweight
  5442. fweight = fweight - lppland.Lweight
  5443. lppland.Lweight = 0
  5444. }
  5445. }
  5446. if lppland.Lweight > 0 {
  5447. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5448. if err != nil {
  5449. tx.Rollback()
  5450. logs.Error(err)
  5451. return err
  5452. }
  5453. } else {
  5454. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5455. if err != nil {
  5456. tx.Rollback()
  5457. logs.Error(err)
  5458. return err
  5459. }
  5460. }
  5461. if w == 0 {
  5462. break
  5463. }
  5464. }
  5465. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5466. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5467. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5468. if err != nil {
  5469. tx.Rollback()
  5470. logs.Error(err)
  5471. }
  5472. if w == 0 {
  5473. break
  5474. }
  5475. }
  5476. }
  5477. }
  5478. err = tx.Commit()
  5479. if err != nil {
  5480. logs.Error(err)
  5481. tx.Rollback()
  5482. return err
  5483. }
  5484. now := time.Now()
  5485. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5486. if err != nil {
  5487. logs.Error(err)
  5488. return nil
  5489. }
  5490. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5491. if err != nil {
  5492. logs.Error(err)
  5493. return nil
  5494. }
  5495. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5496. if err != nil {
  5497. logs.Error(err)
  5498. return nil
  5499. }
  5500. for _, newLpplandtl1 := range newLpplandtl1List {
  5501. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5502. background,cowcount,ccountradio,lweighthis,createdate)
  5503. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5504. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5505. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5506. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5507. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5508. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5509. if err != nil {
  5510. logs.Error(err)
  5511. // appG.Response(http.StatusOK, e.ERROR, false)
  5512. return err
  5513. }
  5514. }
  5515. for _, newFpd := range newFpdDataList {
  5516. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5517. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5518. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5519. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5520. if err != nil {
  5521. logs.Error(err)
  5522. // appG.Response(http.StatusOK, e.ERROR, false)
  5523. return err
  5524. }
  5525. }
  5526. for _, newFeedp := range newFeedpList {
  5527. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5528. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5529. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5530. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5531. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5532. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5533. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5534. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5535. if err != nil {
  5536. logs.Error(err)
  5537. // appG.Response(http.StatusOK, e.ERROR, false)
  5538. return err
  5539. }
  5540. }
  5541. return nil
  5542. }
  5543. func DeleteFTdetail(c *gin.Context) {
  5544. appG := app.Gin{C: c}
  5545. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5546. fsion := gofasion.NewFasion(string(dataByte))
  5547. parammaps := fsion.Get("parammaps")
  5548. pastureid := parammaps.Get("pastureid").ValueStr()
  5549. ftid := parammaps.Get("ftid").ValueStr()
  5550. tx := restful.Engine.NewSession()
  5551. defer tx.Close()
  5552. tx.Begin()
  5553. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5554. if err != nil {
  5555. tx.Rollback()
  5556. logs.Error(err)
  5557. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5558. return
  5559. }
  5560. if parammaps.Get("type").ValueStr() == "1" {
  5561. _, err := tx.SQL(`UPDATE feedp fp
  5562. set
  5563. fp.ftweight= IFNULL(IF(
  5564. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5565. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5566. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5567. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5568. ),0),fp.feedweight = IFNULL(IF(
  5569. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5570. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5571. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5572. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5573. ),0) +ifnull(fp.supplyweight,0)
  5574. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5575. if err != nil {
  5576. tx.Rollback()
  5577. logs.Error(err)
  5578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5579. return
  5580. }
  5581. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5582. _, err = tx.SQL(`
  5583. UPDATE fpdetail fpd
  5584. INNER JOIN feedp fp
  5585. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5586. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5587. ptuse= 0
  5588. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5589. if err != nil {
  5590. tx.Rollback()
  5591. logs.Error(err)
  5592. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5593. return
  5594. }
  5595. } else {
  5596. _, err := tx.SQL(`UPDATE feedp fp
  5597. SET
  5598. fp.supplyweight= IFNULL(IF(
  5599. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5600. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5601. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5602. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5603. ),0),fp.feedweight = IFNULL(IF(
  5604. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5605. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5606. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5607. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5608. ),0) + ifnull(fp.supplyweight,0)
  5609. WHERE fp.pastureid = ? AND fp.ptsfid =?`, 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. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5617. _, err = tx.SQL(`
  5618. UPDATE fpdetail fpd
  5619. INNER JOIN feedp fp
  5620. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5621. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5622. ptsrate = 0
  5623. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5624. if err != nil {
  5625. tx.Rollback()
  5626. logs.Error(err)
  5627. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5628. return
  5629. }
  5630. }
  5631. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5632. if err != nil {
  5633. tx.Rollback()
  5634. logs.Error(err)
  5635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5636. return
  5637. }
  5638. err = tx.Commit()
  5639. if err != nil {
  5640. tx.Rollback()
  5641. logs.Error(err)
  5642. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5643. return
  5644. }
  5645. appG.Response(http.StatusOK, e.SUCCESS, true)
  5646. }
  5647. func DeleteSpillageAll(c *gin.Context) {
  5648. appG := app.Gin{C: c}
  5649. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5650. fsion := gofasion.NewFasion(string(dataByte))
  5651. parammaps := fsion.Get("parammaps")
  5652. pastureid := parammaps.Get("pastureid").ValueStr()
  5653. times := parammaps.Get("times").ValueStr()
  5654. barid := parammaps.Get("barid").ValueStr()
  5655. tx := restful.Engine.NewSession()
  5656. defer tx.Close()
  5657. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5658. if err != nil {
  5659. logs.Error(err)
  5660. appG.Response(http.StatusOK, e.ERROR, false)
  5661. return
  5662. }
  5663. now := time.Now()
  5664. for _, item := range lpplandtl1List {
  5665. go func(item map[string]interface{}) {
  5666. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5667. background,cowcount,ccountradio,lweighthis,createdate)
  5668. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5669. item["pastureid"], item["lppid"], item["barid"],
  5670. item["barname"], item["fpdid"], item["fttype"],
  5671. item["lweight"], item["sort"], item["tmrid"],
  5672. item["tmrname"], item["background"], item["cowcount"],
  5673. item["ccountradio"], item["lweighthis"], now).Execute()
  5674. if err != nil {
  5675. logs.Error(err)
  5676. appG.Response(http.StatusOK, e.ERROR, false)
  5677. return
  5678. }
  5679. }(item)
  5680. }
  5681. tx.Begin()
  5682. _, 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()
  5683. if err != nil {
  5684. tx.Rollback()
  5685. logs.Error(err)
  5686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5687. return
  5688. }
  5689. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5690. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5691. if err != nil {
  5692. tx.Rollback()
  5693. logs.Error(err)
  5694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5695. return
  5696. }
  5697. err = tx.Commit()
  5698. if err != nil {
  5699. tx.Rollback()
  5700. logs.Error(err)
  5701. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5702. return
  5703. }
  5704. appG.Response(http.StatusOK, e.SUCCESS, true)
  5705. }
  5706. func GetTMRListEnableTypeAll(c *gin.Context) {
  5707. appG := app.Gin{C: c}
  5708. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5709. fsion := gofasion.NewFasion(string(dataByte))
  5710. parammaps := fsion.Get("parammaps")
  5711. pastureid := parammaps.Get("pastureid").ValueStr()
  5712. tx := restful.Engine.NewSession()
  5713. defer tx.Close()
  5714. dataList, err := tx.SQL(`SELECT
  5715. eqcode,
  5716. tname,
  5717. datacaptureno,
  5718. trim(tclassid) tclassid,
  5719. concat(tname,' / ',eqcode) tmrmix,
  5720. d.label tclassname,
  5721. maxstirfeed,
  5722. remark,
  5723. tmr.enable,
  5724. TRIM(tmr.id) id,
  5725. TRIM(tmr.pastureid)pastureid
  5726. FROM
  5727. tmr
  5728. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5729. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5730. ORDER BY id DESC`, pastureid).Query().List()
  5731. if err != nil {
  5732. logs.Error(err)
  5733. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5734. return
  5735. }
  5736. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5737. if err != nil {
  5738. logs.Error(err)
  5739. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5740. return
  5741. }
  5742. var carNum int64
  5743. for _, sysopt := range sysoptData {
  5744. if sysopt["inforvalue"] == nil {
  5745. carNum = 1
  5746. } else {
  5747. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5748. }
  5749. }
  5750. id := 200
  5751. n := 0
  5752. for i := carNum; i > 0; i-- {
  5753. id++
  5754. n++
  5755. data := make(map[string]interface{}, 0)
  5756. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5757. data["tname"] = fmt.Sprintf("任意车%d", n)
  5758. data["datacaptureno"] = -2
  5759. data["tclassid"] = -2
  5760. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5761. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5762. data["maxstirfeed"] = 100000
  5763. data["remark"] = fmt.Sprintf("任意车%d", n)
  5764. data["enable"] = 1
  5765. data["id"] = fmt.Sprintf("%d", id)
  5766. data["pastureid"] = pastureid
  5767. dataList = append(dataList, data)
  5768. }
  5769. // UNION ALL
  5770. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5771. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5772. }
  5773. func GetFeedpHistory(c *gin.Context) {
  5774. appG := app.Gin{C: c}
  5775. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5776. fsion := gofasion.NewFasion(string(dataByte))
  5777. // parammaps := fsion.Get("parammaps")
  5778. bar := fsion.Get("barname").ValueStr()
  5779. startDate := fsion.Get("startDate").ValueStr()
  5780. endDate := fsion.Get("endDate").ValueStr()
  5781. tx := restful.Engine.NewSession()
  5782. defer tx.Close()
  5783. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5784. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5785. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5786. if err != nil {
  5787. logs.Error(err)
  5788. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5789. return
  5790. }
  5791. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5792. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5793. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5794. if err != nil {
  5795. logs.Error(err)
  5796. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5797. return
  5798. }
  5799. for _, feedp := range feedpList {
  5800. // LastftList, err := tx.SQL(` select tname ,id
  5801. // from feedtemplethistory where id = ?
  5802. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5803. // if err != nil {
  5804. // logs.Error(err)
  5805. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5806. // return
  5807. // }
  5808. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5809. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5810. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5811. if err != nil {
  5812. logs.Error(err)
  5813. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5814. return
  5815. }
  5816. var ftname interface{}
  5817. ftnamestatus := 0
  5818. ftname = feedp["ftname"]
  5819. var lastftid int64
  5820. if len(nextfeedpList) > 0 {
  5821. for _, ft := range nextfeedpList {
  5822. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5823. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5824. lastftid = ft["ftid"].(int64)
  5825. ftnamestatus = 1
  5826. break
  5827. }
  5828. }
  5829. }
  5830. for i, fpd := range fpdList {
  5831. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5832. fpd["weightstatus"] = 0
  5833. fpd["tratiostatus"] = 0
  5834. fpd["ftnamestatus"] = ftnamestatus
  5835. for k, fpd2 := range fpdList {
  5836. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5837. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5838. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5839. fpd["weightstatus"] = 1
  5840. }
  5841. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5842. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5843. fpd["tratiostatus"] = 1
  5844. }
  5845. break
  5846. }
  5847. }
  5848. fpd["barid"] = feedp["barid"]
  5849. fpd["barname"] = feedp["barname"]
  5850. fpd["ccount"] = feedp["ccount"]
  5851. fpd["ratio"] = feedp["ratio"]
  5852. fpd["ccountratio"] = feedp["ccountratio"]
  5853. fpd["ftid"] = feedp["ftid"]
  5854. fpd["ftname"] = ftname
  5855. fpd["ccountstatus"] = 0
  5856. fpd["ccountratiostatus"] = 0
  5857. fpd["ratiostatus"] = 0
  5858. fpd["ftnamestatus"] = 0
  5859. fpd["lastftid"] = lastftid
  5860. for _, next := range nextfeedpList {
  5861. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5862. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5863. fpd["ccountstatus"] = 1
  5864. }
  5865. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5866. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5867. fpd["ccountratiostatus"] = 1
  5868. }
  5869. if next["ratio"].(string) != fpd["ratio"].(string) {
  5870. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5871. fpd["ratiostatus"] = 1
  5872. }
  5873. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5874. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5875. // fpd["ftnamestatus"] = 1
  5876. // }
  5877. }
  5878. }
  5879. }
  5880. }
  5881. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5882. }
  5883. // func GetLpplandtl1History(c *gin.Context) {
  5884. // appG := app.Gin{C: c}
  5885. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5886. // fsion := gofasion.NewFasion(string(dataByte))
  5887. // // parammaps := fsion.Get("parammaps")
  5888. // barid := fsion.Get("barid").ValueStr()
  5889. // startDate := fsion.Get("startDate").ValueStr()
  5890. // endDate := fsion.Get("endDate").ValueStr()
  5891. // tx := restful.Engine.NewSession()
  5892. // defer tx.Close()
  5893. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5894. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5895. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5896. // // if err != nil {
  5897. // // logs.Error(err)
  5898. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5899. // // return
  5900. // // }
  5901. // // for _, feedp := range feedpList {
  5902. // // fmt.Println(feedp)
  5903. // // for i, fpd := range fpdList {
  5904. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5905. // // for k, fpd2 := range fpdList {
  5906. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5907. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5908. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5909. // // }
  5910. // // break
  5911. // // }
  5912. // // }
  5913. // // fpd["barid"] = feedp["barid"]
  5914. // // fpd["barname"] = feedp["barname"]
  5915. // // fpd["ccount"] = feedp["ccount"]
  5916. // // fpd["ratio"] = feedp["ratio"]
  5917. // // fpd["ccountratio"] = feedp["ccountratio"]
  5918. // // fpd["ftid"] = feedp["ftid"]
  5919. // // fpd["ftname"] = feedp["ftname"]
  5920. // // }
  5921. // // }
  5922. // // }
  5923. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5924. // }
  5925. func GetRemind(c *gin.Context) {
  5926. appG := app.Gin{C: c}
  5927. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5928. fsion := gofasion.NewFasion(string(dataByte))
  5929. parammaps := fsion.Get("parammaps")
  5930. pastureid := parammaps.Get("pastureid").ValueStr()
  5931. tx := restful.Engine.NewSession()
  5932. defer tx.Close()
  5933. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5934. if err != nil {
  5935. logs.Error(err)
  5936. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5937. return
  5938. }
  5939. // pastureid = "3"
  5940. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5941. if err != nil {
  5942. logs.Error(err)
  5943. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5944. return
  5945. }
  5946. defer resp.Body.Close()
  5947. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5948. buf.ReadFrom(resp.Body)
  5949. fmt.Println(string(buf.Bytes()))
  5950. respMap := make(map[string]interface{}, 0)
  5951. err = json.Unmarshal(buf.Bytes(), &respMap)
  5952. if err != nil {
  5953. logs.Error(err)
  5954. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5955. return
  5956. }
  5957. for _, data := range dataList {
  5958. r := make(map[string]interface{}, 0)
  5959. r["sys_name"] = ""
  5960. r["service_id"] = ""
  5961. r["pasture_id"] = ""
  5962. r["type_name"] = ""
  5963. r["remind_type_id"] = ""
  5964. r["remind_type"] = ""
  5965. r["push_date"] = ""
  5966. r["push_time"] = ""
  5967. r["interval_time"] = ""
  5968. r["push_limit"] = ""
  5969. r["template_id"] = ""
  5970. r["roles_id"] = ""
  5971. r["users_id"] = ""
  5972. r["date_type"] = ""
  5973. r["cycle_type"] = ""
  5974. data["data"] = r
  5975. for _, resp := range respMap["data"].([]interface{}) {
  5976. resp1 := resp.(map[string]interface{})
  5977. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5978. if resp1["push_time"] == nil {
  5979. resp1["push_time"] = ""
  5980. }
  5981. data["data"] = resp1
  5982. break
  5983. }
  5984. }
  5985. }
  5986. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5987. }
  5988. type NoticeMsgtype struct {
  5989. SysName string `json:"sys_name"`
  5990. PastureId int64 `json:"pasture_id"`
  5991. ServiceId int64 `json:"service_id"`
  5992. TypeName string `json:"type_name"`
  5993. RemindType int64 `json:"remind_type"`
  5994. PushDate int64 `json:"push_date"`
  5995. PushTime string `json:"push_time"`
  5996. IntervalTime int64 `json:"interval_time"`
  5997. PushLimit int64 `json:"push_limit"`
  5998. TemplateId string `json:"template_id"`
  5999. UsersId string `json:"users_id"`
  6000. DateType int64 `json:"date_type"`
  6001. CycleType int64 `json:"cycle_type"`
  6002. DelayTime int64 `json:"delay_time"`
  6003. Status int64 `json:"status"`
  6004. }
  6005. func UpdateRemind(c *gin.Context) {
  6006. appG := app.Gin{C: c}
  6007. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6008. parammaps := gofasion.NewFasion(string(dataByte))
  6009. // parammaps := fsion.Get("parammaps")
  6010. // user := parammaps.Get("user").ValueStr()
  6011. id := parammaps.Get("id").ValueInt64()
  6012. noticeMsgtype := new(NoticeMsgtype)
  6013. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6014. noticeMsgtype.ServiceId = id
  6015. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6016. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6017. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6018. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6019. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6020. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6021. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6022. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6023. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6024. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6025. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6026. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6027. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6028. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6029. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6030. //TODO
  6031. noticeMsgtype.SysName = "tmrWatch"
  6032. userList := parammaps.Get("user").Array()
  6033. var userstr []string
  6034. for _, user := range userList {
  6035. userstr = append(userstr, user.ValueStr())
  6036. }
  6037. tx := restful.Engine.NewSession()
  6038. defer tx.Close()
  6039. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6040. if err != nil {
  6041. logs.Error(err)
  6042. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6043. return
  6044. }
  6045. // var jsonStr = []byte(noticeMsgtype
  6046. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6047. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6048. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6049. req.Header.Set("Content-Type", "application/json")
  6050. client := &http.Client{}
  6051. resp, err := client.Do(req)
  6052. if err != nil {
  6053. logs.Error(err)
  6054. }
  6055. defer resp.Body.Close()
  6056. body, _ := ioutil.ReadAll(resp.Body)
  6057. fmt.Println("response Body:", string(body))
  6058. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6059. if err != nil {
  6060. logs.Error(err)
  6061. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6062. return
  6063. }
  6064. defer getresp.Body.Close()
  6065. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6066. buf.ReadFrom(getresp.Body)
  6067. // fmt.Println(string(buf.Bytes()))
  6068. respMap := make(map[string]interface{}, 0)
  6069. err = json.Unmarshal(buf.Bytes(), &respMap)
  6070. if err != nil {
  6071. logs.Error(err)
  6072. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6073. return
  6074. }
  6075. for _, resp := range respMap["data"].([]interface{}) {
  6076. resp1 := resp.(map[string]interface{})
  6077. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6078. if err != nil {
  6079. logs.Error(err)
  6080. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6081. return
  6082. }
  6083. }
  6084. appG.Response(http.StatusOK, e.SUCCESS, true)
  6085. }
  6086. func GetSpillageallHistory(c *gin.Context) {
  6087. appG := app.Gin{C: c}
  6088. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6089. parammaps := gofasion.NewFasion(string(dataByte))
  6090. barname := parammaps.Get("barname").ValueStr()
  6091. pastureid := parammaps.Get("pastureid").ValueStr()
  6092. startdate := parammaps.Get("startDate").ValueStr()
  6093. enddate := parammaps.Get("endDate").ValueStr()
  6094. tx := restful.Engine.NewSession()
  6095. defer tx.Close()
  6096. 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
  6097. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6098. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6099. if err != nil {
  6100. logs.Error(err)
  6101. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6102. return
  6103. }
  6104. respMap := make([]map[string]interface{}, 0)
  6105. data := make(map[interface{}]interface{})
  6106. for _, history := range historyList {
  6107. data[history["createdate"]] = history["createdate"]
  6108. }
  6109. createList := []string{}
  6110. for _, v := range data {
  6111. createList = append(createList, v.(string))
  6112. }
  6113. // sort.Sort()
  6114. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6115. sort.Slice(createList, func(i, j int) bool {
  6116. return createList[i] > createList[j]
  6117. })
  6118. for _, v := range createList {
  6119. a := make(map[string]interface{})
  6120. a["createdate"] = data[v]
  6121. // createList = append(createList, v.(string))
  6122. respMap = append(respMap, a)
  6123. }
  6124. number := 0
  6125. dataMap := make([]interface{}, 0)
  6126. for k, resp := range respMap {
  6127. createdate := resp["createdate"].(string)
  6128. var nextcreatedate string
  6129. if len(respMap) > k+1 {
  6130. nextcreatedate = respMap[k+1]["createdate"].(string)
  6131. }
  6132. // dataList := make(map[string][]interface{})
  6133. // list := make(map[string]interface{})
  6134. times := make(map[interface{}]int)
  6135. for _, history := range historyList {
  6136. // List := make(map[interface{}][]interface{})
  6137. i := 0
  6138. if history["createdate"].(string) == createdate {
  6139. times[history["times"]]++
  6140. data := make(map[string]interface{})
  6141. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6142. // exist := false
  6143. if nextcreatedate != "" {
  6144. for _, history1 := range historyList {
  6145. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6146. history1["times"].(int64) == history["times"].(int64) {
  6147. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6148. break
  6149. // exist = true
  6150. }
  6151. }
  6152. }
  6153. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6154. i++
  6155. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6156. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6157. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6158. // resp["times"] = history["times"]
  6159. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6160. data1 := make(map[string]interface{})
  6161. data1["times"] = history["times"]
  6162. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6163. data1["createdate"] = resp["createdate"]
  6164. // fmt.Println(dataList)
  6165. dataMap = append(dataMap, data1)
  6166. }
  6167. if i > number {
  6168. number = i
  6169. }
  6170. // respMap = append(respMap, dataList)
  6171. }
  6172. // for k, data := range dataList {
  6173. // resp[k] = data
  6174. // }
  6175. // resp["data"] = dataList
  6176. }
  6177. // resp := make(map[string]interface{})
  6178. // sort.Strings(createList)
  6179. //
  6180. // for _, create := range createList {
  6181. // for _, r := range respMap {
  6182. // if create == r["createdate"].(string) {
  6183. // resp[create] = r
  6184. // break
  6185. // }
  6186. // }
  6187. // }
  6188. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6189. var trainsList []interface{}
  6190. for i := 0; i < number; i++ {
  6191. trains := make(map[string]interface{})
  6192. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6193. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6194. trainsList = append(trainsList, trains)
  6195. }
  6196. respdata := make(map[string]interface{})
  6197. respdata["data"] = dataMap
  6198. respdata["trains"] = trainsList
  6199. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6200. }
  6201. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6202. appG := app.Gin{C: c}
  6203. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6204. parammaps := gofasion.NewFasion(string(dataByte))
  6205. ftid := parammaps.Get("ftid").ValueInt64()
  6206. lastftid := parammaps.Get("lastftid").ValueInt64()
  6207. pastureid := parammaps.Get("pastureid").ValueInt64()
  6208. // createdate := parammaps.Get("createdate").ValueStr()
  6209. tx := restful.Engine.NewSession()
  6210. defer tx.Close()
  6211. data := make(map[string]interface{})
  6212. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6213. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6214. if err != nil {
  6215. logs.Error(err)
  6216. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6217. return
  6218. }
  6219. feedtemplet := make(map[string]interface{})
  6220. for _, f := range feedtempletList {
  6221. feedtemplet = f
  6222. }
  6223. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6224. if err != nil {
  6225. logs.Error(err)
  6226. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6227. return
  6228. }
  6229. feedtemplet["fit"] = fitList
  6230. data["current"] = feedtemplet
  6231. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6232. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6233. if err != nil {
  6234. logs.Error(err)
  6235. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6236. return
  6237. }
  6238. lastfeedtemplet := make(map[string]interface{})
  6239. for _, f := range lastfeedtempletList {
  6240. lastfeedtemplet = f
  6241. }
  6242. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6243. if err != nil {
  6244. logs.Error(err)
  6245. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6246. return
  6247. }
  6248. lastfeedtemplet["fit"] = lastfitList
  6249. data["last"] = lastfeedtemplet
  6250. appG.Response(http.StatusOK, e.SUCCESS, data)
  6251. }
  6252. func GetFeedtempletHistory(c *gin.Context) {
  6253. appG := app.Gin{C: c}
  6254. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6255. parammaps := gofasion.NewFasion(string(dataByte))
  6256. ftid := parammaps.Get("ftid").ValueStr()
  6257. pastureid := parammaps.Get("pastureid").ValueInt64()
  6258. start := parammaps.Get("startdate").ValueStr()
  6259. end := parammaps.Get("enddate").ValueStr()
  6260. tx := restful.Engine.NewSession()
  6261. defer tx.Close()
  6262. 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 ?
  6263. and id = ? and pastureid = ? order by createdate desc `,
  6264. start, end, ftid, pastureid).Query().List()
  6265. if err != nil {
  6266. logs.Error(err)
  6267. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6268. return
  6269. }
  6270. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6271. ftid, pastureid).Query().List()
  6272. if err != nil {
  6273. logs.Error(err)
  6274. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6275. return
  6276. }
  6277. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6278. for i, ft := range ftList {
  6279. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6280. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6281. (select empname from user where id = fit.userId) empname,
  6282. 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
  6283. where fit.fitid = ?
  6284. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6285. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6286. if err != nil {
  6287. logs.Error(err)
  6288. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6289. return
  6290. }
  6291. ft["createdate"] = ft["createdate1"]
  6292. // data["tname"] = ft["tname"]
  6293. // data["tcode"] = ft["tcode"]
  6294. // data["tcolor"] = ft["tcolor"]
  6295. // data["fttype"] = ft["fttype"]
  6296. // data["ccname"] = ft["ccname"]
  6297. // data["source"] = ft["source"]
  6298. // data["version"] = ft["version"]
  6299. // data["remark"] = ft["remark"]
  6300. for n, ft2 := range ftList {
  6301. if i < n {
  6302. if ft["tname"].(string) != ft2["tname"].(string) {
  6303. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6304. }
  6305. if _, ok := ft["tcode"]; ok {
  6306. if _, ok := ft2["tcode"]; ok {
  6307. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6308. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6309. }
  6310. }
  6311. }
  6312. if _, ok := ft["tcolor"]; ok {
  6313. if _, ok := ft2["tcolor"]; ok {
  6314. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6315. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6316. }
  6317. }
  6318. }
  6319. if _, ok := ft["fttype"]; ok {
  6320. if _, ok := ft2["fttype"]; ok {
  6321. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6322. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6323. }
  6324. }
  6325. }
  6326. if _, ok := ft["ccname"]; ok {
  6327. if _, ok := ft2["ccname"]; ok {
  6328. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6329. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6330. }
  6331. }
  6332. }
  6333. if _, ok := ft["source"]; ok {
  6334. if _, ok := ft2["source"]; ok {
  6335. if ft["source"].(string) != ft2["source"].(string) {
  6336. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6337. }
  6338. }
  6339. }
  6340. if _, ok := ft["version"]; ok {
  6341. if _, ok := ft2["version"]; ok {
  6342. if ft["version"].(int64) != ft2["version"].(int64) {
  6343. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6344. }
  6345. }
  6346. }
  6347. if _, ok := ft["remark"]; ok {
  6348. if _, ok := ft2["remark"]; ok {
  6349. if ft["remark"].(string) != ft2["remark"].(string) {
  6350. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6351. }
  6352. }
  6353. }
  6354. break
  6355. }
  6356. }
  6357. dataList := make([]map[string]interface{}, 0)
  6358. if len(fithisList) > 0 {
  6359. for _, fit := range fithisList {
  6360. data := make(map[string]interface{})
  6361. data["feedgroup"] = fit["feedgroup"]
  6362. data["fname"] = fit["fname"]
  6363. data["empname"] = fit["empname"]
  6364. if fit["Eweight"] != nil {
  6365. if fit["Eweight"].(string) != fit["weight"].(string) {
  6366. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6367. } else {
  6368. data["fweight"] = fit["Eweight"]
  6369. }
  6370. data["fweightstatus"] = 1
  6371. } else {
  6372. data["fweight"] = fit["weight"]
  6373. data["fweightstatus"] = 0
  6374. }
  6375. data["autosecond"] = fit["autosecond"]
  6376. // data["tname"] = ft["tname"]
  6377. // data["tcode"] = ft["tcode"]
  6378. // data["tcolor"] = ft["tcolor"]
  6379. // data["fttype"] = ft["fttype"]
  6380. // data["ccname"] = ft["ccname"]
  6381. // data["source"] = ft["source"]
  6382. // data["version"] = ft["version"]
  6383. // data["remark"] = ft["remark"]
  6384. // data["createdate"] = ft["createdate1"]
  6385. // ft["fit"] = data
  6386. dataList = append(dataList, data)
  6387. }
  6388. } else {
  6389. for _, fit := range ftdetailList {
  6390. data := make(map[string]interface{})
  6391. data["feedgroup"] = fit["feedgroup"]
  6392. data["fname"] = fit["fname"]
  6393. // if fit["Eweight"] != nil {
  6394. // data["weight"] = fit["Eweight"]
  6395. // } else {
  6396. data["fweight"] = fit["fweight"]
  6397. // }
  6398. data["autosecond"] = fit["autosecond"]
  6399. // ft["fit"] = data
  6400. dataList = append(dataList, data)
  6401. }
  6402. }
  6403. ft["fit"] = dataList
  6404. }
  6405. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6406. }
  6407. func UpdateMaterialTMR(c *gin.Context) {
  6408. appG := app.Gin{C: c}
  6409. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6410. parammaps := gofasion.NewFasion(string(dataByte))
  6411. tmrid := parammaps.Get("tmrid").ValueStr()
  6412. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6413. lppid := parammaps.Get("lppid").ValueStr()
  6414. times := parammaps.Get("times").ValueStr()
  6415. pastureid := parammaps.Get("pastureid").ValueStr()
  6416. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6417. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6418. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6419. tx := restful.Engine.NewSession()
  6420. defer tx.Close()
  6421. tx.Begin()
  6422. if tmrid != "1000" {
  6423. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6424. if err != nil {
  6425. logs.Error(err)
  6426. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6427. return
  6428. }
  6429. var maxstirfeed float64
  6430. for _, tmr := range tmrList {
  6431. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6432. }
  6433. if status == 0 {
  6434. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6435. if err != nil {
  6436. tx.Rollback()
  6437. logs.Error(err)
  6438. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6439. return
  6440. }
  6441. var lweight float64
  6442. for _, item := range lpplandtl1List {
  6443. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6444. lweight += fl
  6445. }
  6446. if lweight > maxstirfeed {
  6447. lweight = lweight - maxstirfeed
  6448. } else {
  6449. lweight = 0
  6450. }
  6451. if lweight > 0 {
  6452. lweight1 := lweight / float64(len(lpplandtl1List))
  6453. number := 0
  6454. for _, item := range lpplandtl1List {
  6455. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6456. if lweight1 >= fl {
  6457. number++
  6458. }
  6459. }
  6460. lweight := lweight / float64((len(lpplandtl1List) - number))
  6461. for _, item := range lpplandtl1List {
  6462. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6463. if lweight1 >= fl {
  6464. continue
  6465. }
  6466. if tmrtype == "1" {
  6467. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6468. if err != nil {
  6469. tx.Rollback()
  6470. logs.Error(err)
  6471. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6472. return
  6473. }
  6474. } else if tmrtype == "2" {
  6475. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6476. if err != nil {
  6477. tx.Rollback()
  6478. logs.Error(err)
  6479. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6480. return
  6481. }
  6482. }
  6483. if item["fttype"].(int64) == 0 {
  6484. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6485. if err != nil {
  6486. tx.Rollback()
  6487. logs.Error(err)
  6488. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6489. return
  6490. }
  6491. } else {
  6492. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6493. if err != nil {
  6494. tx.Rollback()
  6495. logs.Error(err)
  6496. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6497. return
  6498. }
  6499. }
  6500. }
  6501. } else {
  6502. for _, item := range lpplandtl1List {
  6503. // 自走式
  6504. if tmrtype == "1" {
  6505. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6506. if err != nil {
  6507. logs.Error(err)
  6508. tx.Rollback()
  6509. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6510. return
  6511. }
  6512. } else if tmrtype == "2" {
  6513. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6514. if err != nil {
  6515. logs.Error(err)
  6516. tx.Rollback()
  6517. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6518. return
  6519. }
  6520. }
  6521. }
  6522. }
  6523. } else if status == 1 {
  6524. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6525. if err != nil {
  6526. logs.Error(err)
  6527. tx.Rollback()
  6528. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6529. return
  6530. }
  6531. var lweight float64
  6532. for _, item := range lpplandtl1List {
  6533. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6534. lweight += fl
  6535. }
  6536. if lweight > maxstirfeed {
  6537. lweight = lweight - maxstirfeed
  6538. } else {
  6539. lweight = 0
  6540. }
  6541. for _, item := range lpplandtl1List {
  6542. if lweight > 0 {
  6543. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6544. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6545. if fl >= lweight {
  6546. item["lweight"] = fl - lweight
  6547. lweight = 0
  6548. if tmrtype == "1" {
  6549. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6550. if err != nil {
  6551. logs.Error(err)
  6552. tx.Rollback()
  6553. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6554. return
  6555. }
  6556. } else if tmrtype == "2" {
  6557. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6558. if err != nil {
  6559. logs.Error(err)
  6560. tx.Rollback()
  6561. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6562. return
  6563. }
  6564. }
  6565. if item["fttype"].(int64) == 0 {
  6566. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6567. if err != nil {
  6568. logs.Error(err)
  6569. tx.Rollback()
  6570. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6571. return
  6572. }
  6573. } else {
  6574. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6575. if err != nil {
  6576. logs.Error(err)
  6577. tx.Rollback()
  6578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6579. return
  6580. }
  6581. }
  6582. } else {
  6583. lweight = lweight - fl
  6584. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6585. if err != nil {
  6586. logs.Error(err)
  6587. tx.Rollback()
  6588. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6589. return
  6590. }
  6591. if item["fttype"].(int64) == 0 {
  6592. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6593. if err != nil {
  6594. logs.Error(err)
  6595. tx.Rollback()
  6596. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6597. return
  6598. }
  6599. } else {
  6600. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6601. if err != nil {
  6602. logs.Error(err)
  6603. tx.Rollback()
  6604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6605. return
  6606. }
  6607. }
  6608. }
  6609. } else {
  6610. // 自走式
  6611. if tmrtype == "1" {
  6612. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6613. if err != nil {
  6614. logs.Error(err)
  6615. tx.Rollback()
  6616. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6617. return
  6618. }
  6619. } else if tmrtype == "2" {
  6620. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6621. if err != nil {
  6622. logs.Error(err)
  6623. tx.Rollback()
  6624. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6625. return
  6626. }
  6627. }
  6628. }
  6629. }
  6630. } else {
  6631. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6632. if err != nil {
  6633. logs.Error(err)
  6634. tx.Rollback()
  6635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6636. return
  6637. }
  6638. for _, item := range lpplandtl1List {
  6639. if item["fttype"].(int64) == 0 {
  6640. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6641. if err != nil {
  6642. logs.Error(err)
  6643. tx.Rollback()
  6644. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6645. return
  6646. }
  6647. } else {
  6648. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6649. if err != nil {
  6650. logs.Error(err)
  6651. tx.Rollback()
  6652. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6653. return
  6654. }
  6655. }
  6656. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6657. if err != nil {
  6658. logs.Error(err)
  6659. tx.Rollback()
  6660. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6661. return
  6662. }
  6663. }
  6664. }
  6665. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6666. if err != nil {
  6667. logs.Error(err)
  6668. tx.Rollback()
  6669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6670. return
  6671. }
  6672. } else {
  6673. if status == 2 {
  6674. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6675. if err != nil {
  6676. logs.Error(err)
  6677. tx.Rollback()
  6678. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6679. return
  6680. }
  6681. for _, item := range lpplandtl1List {
  6682. if item["fttype"].(int64) == 0 {
  6683. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6684. if err != nil {
  6685. logs.Error(err)
  6686. tx.Rollback()
  6687. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6688. return
  6689. }
  6690. } else {
  6691. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6692. if err != nil {
  6693. logs.Error(err)
  6694. tx.Rollback()
  6695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6696. return
  6697. }
  6698. }
  6699. }
  6700. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6701. if err != nil {
  6702. logs.Error(err)
  6703. tx.Rollback()
  6704. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6705. return
  6706. }
  6707. } else {
  6708. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. }
  6716. }
  6717. err := tx.Commit()
  6718. if err != nil {
  6719. logs.Error(err)
  6720. tx.Rollback()
  6721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6722. return
  6723. }
  6724. appG.Response(http.StatusOK, e.SUCCESS, true)
  6725. }
  6726. func UpdateMaterialTMRDate(c *gin.Context) {
  6727. appG := app.Gin{C: c}
  6728. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6729. parammaps := gofasion.NewFasion(string(dataByte))
  6730. tmrid := parammaps.Get("tmrid").ValueStr()
  6731. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6732. lppid := parammaps.Get("lppid").ValueStr()
  6733. times := parammaps.Get("times").ValueStr()
  6734. pastureid := parammaps.Get("pastureid").ValueStr()
  6735. date := parammaps.Get("date").ValueStr()
  6736. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6737. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6738. tx := restful.Engine.NewSession()
  6739. defer tx.Close()
  6740. tx.Begin()
  6741. if tmrid != "1000" {
  6742. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6743. if err != nil {
  6744. logs.Error(err)
  6745. tx.Rollback()
  6746. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6747. return
  6748. }
  6749. var maxstirfeed float64
  6750. for _, tmr := range tmrList {
  6751. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6752. }
  6753. if status == 0 {
  6754. 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()
  6755. if err != nil {
  6756. logs.Error(err)
  6757. tx.Rollback()
  6758. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6759. return
  6760. }
  6761. var lweight float64
  6762. for _, item := range lpplandtl1List {
  6763. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6764. lweight += fl
  6765. }
  6766. if lweight > maxstirfeed {
  6767. lweight = lweight - maxstirfeed
  6768. } else {
  6769. lweight = 0
  6770. }
  6771. if lweight > 0 {
  6772. lweight1 := lweight / float64(len(lpplandtl1List))
  6773. number := 0
  6774. for _, item := range lpplandtl1List {
  6775. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6776. if lweight1 >= fl {
  6777. number++
  6778. }
  6779. }
  6780. lweight := lweight / float64((len(lpplandtl1List) - number))
  6781. for _, item := range lpplandtl1List {
  6782. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6783. if lweight1 >= fl {
  6784. continue
  6785. }
  6786. if tmrtype == "1" {
  6787. _, 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()
  6788. if err != nil {
  6789. logs.Error(err)
  6790. tx.Rollback()
  6791. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6792. return
  6793. }
  6794. } else if tmrtype == "2" {
  6795. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6796. if err != nil {
  6797. logs.Error(err)
  6798. tx.Rollback()
  6799. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6800. return
  6801. }
  6802. }
  6803. if item["fttype"].(int64) == 0 {
  6804. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6805. if err != nil {
  6806. logs.Error(err)
  6807. tx.Rollback()
  6808. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6809. return
  6810. }
  6811. } else {
  6812. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6813. if err != nil {
  6814. logs.Error(err)
  6815. tx.Rollback()
  6816. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6817. return
  6818. }
  6819. }
  6820. }
  6821. } else {
  6822. for _, item := range lpplandtl1List {
  6823. // 自走式
  6824. if tmrtype == "1" {
  6825. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6826. if err != nil {
  6827. logs.Error(err)
  6828. tx.Rollback()
  6829. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6830. return
  6831. }
  6832. } else if tmrtype == "2" {
  6833. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6834. if err != nil {
  6835. logs.Error(err)
  6836. tx.Rollback()
  6837. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6838. return
  6839. }
  6840. }
  6841. }
  6842. }
  6843. } else if status == 1 {
  6844. 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()
  6845. if err != nil {
  6846. logs.Error(err)
  6847. tx.Rollback()
  6848. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6849. return
  6850. }
  6851. var lweight float64
  6852. for _, item := range lpplandtl1List {
  6853. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6854. lweight += fl
  6855. }
  6856. if lweight > maxstirfeed {
  6857. lweight = lweight - maxstirfeed
  6858. } else {
  6859. lweight = 0
  6860. }
  6861. for _, item := range lpplandtl1List {
  6862. if lweight > 0 {
  6863. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6864. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6865. if fl >= lweight {
  6866. item["lweight"] = fl - lweight
  6867. lweight = 0
  6868. if tmrtype == "1" {
  6869. _, 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()
  6870. if err != nil {
  6871. logs.Error(err)
  6872. tx.Rollback()
  6873. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6874. return
  6875. }
  6876. } else if tmrtype == "2" {
  6877. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6878. if err != nil {
  6879. logs.Error(err)
  6880. tx.Rollback()
  6881. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6882. return
  6883. }
  6884. }
  6885. if item["fttype"].(int64) == 0 {
  6886. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6887. if err != nil {
  6888. logs.Error(err)
  6889. tx.Rollback()
  6890. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6891. return
  6892. }
  6893. } else {
  6894. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6895. if err != nil {
  6896. logs.Error(err)
  6897. tx.Rollback()
  6898. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6899. return
  6900. }
  6901. }
  6902. } else {
  6903. lweight = lweight - fl
  6904. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6905. if err != nil {
  6906. logs.Error(err)
  6907. tx.Rollback()
  6908. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6909. return
  6910. }
  6911. if item["fttype"].(int64) == 0 {
  6912. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6913. if err != nil {
  6914. logs.Error(err)
  6915. tx.Rollback()
  6916. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6917. return
  6918. }
  6919. } else {
  6920. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6921. if err != nil {
  6922. logs.Error(err)
  6923. tx.Rollback()
  6924. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6925. return
  6926. }
  6927. }
  6928. }
  6929. } else {
  6930. // 自走式
  6931. if tmrtype == "1" {
  6932. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6933. if err != nil {
  6934. logs.Error(err)
  6935. tx.Rollback()
  6936. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6937. return
  6938. }
  6939. } else if tmrtype == "2" {
  6940. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6941. if err != nil {
  6942. logs.Error(err)
  6943. tx.Rollback()
  6944. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6945. return
  6946. }
  6947. }
  6948. }
  6949. }
  6950. } else {
  6951. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6952. if err != nil {
  6953. logs.Error(err)
  6954. tx.Rollback()
  6955. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6956. return
  6957. }
  6958. for _, item := range lpplandtl1List {
  6959. if item["fttype"].(int64) == 0 {
  6960. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6961. if err != nil {
  6962. logs.Error(err)
  6963. tx.Rollback()
  6964. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6965. return
  6966. }
  6967. } else {
  6968. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6969. if err != nil {
  6970. logs.Error(err)
  6971. tx.Rollback()
  6972. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6973. return
  6974. }
  6975. }
  6976. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6977. if err != nil {
  6978. logs.Error(err)
  6979. tx.Rollback()
  6980. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6981. return
  6982. }
  6983. }
  6984. }
  6985. _, 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()
  6986. if err != nil {
  6987. logs.Error(err)
  6988. tx.Rollback()
  6989. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6990. return
  6991. }
  6992. } else {
  6993. if status == 2 {
  6994. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6995. if err != nil {
  6996. logs.Error(err)
  6997. tx.Rollback()
  6998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6999. return
  7000. }
  7001. for _, item := range lpplandtl1List {
  7002. if item["fttype"].(int64) == 0 {
  7003. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7004. if err != nil {
  7005. logs.Error(err)
  7006. tx.Rollback()
  7007. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7008. return
  7009. }
  7010. } else {
  7011. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7012. if err != nil {
  7013. logs.Error(err)
  7014. tx.Rollback()
  7015. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7016. return
  7017. }
  7018. }
  7019. }
  7020. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7021. if err != nil {
  7022. logs.Error(err)
  7023. tx.Rollback()
  7024. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7025. return
  7026. }
  7027. } else {
  7028. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7029. if err != nil {
  7030. logs.Error(err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7033. return
  7034. }
  7035. }
  7036. }
  7037. err := tx.Commit()
  7038. if err != nil {
  7039. logs.Error(err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7042. return
  7043. }
  7044. appG.Response(http.StatusOK, e.SUCCESS, true)
  7045. }
  7046. func Decimal(value float64) float64 {
  7047. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7048. return value
  7049. }
  7050. func UpdateDailyData(c *gin.Context) {
  7051. appG := app.Gin{C: c}
  7052. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7053. parammaps := gofasion.NewFasion(string(dataByte))
  7054. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7055. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7056. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7057. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7058. date := parammaps.Get("date").ValueStr()
  7059. tx := restful.Engine.NewSession()
  7060. defer tx.Close()
  7061. 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()
  7062. if err != nil {
  7063. logs.Error("UpdateDailyData-error-0:", err)
  7064. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7065. return
  7066. }
  7067. if count > 0 {
  7068. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7069. return
  7070. }
  7071. tx.Begin()
  7072. if location == 0 {
  7073. fid := parammaps.Get("fid").ValueStr()
  7074. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7075. if err != nil {
  7076. logs.Error("UpdateDailyData-error-1:", err)
  7077. tx.Rollback()
  7078. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7079. return
  7080. }
  7081. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7082. if err != nil {
  7083. logs.Error("UpdateDailyData-error-1:", err)
  7084. tx.Rollback()
  7085. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7086. return
  7087. }
  7088. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7089. if err != nil {
  7090. fmt.Println("Error:", err)
  7091. return
  7092. }
  7093. actualWeight := weight - num
  7094. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7095. if err != nil {
  7096. logs.Error("UpdateDailyData-error-2:", err)
  7097. tx.Rollback()
  7098. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7099. return
  7100. }
  7101. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7102. if err != nil {
  7103. logs.Error("UpdateDailyData-error-3:", err)
  7104. tx.Rollback()
  7105. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7106. return
  7107. }
  7108. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7109. if err != nil {
  7110. logs.Error("UpdateDailyData-error-4:", err)
  7111. tx.Rollback()
  7112. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7113. return
  7114. }
  7115. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7116. if err != nil {
  7117. logs.Error("UpdateDailyData-error-5:", err)
  7118. tx.Rollback()
  7119. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7120. return
  7121. }
  7122. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7123. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7124. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7125. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7126. if err != nil {
  7127. fmt.Println("Error:", err)
  7128. return
  7129. }
  7130. // actual := actualWeight / float64(len(downloadedplanList))
  7131. for _, item := range downloadedplanList {
  7132. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7133. if err != nil {
  7134. fmt.Println("Error:", err)
  7135. return
  7136. }
  7137. actual := itemLweight / lweight * actualWeight
  7138. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7139. if err != nil {
  7140. logs.Error("UpdateDailyData-error-6:", err)
  7141. tx.Rollback()
  7142. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7143. return
  7144. }
  7145. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7146. if err != nil {
  7147. logs.Error("UpdateDailyData-error-7:", err)
  7148. tx.Rollback()
  7149. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7150. return
  7151. }
  7152. _, 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()
  7153. if err != nil {
  7154. logs.Error("UpdateDailyData-error-8:", err)
  7155. tx.Rollback()
  7156. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7157. return
  7158. }
  7159. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7160. if err != nil {
  7161. logs.Error("UpdateDailyData-error-9:", err)
  7162. tx.Rollback()
  7163. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7164. return
  7165. }
  7166. }
  7167. } else {
  7168. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7169. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7170. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7171. // if err != nil {
  7172. // fmt.Println("Error:", err)
  7173. // return
  7174. // }
  7175. for _, item := range downloadedplanList {
  7176. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7177. if err != nil {
  7178. logs.Error("UpdateDailyData-error-6:", err)
  7179. tx.Rollback()
  7180. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7181. return
  7182. }
  7183. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7184. item["lweight"], actualWeight, item["id"]).Execute()
  7185. if err != nil {
  7186. logs.Error("UpdateDailyData-error-7:", err)
  7187. tx.Rollback()
  7188. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7189. return
  7190. }
  7191. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7192. where pid = ?`, item["id"]).Execute()
  7193. if err != nil {
  7194. logs.Error("UpdateDailyData-error-8:", err)
  7195. tx.Rollback()
  7196. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7197. return
  7198. }
  7199. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7200. if err != nil {
  7201. logs.Error("UpdateDailyData-error-9:", err)
  7202. tx.Rollback()
  7203. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7204. return
  7205. }
  7206. }
  7207. }
  7208. } else {
  7209. fbarid := parammaps.Get("fbarid").ValueStr()
  7210. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7211. if err != nil {
  7212. logs.Error("UpdateDailyData-error-10:", err)
  7213. tx.Rollback()
  7214. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7215. return
  7216. }
  7217. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7218. if err != nil {
  7219. logs.Error("UpdateDailyData-error-1:", err)
  7220. tx.Rollback()
  7221. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7222. return
  7223. }
  7224. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7225. if err != nil {
  7226. fmt.Println("Error:", err)
  7227. return
  7228. }
  7229. actualWeight := weight - num
  7230. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7231. if err != nil {
  7232. logs.Error("UpdateDailyData-error-11:", err)
  7233. tx.Rollback()
  7234. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7235. return
  7236. }
  7237. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7238. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7239. if err != nil {
  7240. logs.Error("UpdateDailyData-error-12:", err)
  7241. tx.Rollback()
  7242. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7243. return
  7244. }
  7245. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7246. where pid = ? `, pid).Execute()
  7247. if err != nil {
  7248. logs.Error("UpdateDailyData-error-13:", err)
  7249. tx.Rollback()
  7250. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7251. return
  7252. }
  7253. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7254. if err != nil {
  7255. logs.Error("UpdateDailyData-error-14:", err)
  7256. tx.Rollback()
  7257. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7258. return
  7259. }
  7260. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7261. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7262. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7263. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7264. if err != nil {
  7265. fmt.Println("Error:", err)
  7266. return
  7267. }
  7268. for _, item := range downloadedplanList {
  7269. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7270. if err != nil {
  7271. fmt.Println("Error:", err)
  7272. return
  7273. }
  7274. actual := itemLweight / lweight * actualWeight
  7275. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7276. if err != nil {
  7277. logs.Error("UpdateDailyData-error-6:", err)
  7278. tx.Rollback()
  7279. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7280. return
  7281. }
  7282. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7283. if err != nil {
  7284. logs.Error("UpdateDailyData-error-7:", err)
  7285. tx.Rollback()
  7286. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7287. return
  7288. }
  7289. _, 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()
  7290. if err != nil {
  7291. logs.Error("UpdateDailyData-error-8:", err)
  7292. tx.Rollback()
  7293. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7294. return
  7295. }
  7296. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7297. if err != nil {
  7298. logs.Error("UpdateDailyData-error-9:", err)
  7299. tx.Rollback()
  7300. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7301. return
  7302. }
  7303. }
  7304. } else {
  7305. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7306. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7307. for _, item := range downloadedplanList {
  7308. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7309. // if err != nil {
  7310. // fmt.Println("Error:", err)
  7311. // return
  7312. // }
  7313. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7314. if err != nil {
  7315. logs.Error("UpdateDailyData-error-6:", err)
  7316. tx.Rollback()
  7317. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7318. return
  7319. }
  7320. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7321. item["lweight"], actualWeight, item["id"]).Execute()
  7322. if err != nil {
  7323. logs.Error("UpdateDailyData-error-7:", err)
  7324. tx.Rollback()
  7325. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7326. return
  7327. }
  7328. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7329. where pid = ?`, item["id"]).Execute()
  7330. if err != nil {
  7331. logs.Error("UpdateDailyData-error-8:", err)
  7332. tx.Rollback()
  7333. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7334. return
  7335. }
  7336. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7337. if err != nil {
  7338. logs.Error("UpdateDailyData-error-9:", err)
  7339. tx.Rollback()
  7340. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7341. return
  7342. }
  7343. }
  7344. }
  7345. }
  7346. err = tx.Commit()
  7347. if err != nil {
  7348. logs.Error("UpdateDailyData-error-20:", err)
  7349. tx.Rollback()
  7350. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7351. return
  7352. }
  7353. appG.Response(http.StatusOK, e.SUCCESS, true)
  7354. }
  7355. func GetFormulaStatistics(c *gin.Context) {
  7356. appG := app.Gin{C: c}
  7357. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7358. parammaps := gofasion.NewFasion(string(dataByte))
  7359. startTime := parammaps.Get("startTime").ValueStr()
  7360. endTime := parammaps.Get("endTime").ValueStr()
  7361. pastureId := parammaps.Get("pastureId").ValueStr()
  7362. tx := restful.Engine.NewSession()
  7363. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7364. if err != nil {
  7365. logs.Error("GetFormulaStatistics-error-1:", err)
  7366. tx.Rollback()
  7367. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7368. return
  7369. }
  7370. var feedtemplet, dateList []string
  7371. for _, f := range feedtempletList {
  7372. feedtemplet = append(feedtemplet, f["tname"].(string))
  7373. }
  7374. layout := "2006-01-02"
  7375. // s := "2023-05-01"
  7376. // e := "2023-05-23"
  7377. start, err := time.Parse(layout, startTime)
  7378. if err != nil {
  7379. fmt.Println(err)
  7380. return
  7381. }
  7382. end, err := time.Parse(layout, endTime)
  7383. if err != nil {
  7384. fmt.Println(err)
  7385. return
  7386. }
  7387. end = end.AddDate(0, 0, 1)
  7388. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7389. dateList = append(dateList, d.Format("2006-01-02"))
  7390. }
  7391. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7392. 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= ?
  7393. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7394. if err != nil {
  7395. logs.Error("GetFormulaStatistics-error-2:", err)
  7396. tx.Rollback()
  7397. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7398. return
  7399. }
  7400. var data2 [][]interface{}
  7401. for _, f := range feedtemplet {
  7402. var data1 []interface{}
  7403. for _, date := range dateList {
  7404. exist := false
  7405. for _, item := range downloadedplanList {
  7406. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7407. data1 = append(data1, item["total"])
  7408. exist = true
  7409. break
  7410. }
  7411. }
  7412. if !exist {
  7413. data1 = append(data1, 0)
  7414. }
  7415. }
  7416. data2 = append(data2, data1)
  7417. }
  7418. //前端让加的
  7419. feedtemplet = append(feedtemplet, "")
  7420. {
  7421. var data1 []interface{}
  7422. for _, f := range dateList {
  7423. // f = f + "\n"
  7424. fmt.Println(f)
  7425. data1 = append(data1, 0)
  7426. }
  7427. data2 = append(data2, data1)
  7428. }
  7429. resp := make(map[string]interface{}, 0)
  7430. resp["xdata"] = dateList
  7431. resp["data1"] = feedtemplet
  7432. resp["data2"] = data2
  7433. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7434. }
  7435. func GetPlanData(c *gin.Context) {
  7436. appG := app.Gin{C: c}
  7437. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7438. fsion := gofasion.NewFasion(string(dataByte))
  7439. sqlnamestr := fsion.Get("name").ValueStr()
  7440. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7441. offset := fsion.Get("offset").ValueDefaultInt(0)
  7442. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7443. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7444. month := fsion.Get("month").ValueDefaultStr("map")
  7445. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7446. tx := restful.Engine.NewSession()
  7447. err := tx.Begin()
  7448. defer func() {
  7449. switch {
  7450. case err != nil:
  7451. if tx != nil {
  7452. tx.Rollback()
  7453. }
  7454. default:
  7455. if tx != nil {
  7456. err = tx.Commit()
  7457. }
  7458. }
  7459. if tx != nil {
  7460. tx.Close()
  7461. }
  7462. }()
  7463. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7464. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7465. if sql != "" {
  7466. s_params := make([]interface{}, 0)
  7467. if fsion.HasKey("parammaps") {
  7468. parammaps := fsion.Get("parammaps")
  7469. paramslist := strings.Split(p, ",")
  7470. if len(paramslist) > 0 && p != "" {
  7471. for _, value := range paramslist {
  7472. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7473. if tempv, exists := c.Get("jwt_username"); exists {
  7474. s_params = append(s_params, tempv.(string))
  7475. } else {
  7476. s_params = append(s_params, "")
  7477. }
  7478. } else {
  7479. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7480. }
  7481. }
  7482. }
  7483. }
  7484. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7485. if err != nil {
  7486. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7487. } else {
  7488. paramslist1 := strings.Split(p1, ",")
  7489. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7490. s_params1 := make([]interface{}, 0)
  7491. if len(paramslist1) > 0 && p1 != "" {
  7492. for _, v := range paramslist1 {
  7493. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7494. }
  7495. }
  7496. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7497. for _, item := range arr {
  7498. trgaddressList := []string{}
  7499. if _, ok := item["trgaddress"]; ok {
  7500. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7501. for _, str := range trgaddressList1 {
  7502. if str != "" {
  7503. trgaddressList = append(trgaddressList, str)
  7504. }
  7505. }
  7506. }
  7507. item["trgaddressList"] = trgaddressList
  7508. }
  7509. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7510. }
  7511. // var wg sync.WaitGroup
  7512. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7513. // wg.Add(1)
  7514. // go func(value map[string]interface{}) {
  7515. // defer wg.Done()
  7516. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7517. // }(value)
  7518. // }
  7519. // wg.Wait()
  7520. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7521. }
  7522. } else {
  7523. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7524. }
  7525. }
  7526. func PostPlanData(c *gin.Context) {
  7527. appG := app.Gin{C: c}
  7528. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7529. fsion := gofasion.NewFasion(string(dataByte))
  7530. logging.Info("PostRJSBData err: ", string(dataByte))
  7531. s_params := make([]interface{}, 0)
  7532. tx := restful.Engine.NewSession()
  7533. err := tx.Begin()
  7534. defer func() {
  7535. switch {
  7536. case err != nil:
  7537. if tx != nil {
  7538. tx.Rollback()
  7539. }
  7540. default:
  7541. if tx != nil {
  7542. err = tx.Commit()
  7543. }
  7544. }
  7545. if tx != nil {
  7546. tx.Close()
  7547. }
  7548. }()
  7549. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7550. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7551. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7552. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7553. if !fsion.HasKey("parammaps") {
  7554. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7555. return
  7556. }
  7557. parammaps := fsion.Get("parammaps")
  7558. // paramslist := strings.Split(p, ",")
  7559. // if len(paramslist) > 0 && p != "" {
  7560. // for _, value := range paramslist {
  7561. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7562. // }
  7563. // }
  7564. // _, err = tx.SQL(sql, s_params...).Execute()
  7565. // if err != nil {
  7566. // logging.Error("PostRJSBData err: ", err)
  7567. // msg := geterrmsg(err.Error())
  7568. // appG.Response(http.StatusOK, e.ERROR, msg)
  7569. // return
  7570. // }
  7571. s_params = make([]interface{}, 0)
  7572. paramslist := strings.Split(p1, ",")
  7573. if len(paramslist) > 0 && p1 != "" {
  7574. for _, value := range paramslist {
  7575. // if value == "ID" {
  7576. // id := parammaps.Get("ID").ValueStr()
  7577. // pastureid := parammaps.Get("pastureid").ValueStr()
  7578. // 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
  7579. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7580. // if err != nil {
  7581. // logging.Error("PostRJSBData err: ", err)
  7582. // msg := geterrmsg(err.Error())
  7583. // appG.Response(http.StatusOK, e.ERROR, msg)
  7584. // return
  7585. // }
  7586. // for _, item := range datalist {
  7587. // id = item["id"]
  7588. // }
  7589. // s_params = append(s_params, id)
  7590. // } else {
  7591. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7592. // }
  7593. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7594. }
  7595. }
  7596. _, err = tx.SQL(sql1, s_params...).Execute()
  7597. if err != nil {
  7598. logging.Error("PostRJSBData1 err: ", err)
  7599. msg := geterrmsg(err.Error())
  7600. appG.Response(http.StatusOK, e.ERROR, msg)
  7601. return
  7602. }
  7603. s_params = make([]interface{}, 0)
  7604. paramslist = strings.Split(p2, ",")
  7605. if len(paramslist) > 0 && p2 != "" {
  7606. for _, value := range paramslist {
  7607. if value == "ID" {
  7608. id := parammaps.Get("ID").ValueStr()
  7609. pastureid := parammaps.Get("pastureid").ValueStr()
  7610. 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
  7611. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7612. if err != nil {
  7613. logging.Error("PostRJSBData err: ", err)
  7614. msg := geterrmsg(err.Error())
  7615. appG.Response(http.StatusOK, e.ERROR, msg)
  7616. return
  7617. }
  7618. for _, item := range datalist {
  7619. id = item["id"]
  7620. }
  7621. s_params = append(s_params, id)
  7622. } else {
  7623. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7624. }
  7625. }
  7626. }
  7627. _, err = tx.SQL(sql2, s_params...).Execute()
  7628. if err != nil {
  7629. logging.Error("PostRJSBData2 err: ", err)
  7630. msg := geterrmsg(err.Error())
  7631. appG.Response(http.StatusOK, e.ERROR, msg)
  7632. return
  7633. }
  7634. s_params = make([]interface{}, 0)
  7635. paramslist = strings.Split(p3, ",")
  7636. if len(paramslist) > 0 && p3 != "" {
  7637. for _, value := range paramslist {
  7638. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7639. }
  7640. }
  7641. _, err = tx.SQL(sql3, s_params...).Execute()
  7642. if err != nil {
  7643. logging.Error("PostRJSBData3 err: ", err)
  7644. msg := geterrmsg(err.Error())
  7645. appG.Response(http.StatusOK, e.ERROR, msg)
  7646. return
  7647. }
  7648. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7649. }
  7650. func CheckFeedTrgaddress(c *gin.Context) {
  7651. appG := app.Gin{C: c}
  7652. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7653. fsion := gofasion.NewFasion(string(dataByte))
  7654. fclassid := fsion.Get("fclassid").ValueStr()
  7655. feedId := fsion.Get("feedId").ValueStr()
  7656. backup1 := fsion.Get("backup1").ValueStr()
  7657. backup1List := strings.Split(backup1, ",")
  7658. tx := restful.Engine.NewSession()
  7659. defer tx.Close()
  7660. // if backup1 != "" {
  7661. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7662. for _, feed := range feedList {
  7663. if feed["backup1"] == "" {
  7664. continue
  7665. }
  7666. feedbackupList := strings.Split(feed["backup1"], ",")
  7667. for _, feedbackup := range feedbackupList {
  7668. for _, backup := range backup1List {
  7669. if feedbackup == backup {
  7670. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7671. return
  7672. }
  7673. }
  7674. }
  7675. }
  7676. // }
  7677. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7678. }
  7679. func ThiGetDataByName(c *gin.Context) {
  7680. appG := app.Gin{C: c}
  7681. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7682. fsion := gofasion.NewFasion(string(dataByte))
  7683. sqlnamestr := fsion.Get("name").ValueStr()
  7684. offset := fsion.Get("offset").ValueDefaultInt(0)
  7685. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7686. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7687. tx := restful.Engine.NewSession()
  7688. err := tx.Begin()
  7689. defer func() {
  7690. switch {
  7691. case err != nil:
  7692. logging.Error("tx.Begin 事务启动失败__error:", err)
  7693. if tx != nil {
  7694. tx.Rollback()
  7695. }
  7696. default:
  7697. if tx != nil {
  7698. err = tx.Commit()
  7699. }
  7700. }
  7701. if tx != nil {
  7702. tx.Close()
  7703. }
  7704. }()
  7705. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7706. if sql != "" {
  7707. s_params := make([]interface{}, 0)
  7708. if fsion.HasKey("parammaps") {
  7709. parammaps := fsion.Get("parammaps")
  7710. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7711. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7712. }
  7713. paramslist := strings.Split(p, ",")
  7714. if len(paramslist) > 0 && p != "" {
  7715. for _, value := range paramslist {
  7716. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7717. if tempv, exists := c.Get("jwt_username"); exists {
  7718. s_params = append(s_params, tempv.(string))
  7719. } else {
  7720. s_params = append(s_params, "")
  7721. }
  7722. } else {
  7723. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7724. }
  7725. }
  7726. }
  7727. } else if fsion.HasKey("params") {
  7728. params := fsion.Get("params").Array()
  7729. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7730. for _, v_params := range params {
  7731. s_params = append(s_params, v_params.ValueStr())
  7732. }
  7733. }
  7734. if returntype == "xlsx" {
  7735. var xlsxfile *xlsx.File
  7736. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7737. //c.File("c:/dd.xlsx")
  7738. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7739. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7740. c.Header("Content-Transfer-Encoding", "binary")
  7741. _ = xlsxfile.Write(c.Writer)
  7742. } else {
  7743. if sqlnamestr == "getHomepageStr" {
  7744. parammaps := fsion.Get("parammaps")
  7745. pastureid := parammaps.Get("pastureid").ValueStr()
  7746. var montimeList []float64
  7747. var montime float64
  7748. var wg sync.WaitGroup
  7749. now := time.Now()
  7750. for i := 0; i < 30; i++ {
  7751. wg.Add(1)
  7752. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7753. go func(nowstr string) {
  7754. defer wg.Done()
  7755. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7756. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7757. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7758. montimeList = append(montimeList, m)
  7759. }(nowstr)
  7760. }
  7761. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7762. if err != nil {
  7763. logging.Error("GetDataByName err: ", err)
  7764. msg := geterrmsg(err.Error())
  7765. appG.Response(http.StatusOK, e.ERROR, msg)
  7766. }
  7767. wg.Wait()
  7768. for _, m := range montimeList {
  7769. montime += m
  7770. }
  7771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7772. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7773. return
  7774. }
  7775. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7776. if err != nil {
  7777. logging.Error("GetDataByName err: ", err)
  7778. msg := geterrmsg(err.Error())
  7779. appG.Response(http.StatusOK, e.ERROR, msg)
  7780. } else {
  7781. if sqlnamestr == "getFeedTrgaddressList" {
  7782. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7783. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7784. trgaddressList := []string{}
  7785. for _, str := range trgaddressList1 {
  7786. if str != "" {
  7787. trgaddressList = append(trgaddressList, str)
  7788. }
  7789. }
  7790. item["trgaddressList"] = trgaddressList
  7791. }
  7792. }
  7793. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7794. }
  7795. }
  7796. } else {
  7797. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7798. }
  7799. }
  7800. // func ToggleCcount(c *gin.Context) {
  7801. // appG := app.Gin{C: c}
  7802. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7803. // fsion := gofasion.NewFasion(string(dataByte))
  7804. // // 0 实际 1 软件
  7805. // status := fsion.Get("status").ValueDefaultInt64(0)
  7806. // pastureId := fsion.Get("pastureId").ValueStr()
  7807. // tx := restful.Engine.NewSession()
  7808. // err := tx.Begin()
  7809. // defer func() {
  7810. // switch {
  7811. // case err != nil:
  7812. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7813. // if tx != nil {
  7814. // tx.Rollback()
  7815. // }
  7816. // default:
  7817. // if tx != nil {
  7818. // err = tx.Commit()
  7819. // }
  7820. // }
  7821. // if tx != nil {
  7822. // tx.Close()
  7823. // }
  7824. // }()
  7825. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7826. // if err != nil {
  7827. // logs.Error(err)
  7828. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7829. // return
  7830. // }
  7831. // for _, bar := range barList {
  7832. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7833. // if err != nil {
  7834. // logs.Error(err)
  7835. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7836. // return
  7837. // }
  7838. // if !exist {
  7839. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7840. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7841. // if err != nil {
  7842. // logs.Error(err)
  7843. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7844. // return
  7845. // }
  7846. // }
  7847. // }
  7848. // if status == 0 {
  7849. // tx.Exec(`update feedp set ccount = actualcount `)
  7850. // }else{
  7851. // tx.Exec(`update feedp set ccount = softccount `)
  7852. // }
  7853. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7854. // if err != nil {
  7855. // logs.Error(err)
  7856. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7857. // return
  7858. // }
  7859. // for _, feedpData :=range feedpList{
  7860. // var feedpargs []interface{}
  7861. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7862. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7863. // if _, ok := feedpData["ftname"]; ok {
  7864. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7865. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7866. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7867. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7868. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7869. // } else {
  7870. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7871. // }
  7872. // if _, ok := feedpData["ptsfname"]; ok {
  7873. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7874. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7875. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7876. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7877. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7878. // } else {
  7879. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7880. // }
  7881. // upFeedpSql += " where barname = ? and pastureid = ? "
  7882. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7883. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7884. // if err != nil {
  7885. // logs.Error(err)
  7886. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7887. // return
  7888. // }
  7889. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7890. // if err != nil {
  7891. // logs.Error(err)
  7892. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7893. // return
  7894. // }
  7895. // if !exist1 {
  7896. // _, 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) `,
  7897. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7898. // if err != nil {
  7899. // logs.Error(err)
  7900. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7901. // return
  7902. // }
  7903. // }
  7904. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7905. // if err != nil {
  7906. // logs.Error(err)
  7907. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7908. // return
  7909. // }
  7910. // if !exist2 {
  7911. // _, 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) `,
  7912. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7913. // if err != nil {
  7914. // logs.Error(err)
  7915. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7916. // return
  7917. // }
  7918. // }
  7919. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7920. // if err != nil {
  7921. // logs.Error(err)
  7922. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7923. // return
  7924. // }
  7925. // if !exist3 {
  7926. // _, 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) `,
  7927. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7928. // if err != nil {
  7929. // logs.Error(err)
  7930. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7931. // return
  7932. // }
  7933. // }
  7934. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7935. // if err != nil {
  7936. // logs.Error(err)
  7937. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7938. // return
  7939. // }
  7940. // if !exist4 {
  7941. // _, 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) `,
  7942. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7943. // if err != nil {
  7944. // logs.Error(err)
  7945. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7946. // return
  7947. // }
  7948. // }
  7949. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7950. // if err != nil {
  7951. // logs.Error(err)
  7952. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7953. // return
  7954. // }
  7955. // if !exist5 {
  7956. // _, 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) `,
  7957. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7958. // if err != nil {
  7959. // logs.Error(err)
  7960. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7961. // return
  7962. // }
  7963. // }
  7964. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7965. // if err != nil {
  7966. // logs.Error(err)
  7967. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7968. // return
  7969. // }
  7970. // if !exist6 {
  7971. // _, 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) `,
  7972. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7973. // if err != nil {
  7974. // logs.Error(err)
  7975. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7976. // return
  7977. // }
  7978. // }
  7979. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7980. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7981. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7982. // and pastureid = ? and times = ?`
  7983. // var fpdargs1 []interface{}
  7984. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7985. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7986. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7987. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7988. // if err != nil {
  7989. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7990. // return
  7991. // }
  7992. // var fpdargs2 []interface{}
  7993. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7994. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7995. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7996. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7997. // if err != nil {
  7998. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7999. // return
  8000. // }
  8001. // var fpdargs3 []interface{}
  8002. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8003. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8004. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8005. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8006. // if err != nil {
  8007. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8008. // return
  8009. // }
  8010. // var fpdargs4 []interface{}
  8011. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8012. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8013. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8014. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8015. // if err != nil {
  8016. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8017. // return
  8018. // }
  8019. // var fpdargs5 []interface{}
  8020. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8021. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8022. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8023. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8024. // if err != nil {
  8025. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8026. // return
  8027. // }
  8028. // var fpdargs6 []interface{}
  8029. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8030. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8031. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8032. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8033. // if err != nil {
  8034. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8035. // return
  8036. // }
  8037. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8038. // 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()
  8039. // if err != nil {
  8040. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8041. // return
  8042. // }
  8043. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8044. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8045. // upFpdetailList := make([]*upFpdetail, 0)
  8046. // for _, newfpd := range newList {
  8047. // for _, oldfpd := range oldFpdList {
  8048. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8049. // var oldweight, newweight float64
  8050. // if oldfpd["weight"] != nil {
  8051. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8052. // }
  8053. // if newfpd["weight"] != nil {
  8054. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8055. // }
  8056. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8057. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8058. // Old: oldweight,
  8059. // New: newweight,
  8060. // Times: newfpd["times"].(int64),
  8061. // Ptid: newfpd["ptid"].(int64),
  8062. // Fweight: fweight,
  8063. // Id: oldfpd["id"].(int64),
  8064. // })
  8065. // break
  8066. // }
  8067. // }
  8068. // }
  8069. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8070. // }
  8071. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8072. // }
  8073. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8074. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8075. if err != nil {
  8076. return err
  8077. }
  8078. for _, item := range feedpList {
  8079. // if item["ftid"].(string) != data["ftid"].(string) {
  8080. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8081. if err != nil {
  8082. return err
  8083. }
  8084. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8085. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8086. if err != nil {
  8087. return err
  8088. }
  8089. // }
  8090. }
  8091. return nil
  8092. }
  8093. func PostPlanDatas(c *gin.Context) {
  8094. appG := app.Gin{C: c}
  8095. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8096. fsions := gofasion.NewFasion(string(dataByte))
  8097. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8098. tx := restful.Engine.NewSession()
  8099. err := tx.Begin()
  8100. defer func() {
  8101. switch {
  8102. case err != nil:
  8103. if tx != nil {
  8104. tx.Rollback()
  8105. }
  8106. default:
  8107. if tx != nil {
  8108. err = tx.Commit()
  8109. }
  8110. }
  8111. if tx != nil {
  8112. tx.Close()
  8113. }
  8114. }()
  8115. pastureId := fsions.Get("pastureid").ValueStr()
  8116. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8117. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8118. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8119. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8120. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8121. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8122. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8123. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8124. for _, parammaps := range fsions.Get("arrList").Array() {
  8125. fmt.Println(parammaps.Json())
  8126. if parammaps.Json() == "null" {
  8127. continue
  8128. }
  8129. // if !fsion.HasKey("arrList") {
  8130. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8131. // return
  8132. // continue
  8133. // }
  8134. // parammaps := fsion.Get("arrList")
  8135. s_params := make([]interface{}, 0)
  8136. // paramslist := strings.Split(p, ",")
  8137. // if len(paramslist) > 0 && p != "" {
  8138. // for _, value := range paramslist {
  8139. // if value == "pastureid" {
  8140. // s_params = append(s_params, pastureId)
  8141. // } else {
  8142. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8143. // }
  8144. // }
  8145. // }
  8146. // _, err = tx.SQL(sql, s_params...).Execute()
  8147. // if err != nil {
  8148. // logging.Error("PostRJSBData err: ", err)
  8149. // msg := geterrmsg(err.Error())
  8150. // appG.Response(http.StatusOK, e.ERROR, msg)
  8151. // return
  8152. // }
  8153. s_params = make([]interface{}, 0)
  8154. paramslist := strings.Split(p1, ",")
  8155. if len(paramslist) > 0 && p1 != "" {
  8156. for _, value := range paramslist {
  8157. // if value == "ID" {
  8158. // id := parammaps.Get("ID").ValueStr()
  8159. // pastureid := parammaps.Get("pastureid").ValueStr()
  8160. // 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
  8161. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8162. // if err != nil {
  8163. // logging.Error("PostRJSBData err: ", err)
  8164. // msg := geterrmsg(err.Error())
  8165. // appG.Response(http.StatusOK, e.ERROR, msg)
  8166. // return
  8167. // }
  8168. // for _, item := range datalist {
  8169. // id = item["id"]
  8170. // }
  8171. // s_params = append(s_params, id)
  8172. // } else {
  8173. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8174. // }
  8175. if value == "pastureid" {
  8176. s_params = append(s_params, pastureId)
  8177. } else {
  8178. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8179. }
  8180. }
  8181. }
  8182. _, err = tx.SQL(sql1, s_params...).Execute()
  8183. if err != nil {
  8184. logging.Error("PostRJSBData1 err: ", err)
  8185. msg := geterrmsg(err.Error())
  8186. appG.Response(http.StatusOK, e.ERROR, msg)
  8187. return
  8188. }
  8189. s_params = make([]interface{}, 0)
  8190. paramslist = strings.Split(p2, ",")
  8191. if len(paramslist) > 0 && p2 != "" {
  8192. for _, value := range paramslist {
  8193. if value == "ID" {
  8194. id := parammaps.Get("ID").ValueStr()
  8195. pastureid := parammaps.Get("pastureid").ValueStr()
  8196. 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
  8197. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8198. if err != nil {
  8199. logging.Error("PostRJSBData err: ", err)
  8200. msg := geterrmsg(err.Error())
  8201. appG.Response(http.StatusOK, e.ERROR, msg)
  8202. return
  8203. }
  8204. for _, item := range datalist {
  8205. id = item["id"]
  8206. }
  8207. s_params = append(s_params, id)
  8208. } else 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. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8214. }
  8215. }
  8216. _, err = tx.SQL(sql2, s_params...).Execute()
  8217. if err != nil {
  8218. logging.Error("PostRJSBData2 err: ", err)
  8219. msg := geterrmsg(err.Error())
  8220. appG.Response(http.StatusOK, e.ERROR, msg)
  8221. return
  8222. }
  8223. s_params = make([]interface{}, 0)
  8224. paramslist = strings.Split(p3, ",")
  8225. if len(paramslist) > 0 && p3 != "" {
  8226. for _, value := range paramslist {
  8227. if value == "pastureid" {
  8228. s_params = append(s_params, pastureId)
  8229. } else {
  8230. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8231. }
  8232. }
  8233. }
  8234. _, err = tx.SQL(sql3, s_params...).Execute()
  8235. if err != nil {
  8236. logging.Error("PostRJSBData3 err: ", err)
  8237. msg := geterrmsg(err.Error())
  8238. appG.Response(http.StatusOK, e.ERROR, msg)
  8239. return
  8240. }
  8241. }
  8242. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8243. }
  8244. func FpdBatchEdit(c *gin.Context) {
  8245. appG := app.Gin{C: c}
  8246. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8247. fsions := gofasion.NewFasion(string(dataByte))
  8248. barList := fsions.Get("barList").Array()
  8249. pastureid := fsions.Get("pastureId").ValueStr()
  8250. tx := restful.Engine.NewSession()
  8251. defer tx.Close()
  8252. 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
  8253. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8254. if err != nil {
  8255. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8256. return
  8257. }
  8258. for _, barFsions := range barList {
  8259. dataexcel := make(map[string]interface{}, 0)
  8260. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8261. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8262. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8263. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8264. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8265. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8266. continue
  8267. }
  8268. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8269. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8270. // if err != nil {
  8271. // logs.Error(err)
  8272. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8273. // return
  8274. // }
  8275. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8276. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8277. // if err != nil {
  8278. // logs.Error(err)
  8279. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8280. // return
  8281. // }
  8282. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8283. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8284. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8285. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8286. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8287. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8288. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8289. if err != nil {
  8290. logs.Error(err)
  8291. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8292. return
  8293. }
  8294. if !ftexist {
  8295. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8296. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8297. if err != nil {
  8298. logs.Error(err)
  8299. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8300. return
  8301. }
  8302. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8303. if err != nil {
  8304. logs.Error(err)
  8305. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8306. return
  8307. }
  8308. }
  8309. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8310. if err != nil {
  8311. logs.Error(err)
  8312. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8313. return
  8314. }
  8315. if !exist {
  8316. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8317. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8318. if err != nil {
  8319. logs.Error(err)
  8320. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8321. return
  8322. }
  8323. }
  8324. var feedpargs []interface{}
  8325. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8326. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8327. if _, ok := dataexcel["ftname"]; ok {
  8328. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8329. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8330. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8331. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8332. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8333. } else {
  8334. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8335. }
  8336. if _, ok := dataexcel["ptsfname"]; ok {
  8337. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8338. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8339. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8340. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8341. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8342. } else {
  8343. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8344. }
  8345. upFeedpSql += " where barname = ? and pastureid = ? "
  8346. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8347. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8348. if err != nil {
  8349. logs.Error(err)
  8350. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8351. return
  8352. }
  8353. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8354. if err != nil {
  8355. logs.Error(err)
  8356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8357. return
  8358. }
  8359. if !exist1 {
  8360. _, 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) `,
  8361. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8362. if err != nil {
  8363. logs.Error(err)
  8364. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8365. return
  8366. }
  8367. }
  8368. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8369. if err != nil {
  8370. logs.Error(err)
  8371. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8372. return
  8373. }
  8374. if !exist2 {
  8375. _, 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) `,
  8376. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8377. if err != nil {
  8378. logs.Error(err)
  8379. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8380. return
  8381. }
  8382. }
  8383. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8384. if err != nil {
  8385. logs.Error(err)
  8386. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8387. return
  8388. }
  8389. if !exist3 {
  8390. _, 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) `,
  8391. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8392. if err != nil {
  8393. logs.Error(err)
  8394. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8395. return
  8396. }
  8397. }
  8398. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8399. if err != nil {
  8400. logs.Error(err)
  8401. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8402. return
  8403. }
  8404. if !exist4 {
  8405. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  8406. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8407. if err != nil {
  8408. logs.Error(err)
  8409. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8410. return
  8411. }
  8412. }
  8413. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8414. if err != nil {
  8415. logs.Error(err)
  8416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8417. return
  8418. }
  8419. if !exist5 {
  8420. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  8421. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8422. if err != nil {
  8423. logs.Error(err)
  8424. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8425. return
  8426. }
  8427. }
  8428. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8429. if err != nil {
  8430. logs.Error(err)
  8431. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8432. return
  8433. }
  8434. if !exist6 {
  8435. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  8436. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8437. if err != nil {
  8438. logs.Error(err)
  8439. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8440. return
  8441. }
  8442. }
  8443. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8444. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8445. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8446. and pastureid = ? and times = ?`
  8447. var fpdargs1 []interface{}
  8448. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8449. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8450. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8451. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8452. if err != nil {
  8453. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8454. return
  8455. }
  8456. var fpdargs2 []interface{}
  8457. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8458. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8459. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8460. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8461. if err != nil {
  8462. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8463. return
  8464. }
  8465. var fpdargs3 []interface{}
  8466. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8467. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8468. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8469. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8470. if err != nil {
  8471. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8472. return
  8473. }
  8474. var fpdargs4 []interface{}
  8475. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8476. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8477. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8478. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8479. if err != nil {
  8480. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8481. return
  8482. }
  8483. var fpdargs5 []interface{}
  8484. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8485. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8486. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8487. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8488. if err != nil {
  8489. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8490. return
  8491. }
  8492. var fpdargs6 []interface{}
  8493. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8494. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8495. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8496. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8497. if err != nil {
  8498. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8499. return
  8500. }
  8501. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8502. 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()
  8503. if err != nil {
  8504. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8505. return
  8506. }
  8507. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8508. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8509. upFpdetailList := make([]*upFpdetail, 0)
  8510. for _, newfpd := range newList {
  8511. for _, oldfpd := range oldFpdList {
  8512. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8513. var oldweight, newweight float64
  8514. if oldfpd["weight"] != nil {
  8515. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8516. }
  8517. if newfpd["weight"] != nil {
  8518. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8519. }
  8520. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8521. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8522. Old: oldweight,
  8523. New: newweight,
  8524. Times: newfpd["times"].(int64),
  8525. Ptid: newfpd["ptid"].(int64),
  8526. Fweight: fweight,
  8527. Id: oldfpd["id"].(int64),
  8528. })
  8529. break
  8530. }
  8531. }
  8532. }
  8533. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8534. }
  8535. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8536. }
  8537. func UdBarSync(c *gin.Context) {
  8538. appG := app.Gin{C: c}
  8539. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8540. fsions := gofasion.NewFasion(string(dataByte))
  8541. pastureid := fsions.Get("pastureId").ValueStr()
  8542. tx := restful.Engine.NewSession()
  8543. defer tx.Close()
  8544. pastureinfo := new(udPastureInfo)
  8545. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8546. if err != nil {
  8547. logs.Error(err)
  8548. return
  8549. }
  8550. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8551. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8552. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8553. }
  8554. func UdFeedSync(c *gin.Context) {
  8555. appG := app.Gin{C: c}
  8556. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8557. fsions := gofasion.NewFasion(string(dataByte))
  8558. pastureid := fsions.Get("pastureId").ValueStr()
  8559. tx := restful.Engine.NewSession()
  8560. defer tx.Close()
  8561. pastureinfo := new(udPastureInfo)
  8562. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8563. if err != nil {
  8564. logs.Error(err)
  8565. return
  8566. }
  8567. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8568. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8569. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8570. }
  8571. func UdFeedtempletPush(c *gin.Context) {
  8572. appG := app.Gin{C: c}
  8573. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8574. fsions := gofasion.NewFasion(string(dataByte))
  8575. pastureid := fsions.Get("pastureId").ValueStr()
  8576. date := fsions.Get("date").ValueStr()
  8577. tx := restful.Engine.NewSession()
  8578. defer tx.Close()
  8579. pastureinfo := new(udPastureInfo)
  8580. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8581. if err != nil {
  8582. logs.Error(err)
  8583. return
  8584. }
  8585. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8586. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8587. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8588. }
  8589. func UdUtirPush(c *gin.Context) {
  8590. appG := app.Gin{C: c}
  8591. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8592. fsions := gofasion.NewFasion(string(dataByte))
  8593. pastureid := fsions.Get("pastureId").ValueStr()
  8594. date := fsions.Get("date").ValueStr()
  8595. tx := restful.Engine.NewSession()
  8596. defer tx.Close()
  8597. pastureinfo := new(udPastureInfo)
  8598. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8599. if err != nil {
  8600. logs.Error(err)
  8601. return
  8602. }
  8603. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8604. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8605. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8606. }
  8607. func UdBarFeedRemainPush(c *gin.Context) {
  8608. appG := app.Gin{C: c}
  8609. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8610. fsions := gofasion.NewFasion(string(dataByte))
  8611. pastureid := fsions.Get("pastureId").ValueStr()
  8612. date := fsions.Get("date").ValueStr()
  8613. tx := restful.Engine.NewSession()
  8614. defer tx.Close()
  8615. pastureinfo := new(udPastureInfo)
  8616. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8617. if err != nil {
  8618. logs.Error(err)
  8619. return
  8620. }
  8621. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8622. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8623. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8624. }
  8625. func UdMaterialIssuePush(c *gin.Context) {
  8626. appG := app.Gin{C: c}
  8627. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8628. fsions := gofasion.NewFasion(string(dataByte))
  8629. pastureid := fsions.Get("pastureId").ValueStr()
  8630. date := fsions.Get("date").ValueStr()
  8631. tx := restful.Engine.NewSession()
  8632. defer tx.Close()
  8633. pastureinfo := new(udPastureInfo)
  8634. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8635. if err != nil {
  8636. logs.Error(err)
  8637. return
  8638. }
  8639. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8640. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8641. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8642. }
  8643. func DelFeedTemplet(c *gin.Context) {
  8644. appG := app.Gin{C: c}
  8645. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8646. fsions := gofasion.NewFasion(string(dataByte))
  8647. ftId := fsions.Get("ftId").ValueStr()
  8648. // userId := fsions.Get("userId").ValueStr()
  8649. tx := restful.Engine.NewSession()
  8650. defer tx.Close()
  8651. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8652. if err != nil {
  8653. logs.Error(err)
  8654. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8655. return
  8656. }
  8657. /*
  8658. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8659. if err != nil {
  8660. logs.Error(err)
  8661. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8662. return
  8663. }
  8664. */
  8665. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8666. if err != nil {
  8667. logs.Error(err)
  8668. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8669. return
  8670. }
  8671. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8672. if err != nil {
  8673. logs.Error(err)
  8674. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8675. return
  8676. }
  8677. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8678. if count > 0 {
  8679. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8680. if err != nil {
  8681. logs.Error(err)
  8682. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8683. return
  8684. }
  8685. }
  8686. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8687. if err != nil {
  8688. logs.Error(err)
  8689. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8690. return
  8691. }
  8692. // var barIdStr []string
  8693. // for _, bar := range barIdList {
  8694. // barIdStr = append(barIdStr, bar["barid"])
  8695. // }
  8696. // if len(barIdStr) > 0 {
  8697. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8698. // if err != nil {
  8699. // logs.Error(err)
  8700. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8701. // return
  8702. // }
  8703. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8704. // if err != nil {
  8705. // logs.Error(err)
  8706. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8707. // return
  8708. // }
  8709. // now := time.Now()
  8710. // for _, newFpd := range newFpdDataList {
  8711. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8712. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8713. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8714. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8715. // if err != nil {
  8716. // logs.Error(err)
  8717. // appG.Response(http.StatusOK, e.ERROR, false)
  8718. // return
  8719. // }
  8720. // }
  8721. // for _, newFeedp := range newFeedpList {
  8722. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8723. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8724. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8725. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8726. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8727. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8728. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8729. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8730. // if err != nil {
  8731. // logs.Error(err)
  8732. // appG.Response(http.StatusOK, e.ERROR, false)
  8733. // return
  8734. // }
  8735. // }
  8736. // }
  8737. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8738. }
  8739. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8740. data := fasion["parammaps"].(map[string]interface{})
  8741. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8742. fmt.Println(err)
  8743. plancount1, err := tx.SQL(`SELECT
  8744. count( 1 )
  8745. FROM
  8746. (
  8747. SELECT
  8748. d.id
  8749. FROM
  8750. downloadedplan d
  8751. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8752. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8753. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8754. WHERE
  8755. d.mydate = ?
  8756. AND d.havebutton = 0
  8757. AND lpplantype IN ( 0, 1, 2 )
  8758. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8759. ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 and dd2.fname = d2.fname )
  8760. GROUP BY
  8761. d.id
  8762. ) d
  8763. `,
  8764. data["startTime"]).Count()
  8765. fmt.Println(err)
  8766. if plancount != plancount1 && number < 10 {
  8767. number++
  8768. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8769. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8770. }
  8771. }
  8772. func EditPlanSort(c *gin.Context) {
  8773. appG := app.Gin{C: c}
  8774. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8775. fsions := gofasion.NewFasion(string(dataByte))
  8776. planIdStr := fsions.Get("planId").ValueStr()
  8777. mydate := fsions.Get("mydate").ValueStr()
  8778. sort := fsions.Get("sort").ValueStr()
  8779. tx := restful.Engine.NewSession()
  8780. defer tx.Close()
  8781. tx.Begin()
  8782. type downloadedplan struct {
  8783. Id int64 `xorm:"id"`
  8784. Sort int `xorm:"sort"`
  8785. Pid int64 `xorm:"pid"`
  8786. }
  8787. planInfo := new(downloadedplan)
  8788. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8789. if err != nil {
  8790. logs.Error(err)
  8791. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8792. tx.Rollback()
  8793. return
  8794. }
  8795. sort1, _ := strconv.Atoi(sort)
  8796. if sort1 == planInfo.Sort {
  8797. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8798. tx.Rollback()
  8799. return
  8800. }
  8801. 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()
  8802. if err != nil {
  8803. logs.Error(err)
  8804. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8805. tx.Rollback()
  8806. return
  8807. }
  8808. if count1 == 0 {
  8809. tx.Rollback()
  8810. logs.Error(err)
  8811. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8812. return
  8813. }
  8814. 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()
  8815. if err != nil {
  8816. logs.Error(err)
  8817. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8818. tx.Rollback()
  8819. return
  8820. }
  8821. if count > 0 {
  8822. tx.Rollback()
  8823. logs.Error(err)
  8824. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8825. return
  8826. }
  8827. if planInfo.Sort > sort1 {
  8828. 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()
  8829. if err != nil {
  8830. logs.Error(err)
  8831. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8832. tx.Rollback()
  8833. return
  8834. }
  8835. var minSort, pidCount int
  8836. for _, sort := range minSortList {
  8837. minSort, _ = strconv.Atoi(sort["sort"])
  8838. }
  8839. planList := make([]*downloadedplan, 0)
  8840. 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)
  8841. if err != nil {
  8842. logs.Error(err)
  8843. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8844. tx.Rollback()
  8845. return
  8846. }
  8847. planPid := planInfo.Pid
  8848. planList1 := make([]*downloadedplan, 0)
  8849. planList2 := make([]*downloadedplan, 0)
  8850. for _, plan := range planList {
  8851. if plan.Pid == planPid {
  8852. pidCount++
  8853. planList1 = append(planList1, plan)
  8854. } else {
  8855. planList2 = append(planList2, plan)
  8856. }
  8857. }
  8858. planList1 = append(planList1, planList2...)
  8859. for i, plan := range planList1 {
  8860. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8861. if err != nil {
  8862. logs.Error(err)
  8863. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8864. tx.Rollback()
  8865. return
  8866. }
  8867. }
  8868. } else {
  8869. 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()
  8870. if err != nil {
  8871. logs.Error(err)
  8872. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8873. tx.Rollback()
  8874. return
  8875. }
  8876. var maxSort int
  8877. for _, sort := range maxSortList {
  8878. maxSort, _ = strconv.Atoi(sort["sort"])
  8879. }
  8880. planList := make([]*downloadedplan, 0)
  8881. 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)
  8882. if err != nil {
  8883. logs.Error(err)
  8884. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8885. tx.Rollback()
  8886. return
  8887. }
  8888. planPid := planInfo.Pid
  8889. planList1 := make([]*downloadedplan, 0)
  8890. planList2 := make([]*downloadedplan, 0)
  8891. for _, plan := range planList {
  8892. if plan.Pid == planPid {
  8893. // pidCount++
  8894. planList1 = append(planList1, plan)
  8895. } else {
  8896. planList2 = append(planList2, plan)
  8897. }
  8898. }
  8899. planList2 = append(planList2, planList1...)
  8900. for i, plan := range planList2 {
  8901. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  8902. if err != nil {
  8903. logs.Error(err)
  8904. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8905. tx.Rollback()
  8906. return
  8907. }
  8908. }
  8909. }
  8910. err = tx.Commit()
  8911. if err != nil {
  8912. logs.Error(err)
  8913. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8914. tx.Rollback()
  8915. return
  8916. }
  8917. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8918. }
  8919. func EditDownloadedplanArtificial(c *gin.Context) {
  8920. appG := app.Gin{C: c}
  8921. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8922. fsions := gofasion.NewFasion(string(dataByte))
  8923. planIdStr := fsions.Get("planId").ValueStr()
  8924. tx := restful.Engine.NewSession()
  8925. defer tx.Close()
  8926. tx.Begin()
  8927. planIdList := strings.Split(planIdStr, ",")
  8928. for _, planId := range planIdList {
  8929. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8930. if err != nil {
  8931. logs.Error(err)
  8932. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8933. tx.Rollback()
  8934. return
  8935. }
  8936. }
  8937. err := tx.Commit()
  8938. if err != nil {
  8939. logs.Error(err)
  8940. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8941. tx.Rollback()
  8942. return
  8943. }
  8944. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8945. }
  8946. type PlanRFID struct {
  8947. RFID string `json:"RFID"`
  8948. Lweight string `json:"lweight"`
  8949. Gear string `json:"gear"`
  8950. Speed string `json:"speed"`
  8951. }
  8952. func GetPlanRFID(c *gin.Context) {
  8953. appG := app.Gin{C: c}
  8954. RFIDStr := c.Query("RFID")
  8955. planRFIDList := make([]*PlanRFID, 0)
  8956. planRFIDList = append(planRFIDList, &PlanRFID{
  8957. RFID: RFIDStr,
  8958. Lweight: "1411.1",
  8959. Gear: "1",
  8960. Speed: "10",
  8961. })
  8962. planRFIDList = append(planRFIDList, &PlanRFID{
  8963. RFID: RFIDStr,
  8964. Lweight: "1322.1",
  8965. Gear: "1",
  8966. Speed: "10",
  8967. })
  8968. planRFIDList = append(planRFIDList, &PlanRFID{
  8969. RFID: RFIDStr,
  8970. Lweight: "1904.1",
  8971. Gear: "1",
  8972. Speed: "10",
  8973. })
  8974. planRFIDList = append(planRFIDList, &PlanRFID{
  8975. RFID: RFIDStr,
  8976. Lweight: "1870.1",
  8977. Gear: "1",
  8978. Speed: "10",
  8979. })
  8980. planRFIDList = append(planRFIDList, &PlanRFID{
  8981. RFID: RFIDStr,
  8982. Lweight: "2041.1",
  8983. Gear: "1",
  8984. Speed: "10",
  8985. })
  8986. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8987. }
  8988. type tmrEquipmentMuster struct {
  8989. A string
  8990. N string
  8991. }
  8992. func GetTmrEquipmentMuster(c *gin.Context) {
  8993. appG := app.Gin{C: c}
  8994. id := c.Query("id")
  8995. tx := restful.Engine.NewSession()
  8996. defer tx.Close()
  8997. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8998. if err != nil {
  8999. logs.Error(err)
  9000. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9001. return
  9002. }
  9003. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9004. for _, data := range dataList {
  9005. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9006. for _, g := range tmrEquipmentMusterList {
  9007. a, _ := strconv.ParseFloat(g.A, 64)
  9008. n, _ := strconv.ParseFloat(g.N, 64)
  9009. a1, n1 := ddmmtoddd(a, n)
  9010. g.A = fmt.Sprintf("%f", n1)
  9011. g.N = fmt.Sprintf("%f", a1)
  9012. }
  9013. }
  9014. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9015. }
  9016. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9017. lngDegree := fmt.Sprintf("%f", lng/100)
  9018. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9019. lngDegreeInt := int(lngDegreefloat * 1000000)
  9020. dd := lngDegreeInt / 100 * 100 / 60
  9021. fmt.Println(dd)
  9022. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9023. latDegree := fmt.Sprintf("%f", lat/100)
  9024. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9025. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9026. latDegreeInt := int(latDegreefloat * 1000000)
  9027. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9028. a, _ := strconv.ParseFloat(lngStr, 64)
  9029. b, _ := strconv.ParseFloat(latStr, 64)
  9030. return coordtransform.WGS84toGCJ02(b, a)
  9031. }
  9032. func EditDownloadedplanExecWeight(c *gin.Context) {
  9033. appG := app.Gin{C: c}
  9034. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9035. fsions := gofasion.NewFasion(string(dataByte))
  9036. pid := fsions.Get("pid").ValueStr()
  9037. sort := fsions.Get("sort").ValueStr()
  9038. weight := fsions.Get("weight").ValueStr()
  9039. userId := fsions.Get("userId").ValueStr()
  9040. tx := restful.Engine.NewSession()
  9041. defer tx.Close()
  9042. tx.Begin()
  9043. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9044. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9045. pid, sort, pid, sort, weight, userId)
  9046. if err != nil {
  9047. logs.Error(err)
  9048. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9049. tx.Rollback()
  9050. return
  9051. }
  9052. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9053. if err != nil {
  9054. logs.Error(err)
  9055. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9056. tx.Rollback()
  9057. return
  9058. }
  9059. _, 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)
  9060. if err != nil {
  9061. logs.Error(err)
  9062. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9063. tx.Rollback()
  9064. return
  9065. }
  9066. err = tx.Commit()
  9067. if err != nil {
  9068. logs.Error(err)
  9069. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9070. tx.Rollback()
  9071. return
  9072. }
  9073. appG.Response(http.StatusOK, e.SUCCESS, true)
  9074. }
  9075. func EditDownloadplandtl2Weight(c *gin.Context) {
  9076. appG := app.Gin{C: c}
  9077. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9078. fsions := gofasion.NewFasion(string(dataByte))
  9079. pid := fsions.Get("pid").ValueStr()
  9080. sort := fsions.Get("sort").ValueStr()
  9081. weight := fsions.Get("weight").ValueStr()
  9082. userId := fsions.Get("userId").ValueStr()
  9083. tx := restful.Engine.NewSession()
  9084. defer tx.Close()
  9085. tx.Begin()
  9086. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9087. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9088. pid, sort, pid, sort, weight, userId)
  9089. if err != nil {
  9090. logs.Error(err)
  9091. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9092. tx.Rollback()
  9093. return
  9094. }
  9095. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9096. if err != nil {
  9097. logs.Error(err)
  9098. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9099. tx.Rollback()
  9100. return
  9101. }
  9102. err = tx.Commit()
  9103. if err != nil {
  9104. logs.Error(err)
  9105. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9106. tx.Rollback()
  9107. return
  9108. }
  9109. appG.Response(http.StatusOK, e.SUCCESS, true)
  9110. }
  9111. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9112. params := fasion.Get("parammaps")
  9113. surplus := params.Get("surplus").ValueStr()
  9114. surplusId := params.Get("surplusId").ValueStr()
  9115. tx := restful.Engine.NewSession()
  9116. defer tx.Close()
  9117. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9118. if surplusId != "0" {
  9119. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9120. if err != nil {
  9121. log.Println("PostDataByName-error-1: ", err)
  9122. return errors.New("配方修改失败!")
  9123. }
  9124. type ftdetail struct {
  9125. Id string
  9126. Fname string
  9127. Sort int64
  9128. }
  9129. ftList := make([]*ftdetail, 0)
  9130. for _, data := range dataList {
  9131. ft := new(ftdetail)
  9132. ft.Fname = data["fname"]
  9133. ft.Id = data["id"]
  9134. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9135. if err != nil {
  9136. log.Println("PostDataByName-error-2: ", err)
  9137. return err
  9138. }
  9139. ft.Sort = sort
  9140. ftList = append(ftList, ft)
  9141. }
  9142. if surplus == "日粮" {
  9143. for _, ft := range ftList {
  9144. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9145. }
  9146. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9147. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9148. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9149. fmt.Println(err)
  9150. } else {
  9151. var sort int64
  9152. for _, ft := range ftList {
  9153. if ft.Fname == surplus {
  9154. sort = ft.Sort
  9155. break
  9156. }
  9157. }
  9158. if sort == 0 {
  9159. for _, ft := range ftList {
  9160. ft.Sort = ft.Sort + 1
  9161. }
  9162. } else {
  9163. for _, ft := range ftList {
  9164. if ft.Sort >= sort {
  9165. ft.Sort = ft.Sort + 1
  9166. }
  9167. }
  9168. }
  9169. for _, ft := range ftList {
  9170. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9171. }
  9172. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9173. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9174. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9175. if err != nil {
  9176. log.Println("PostDataByName-error-1: ", err)
  9177. fmt.Println(err)
  9178. return errors.New("配方修改失败!")
  9179. }
  9180. }
  9181. }
  9182. return nil
  9183. }
  9184. func FeedSurplus(fasion *gofasion.Fasion) {
  9185. tx := restful.Engine.NewSession()
  9186. defer tx.Close()
  9187. params := fasion.Get("parammaps")
  9188. feedId := params.Get("id").ValueStr()
  9189. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9190. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9191. }
  9192. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9193. // params := fasion.Get("parammaps")
  9194. // surplus := params.Get("surplus").ValueStr()
  9195. // surplusId := params.Get("surplusId").ValueStr()
  9196. tx := restful.Engine.NewSession()
  9197. defer tx.Close()
  9198. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9199. if surplusId != "0" {
  9200. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9201. if err != nil {
  9202. log.Println("PostDataByName-error-1: ", err)
  9203. return errors.New("配方修改失败!")
  9204. }
  9205. type ftdetail struct {
  9206. Id string
  9207. Fname string
  9208. Sort int64
  9209. }
  9210. ftList := make([]*ftdetail, 0)
  9211. for _, data := range dataList {
  9212. ft := new(ftdetail)
  9213. ft.Fname = data["fname"]
  9214. ft.Id = data["id"]
  9215. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9216. if err != nil {
  9217. log.Println("PostDataByName-error-2: ", err)
  9218. return err
  9219. }
  9220. ft.Sort = sort
  9221. ftList = append(ftList, ft)
  9222. }
  9223. if surplus == "日粮" {
  9224. for _, ft := range ftList {
  9225. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9226. }
  9227. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9228. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9229. pastureId, id, surplusId, surplusId, surplusId)
  9230. fmt.Println(err)
  9231. } else {
  9232. var sort int64
  9233. for _, ft := range ftList {
  9234. if ft.Fname == surplus {
  9235. sort = ft.Sort
  9236. break
  9237. }
  9238. }
  9239. if sort == 0 {
  9240. for _, ft := range ftList {
  9241. ft.Sort = ft.Sort + 1
  9242. }
  9243. } else {
  9244. for _, ft := range ftList {
  9245. if ft.Sort >= sort {
  9246. ft.Sort = ft.Sort + 1
  9247. }
  9248. }
  9249. }
  9250. for _, ft := range ftList {
  9251. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9252. }
  9253. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9254. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9255. id, surplusId, surplusId, sort, surplusId, pastureId)
  9256. if err != nil {
  9257. log.Println("PostDataByName-error-1: ", err)
  9258. fmt.Println(err)
  9259. return errors.New("配方修改失败!")
  9260. }
  9261. }
  9262. }
  9263. return nil
  9264. }
  9265. func GetLanguageStatus() string {
  9266. tx := restful.Engine.NewSession()
  9267. defer tx.Close()
  9268. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9269. if err != nil {
  9270. log.Println(err)
  9271. return "0"
  9272. }
  9273. return dataList[0]["inforvalue"]
  9274. }
  9275. func EditLanguage(c *gin.Context) {
  9276. appG := app.Gin{C: c}
  9277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9278. fsions := gofasion.NewFasion(string(dataByte))
  9279. language := fsions.Get("language").ValueStr()
  9280. tx := restful.Engine.NewSession()
  9281. defer tx.Close()
  9282. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9283. if err != nil {
  9284. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9285. return
  9286. }
  9287. if language == "0" {
  9288. _, err := tx.Exec(`delete from dictlist `)
  9289. if err != nil {
  9290. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9291. return
  9292. }
  9293. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9294. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9295. if err != nil {
  9296. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9297. return
  9298. }
  9299. } else {
  9300. _, err := tx.Exec(`delete from dictlist `)
  9301. if err != nil {
  9302. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9303. return
  9304. }
  9305. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9306. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9307. if err != nil {
  9308. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9309. return
  9310. }
  9311. }
  9312. appG.Response(http.StatusOK, e.SUCCESS, true)
  9313. }
  9314. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9315. tx := restful.Engine.NewSession()
  9316. defer tx.Close()
  9317. 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
  9318. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9319. if err != nil {
  9320. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9321. return
  9322. }
  9323. for _, dataexcel := range barList {
  9324. // dataexcel := make(map[string]interface{}, 0)
  9325. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9326. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9327. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9328. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9329. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9330. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9331. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9332. // if err != nil {
  9333. // logs.Error(err)
  9334. // return
  9335. // }
  9336. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9337. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9338. // if err != nil {
  9339. // logs.Error(err)
  9340. // return
  9341. // }
  9342. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9343. continue
  9344. }
  9345. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9346. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9347. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9348. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9349. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9350. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9351. // /*
  9352. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9353. if err != nil {
  9354. logs.Error(err)
  9355. return
  9356. }
  9357. if !ftexist {
  9358. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9359. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9360. if err != nil {
  9361. logs.Error(err)
  9362. return
  9363. }
  9364. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9365. if err != nil {
  9366. logs.Error(err)
  9367. return
  9368. }
  9369. }
  9370. // */
  9371. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9372. if err != nil {
  9373. logs.Error(err)
  9374. return
  9375. }
  9376. if !exist {
  9377. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9378. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9379. if err != nil {
  9380. logs.Error(err)
  9381. return
  9382. }
  9383. }
  9384. var feedpargs []interface{}
  9385. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9386. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9387. if _, ok := dataexcel["ftname"]; ok {
  9388. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9389. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9390. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9391. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9392. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9393. } else {
  9394. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9395. }
  9396. if _, ok := dataexcel["ptsfname"]; ok {
  9397. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9398. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9399. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9400. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9401. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9402. } else {
  9403. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9404. }
  9405. upFeedpSql += " where barname = ? and pastureid = ? "
  9406. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9407. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9408. if err != nil {
  9409. logs.Error(err)
  9410. return
  9411. }
  9412. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9413. if err != nil {
  9414. logs.Error(err)
  9415. return
  9416. }
  9417. if !exist1 {
  9418. _, 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) `,
  9419. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9420. if err != nil {
  9421. logs.Error(err)
  9422. return
  9423. }
  9424. }
  9425. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9426. if err != nil {
  9427. logs.Error(err)
  9428. return
  9429. }
  9430. if !exist2 {
  9431. _, 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) `,
  9432. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9433. if err != nil {
  9434. logs.Error(err)
  9435. return
  9436. }
  9437. }
  9438. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9439. if err != nil {
  9440. logs.Error(err)
  9441. return
  9442. }
  9443. if !exist3 {
  9444. _, 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) `,
  9445. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9446. if err != nil {
  9447. logs.Error(err)
  9448. return
  9449. }
  9450. }
  9451. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9452. if err != nil {
  9453. logs.Error(err)
  9454. return
  9455. }
  9456. if !exist4 {
  9457. _, 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) `,
  9458. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9459. if err != nil {
  9460. logs.Error(err)
  9461. return
  9462. }
  9463. }
  9464. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9465. if err != nil {
  9466. logs.Error(err)
  9467. return
  9468. }
  9469. if !exist5 {
  9470. _, 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) `,
  9471. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9472. if err != nil {
  9473. logs.Error(err)
  9474. return
  9475. }
  9476. }
  9477. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9478. if err != nil {
  9479. logs.Error(err)
  9480. return
  9481. }
  9482. if !exist6 {
  9483. _, 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) `,
  9484. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9485. if err != nil {
  9486. logs.Error(err)
  9487. return
  9488. }
  9489. }
  9490. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9491. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9492. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9493. and pastureid = ? and times = ?`
  9494. var fpdargs1 []interface{}
  9495. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9496. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9497. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9498. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9499. if err != nil {
  9500. fmt.Println(err)
  9501. return
  9502. }
  9503. var fpdargs2 []interface{}
  9504. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9505. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9506. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9507. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9508. if err != nil {
  9509. fmt.Println(err)
  9510. return
  9511. }
  9512. var fpdargs3 []interface{}
  9513. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9514. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9515. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9516. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9517. if err != nil {
  9518. fmt.Println(err)
  9519. return
  9520. }
  9521. var fpdargs4 []interface{}
  9522. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9523. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9524. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9525. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9526. if err != nil {
  9527. fmt.Println(err)
  9528. return
  9529. }
  9530. var fpdargs5 []interface{}
  9531. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9532. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9533. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9534. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9535. if err != nil {
  9536. fmt.Println(err)
  9537. return
  9538. }
  9539. var fpdargs6 []interface{}
  9540. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9541. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9542. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9543. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9544. if err != nil {
  9545. fmt.Println(err)
  9546. return
  9547. }
  9548. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9549. 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()
  9550. if err != nil {
  9551. return
  9552. }
  9553. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9554. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9555. upFpdetailList := make([]*upFpdetail, 0)
  9556. for _, newfpd := range newList {
  9557. for _, oldfpd := range oldFpdList {
  9558. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9559. var oldweight, newweight float64
  9560. if oldfpd["weight"] != nil {
  9561. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9562. }
  9563. if newfpd["weight"] != nil {
  9564. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9565. }
  9566. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9567. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9568. Old: oldweight,
  9569. New: newweight,
  9570. Times: newfpd["times"].(int64),
  9571. Ptid: newfpd["ptid"].(int64),
  9572. Fweight: fweight,
  9573. Id: oldfpd["id"].(int64),
  9574. })
  9575. break
  9576. }
  9577. }
  9578. }
  9579. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9580. }
  9581. }
  9582. func AddXxwFtdetail(c *gin.Context) {
  9583. appG := app.Gin{C: c}
  9584. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  9585. c.Bind(&xxwFtdetailList)
  9586. tx := restful.Engine.NewSession()
  9587. defer tx.Close()
  9588. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  9589. if err != nil {
  9590. logs.Error(err)
  9591. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9592. }
  9593. _, err = tx.Insert(xxwFtdetailList)
  9594. if err != nil {
  9595. logs.Error(err)
  9596. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9597. }
  9598. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  9599. appG.Response(http.StatusOK, e.SUCCESS, true)
  9600. }
  9601. func AddXxwFeedtemplet(c *gin.Context) {
  9602. appG := app.Gin{C: c}
  9603. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  9604. c.Bind(&xxwFeedtempletList)
  9605. tx := restful.Engine.NewSession()
  9606. defer tx.Close()
  9607. pastureinfo := new(udPastureInfo)
  9608. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  9609. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  9610. if err != nil {
  9611. logs.Error(err)
  9612. return
  9613. }
  9614. for _, ft := range xxwFeedtempletList {
  9615. ids, err := setting.SnowIds.NextId()
  9616. if err != nil {
  9617. ids = time.Now().UnixNano()
  9618. logging.Info("create SnowIds err", err)
  9619. }
  9620. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  9621. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  9622. ft.RecipeobjName, ft.RecipeobjName)
  9623. if err != nil {
  9624. logs.Error(err)
  9625. return
  9626. }
  9627. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  9628. _, 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')),
  9629. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  9630. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  9631. if err != nil {
  9632. logs.Error(err)
  9633. return
  9634. }
  9635. }
  9636. appG.Response(http.StatusOK, e.SUCCESS, true)
  9637. }
  9638. func ProcessExcel(c *gin.Context) {
  9639. appG := app.Gin{C: c}
  9640. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9641. fasion := gofasion.NewFasion(string(dataByte))
  9642. params := fasion.Get("parammaps")
  9643. pastureid := params.Get("pastureid").ValueStr()
  9644. startTime := params.Get("startTime").ValueStr()
  9645. stopTime := params.Get("stopTime").ValueStr()
  9646. iscompleted := params.Get("iscompleted").ValueStr()
  9647. lpplantype := params.Get("lpplantype").ValueStr()
  9648. error := params.Get("error").ValueStr()
  9649. hlwc1 := params.Get("hlwc1").ValueStr()
  9650. hlwc2 := params.Get("hlwc2").ValueStr()
  9651. slwc1 := params.Get("slwc1").ValueStr()
  9652. slwc2 := params.Get("slwc2").ValueStr()
  9653. hlzq1 := params.Get("hlzq1").ValueStr()
  9654. hlzq2 := params.Get("hlzq2").ValueStr()
  9655. slzq1 := params.Get("slzq1").ValueStr()
  9656. slzq2 := params.Get("slzq2").ValueStr()
  9657. fclassid := params.Get("fclassid").ValueStr()
  9658. minproesstime := params.Get("minproesstime").ValueStr()
  9659. maxproesstime := params.Get("maxproesstime").ValueStr()
  9660. tx := restful.Engine.NewSession()
  9661. defer tx.Close()
  9662. planList, err := tx.SQL(`SELECT
  9663. 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
  9664. FROM downloadedplan d
  9665. join pasture p on p.pastureid = d.pastureid
  9666. WHERE d.pastureid= ? and d.intime IS NOT NULL
  9667. AND mydate >= ? AND mydate <= ?
  9668. AND (iscompleted=? or ?='')
  9669. AND (lpplantype = ? or ? = '')
  9670. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  9671. 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
  9672. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  9673. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9674. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  9675. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9676. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  9677. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9678. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  9679. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9680. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  9681. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  9682. 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,
  9683. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  9684. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  9685. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  9686. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9687. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  9688. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  9689. or (?= '' and ? = '' ))
  9690. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  9691. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  9692. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  9693. maxproesstime, minproesstime, maxproesstime).QueryString()
  9694. if err != nil {
  9695. logs.Error(err)
  9696. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9697. return
  9698. }
  9699. planExecList, err := tx.SQL(`SELECT
  9700. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9701. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9702. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  9703. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9704. ) proesstime,
  9705. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9706. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  9707. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9708. sumproesstime, d1.pid,
  9709. d1.sort,
  9710. d1.fname,
  9711. d1.lweight,
  9712. d1.actualweightminus,
  9713. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  9714. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  9715. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  9716. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  9717. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  9718. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  9719. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9720. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9721. d1.begintime stoptime,
  9722. d1.lastactualweight,
  9723. d1.actualweight,
  9724. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  9725. case d1.buttontype
  9726. when 1 then '自动'
  9727. when 2 then '手动'
  9728. when 3 then '手动'
  9729. end,
  9730. case d1.buttontype
  9731. when 1 then 'Automatic'
  9732. when 2 then 'Manual'
  9733. when 3 then 'Manual'
  9734. end
  9735. ) buttontype
  9736. FROM
  9737. downloadplandtl1_exec d1
  9738. WHERE d1.date between ? and ?
  9739. ORDER BY sort
  9740. `, startTime, stopTime).QueryString()
  9741. if err != nil {
  9742. logs.Error(err)
  9743. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9744. return
  9745. }
  9746. planExec2, err := tx.SQL(`SELECT
  9747. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  9748. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9749. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9750. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  9751. ) proesstime,
  9752. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  9753. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9754. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  9755. d1.sort,
  9756. d1.fname,
  9757. d1.lweight,
  9758. d1.actualweightminus,
  9759. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  9760. ABS(d1.lweight- d1.actualweightminus) diff,
  9761. 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,
  9762. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9763. d1.begintime stoptime,
  9764. d1.lastactualweight,
  9765. d1.actualweight,d1.pid
  9766. FROM
  9767. downloadplandtl2 d1
  9768. WHERE d1.date between ? and ?
  9769. ORDER BY sort`, startTime, stopTime).QueryString()
  9770. if err != nil {
  9771. logs.Error(err)
  9772. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9773. return
  9774. }
  9775. // 创建一个新的 Excel 文件
  9776. f := excelizexuri.NewFile()
  9777. // 创建工作表名称
  9778. sheetName := "Sheet1"
  9779. border := []excelizexuri.Border{
  9780. {Type: "left", Color: "000000", Style: 1},
  9781. {Type: "right", Color: "000000", Style: 1},
  9782. {Type: "top", Color: "000000", Style: 1},
  9783. {Type: "bottom", Color: "000000", Style: 1},
  9784. }
  9785. // 创建新的样式
  9786. style := &excelizexuri.Style{
  9787. // Border: border,
  9788. Alignment: &excelizexuri.Alignment{
  9789. Vertical: "center",
  9790. Horizontal: "center",
  9791. ShrinkToFit: true,
  9792. WrapText: true,
  9793. },
  9794. }
  9795. styleTitle := &excelizexuri.Style{
  9796. // Border: border,
  9797. Font: &excelizexuri.Font{
  9798. Bold: true, // 加粗
  9799. Size: 24, // 字体大小
  9800. // Name: "宋体", // 字体名称
  9801. // WrapText :true,
  9802. Color: "000000", // 字体颜色(黑色)
  9803. },
  9804. Alignment: &excelizexuri.Alignment{
  9805. Vertical: "center", // 垂直居中
  9806. Horizontal: "center", // 水平居中
  9807. ShrinkToFit: true,
  9808. WrapText: true,
  9809. },
  9810. }
  9811. // 创建样式 ID
  9812. styleTitleId, err := f.NewStyle(styleTitle)
  9813. if err != nil {
  9814. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9815. return
  9816. }
  9817. // 创建样式 ID
  9818. styleID, err := f.NewStyle(style)
  9819. if err != nil {
  9820. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9821. return
  9822. }
  9823. // 合并单元格并设置内容
  9824. f.MergeCell(sheetName, "A1", "K1")
  9825. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  9826. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  9827. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  9828. planExecMap := make(map[string][]map[string]string, 0)
  9829. for _, planExec := range planExecList {
  9830. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  9831. }
  9832. plan2Map := make(map[string][]map[string]string, 0)
  9833. for _, plan2 := range planExec2 {
  9834. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  9835. }
  9836. num := 2
  9837. var notBorder []int
  9838. for _, plan := range planList {
  9839. fmt.Println(plan)
  9840. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  9841. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9842. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9843. for i, header := range headers {
  9844. // 从 A2 开始
  9845. if header == "开始日期" {
  9846. cell := "%" + fmt.Sprintf("c%d", num)
  9847. cell = fmt.Sprintf(cell, 'A'+i+1)
  9848. f.SetCellValue(sheetName, cell, header)
  9849. f.SetCellStyle(sheetName, cell, cell, styleID)
  9850. continue
  9851. }
  9852. cell := "%" + fmt.Sprintf("c%d", num)
  9853. cell = fmt.Sprintf(cell, 'A'+i)
  9854. f.SetCellValue(sheetName, cell, header)
  9855. f.SetCellStyle(sheetName, cell, cell, styleID)
  9856. }
  9857. num += 1
  9858. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  9859. cell := "%" + fmt.Sprintf("c%d", num)
  9860. cell = fmt.Sprintf(cell, 'A'+0)
  9861. f.SetCellValue(sheetName, cell, plan["pastureName"])
  9862. f.SetCellStyle(sheetName, cell, cell, styleID)
  9863. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  9864. cell = "%" + fmt.Sprintf("c%d", num)
  9865. cell = fmt.Sprintf(cell, 'A'+1)
  9866. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  9867. f.SetCellStyle(sheetName, cell, cell, styleID)
  9868. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  9869. cell = "%" + fmt.Sprintf("c%d", num)
  9870. cell = fmt.Sprintf(cell, 'A'+2)
  9871. f.SetCellValue(sheetName, cell, plan["projname"])
  9872. f.SetCellStyle(sheetName, cell, cell, styleID)
  9873. cell = "%" + fmt.Sprintf("c%d", num)
  9874. cell = fmt.Sprintf(cell, 'A'+3)
  9875. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9876. f.SetCellValue(sheetName, cell, plan["mydate"])
  9877. f.SetCellStyle(sheetName, cell, cell, styleID)
  9878. cell = "%" + fmt.Sprintf("c%d", num)
  9879. cell = fmt.Sprintf(cell, 'A'+6)
  9880. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9881. f.SetCellValue(sheetName, cell, plan["intime"])
  9882. f.SetCellStyle(sheetName, cell, cell, styleID)
  9883. num += 1
  9884. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9885. for i, header := range headers1 {
  9886. cell = "%" + fmt.Sprintf("c%d", num)
  9887. cell = fmt.Sprintf(cell, 'C'+i)
  9888. f.SetCellValue(sheetName, cell, header)
  9889. f.SetCellStyle(sheetName, cell, cell, styleID)
  9890. // maxWidth := len(header)
  9891. // colName := string('C' + i)
  9892. // f.SetColWidth(sheetName, colName, colName, 20)
  9893. f.SetColWidth(sheetName, header, header, 40)
  9894. }
  9895. num += 1
  9896. for _, planExec := range planExecMap[plan["id"]] {
  9897. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9898. sort, _ := strconv.Atoi(planExec["sort"])
  9899. f.SetCellValue(sheetName, cell, sort)
  9900. f.SetCellStyle(sheetName, cell, cell, styleID)
  9901. cell = fmt.Sprintf("D%d", num)
  9902. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  9903. f.SetCellValue(sheetName, cell, lweight)
  9904. f.SetCellStyle(sheetName, cell, cell, styleID)
  9905. cell = fmt.Sprintf("E%d", num)
  9906. if _, ok := planExec["actualweightminus"]; ok {
  9907. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  9908. f.SetCellValue(sheetName, cell, actualweightminus)
  9909. f.SetCellStyle(sheetName, cell, cell, styleID)
  9910. } else {
  9911. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  9912. f.SetCellStyle(sheetName, cell, cell, styleID)
  9913. }
  9914. cell = fmt.Sprintf("F%d", num)
  9915. f.SetCellValue(sheetName, cell, planExec["fname"])
  9916. f.SetCellStyle(sheetName, cell, cell, styleID)
  9917. cell = fmt.Sprintf("G%d", num)
  9918. if _, ok := planExec["diff"]; ok {
  9919. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  9920. f.SetCellValue(sheetName, cell, diff)
  9921. f.SetCellStyle(sheetName, cell, cell, styleID)
  9922. } else {
  9923. f.SetCellValue(sheetName, cell, planExec["diff"])
  9924. f.SetCellStyle(sheetName, cell, cell, styleID)
  9925. }
  9926. cell = fmt.Sprintf("H%d", num)
  9927. if _, ok := planExec["diffRate"]; ok {
  9928. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  9929. f.SetCellValue(sheetName, cell, diffRate)
  9930. f.SetCellStyle(sheetName, cell, cell, styleID)
  9931. } else {
  9932. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  9933. f.SetCellStyle(sheetName, cell, cell, styleID)
  9934. }
  9935. cell = fmt.Sprintf("I%d", num)
  9936. f.SetCellValue(sheetName, cell, planExec["intime"])
  9937. f.SetCellStyle(sheetName, cell, cell, styleID)
  9938. cell = fmt.Sprintf("J%d", num)
  9939. if _, ok := planExec["lastactualweight"]; ok {
  9940. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  9941. f.SetCellValue(sheetName, cell, lastactualweight)
  9942. f.SetCellStyle(sheetName, cell, cell, styleID)
  9943. } else {
  9944. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  9945. f.SetCellStyle(sheetName, cell, cell, styleID)
  9946. }
  9947. cell = fmt.Sprintf("K%d", num)
  9948. if _, ok := planExec["actualweight"]; ok {
  9949. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  9950. f.SetCellValue(sheetName, cell, actualweight)
  9951. f.SetCellStyle(sheetName, cell, cell, styleID)
  9952. } else {
  9953. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  9954. f.SetCellStyle(sheetName, cell, cell, styleID)
  9955. }
  9956. num += 1
  9957. }
  9958. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9959. for i, header := range headers2 {
  9960. cell := "%" + fmt.Sprintf("c%d", num)
  9961. cell = fmt.Sprintf(cell, 'C'+i)
  9962. f.SetCellValue(sheetName, cell, header)
  9963. f.SetCellStyle(sheetName, cell, cell, styleID)
  9964. maxWidth := len(header)
  9965. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  9966. }
  9967. num += 1
  9968. for _, plan2 := range plan2Map[plan["id"]] {
  9969. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9970. sort, _ := strconv.Atoi(plan2["sort"])
  9971. f.SetCellValue(sheetName, cell, sort)
  9972. f.SetCellStyle(sheetName, cell, cell, styleID)
  9973. cell = fmt.Sprintf("D%d", num)
  9974. f.SetCellValue(sheetName, cell, plan2["fname"])
  9975. f.SetCellStyle(sheetName, cell, cell, styleID)
  9976. cell = fmt.Sprintf("E%d", num)
  9977. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  9978. f.SetCellValue(sheetName, cell, lweight)
  9979. f.SetCellStyle(sheetName, cell, cell, styleID)
  9980. cell = fmt.Sprintf("F%d", num)
  9981. if _, ok := plan2["actualweightminus"]; ok {
  9982. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  9983. f.SetCellValue(sheetName, cell, actualweightminus)
  9984. f.SetCellStyle(sheetName, cell, cell, styleID)
  9985. } else {
  9986. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  9987. f.SetCellStyle(sheetName, cell, cell, styleID)
  9988. }
  9989. cell = fmt.Sprintf("G%d", num)
  9990. if _, ok := plan2["diff"]; ok {
  9991. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  9992. f.SetCellValue(sheetName, cell, diff)
  9993. f.SetCellStyle(sheetName, cell, cell, styleID)
  9994. } else {
  9995. f.SetCellValue(sheetName, cell, plan2["diff"])
  9996. f.SetCellStyle(sheetName, cell, cell, styleID)
  9997. }
  9998. cell = fmt.Sprintf("H%d", num)
  9999. if _, ok := plan2["diffRate"]; ok {
  10000. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10001. f.SetCellValue(sheetName, cell, diffRate)
  10002. f.SetCellStyle(sheetName, cell, cell, styleID)
  10003. } else {
  10004. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10005. f.SetCellStyle(sheetName, cell, cell, styleID)
  10006. }
  10007. cell = fmt.Sprintf("I%d", num)
  10008. f.SetCellValue(sheetName, cell, plan2["intime"])
  10009. f.SetCellStyle(sheetName, cell, cell, styleID)
  10010. cell = fmt.Sprintf("J%d", num)
  10011. if _, ok := plan2["lastactualweight"]; ok {
  10012. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10013. f.SetCellValue(sheetName, cell, lastactualweight)
  10014. f.SetCellStyle(sheetName, cell, cell, styleID)
  10015. } else {
  10016. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10017. f.SetCellStyle(sheetName, cell, cell, styleID)
  10018. }
  10019. cell = fmt.Sprintf("K%d", num)
  10020. if _, ok := plan2["lastactualweight"]; ok {
  10021. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10022. f.SetCellValue(sheetName, cell, actualweight)
  10023. f.SetCellStyle(sheetName, cell, cell, styleID)
  10024. } else {
  10025. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10026. f.SetCellStyle(sheetName, cell, cell, styleID)
  10027. }
  10028. num += 1
  10029. }
  10030. num += 1
  10031. notBorder = append(notBorder, num)
  10032. }
  10033. for i := 2; i < num; i++ {
  10034. exist := false
  10035. for _, n := range notBorder {
  10036. if i+1 == n {
  10037. exist = true
  10038. break
  10039. }
  10040. }
  10041. if !exist {
  10042. // 为 A-K 列设置边框
  10043. for col := 'A'; col <= 'K'; col++ {
  10044. cellName := fmt.Sprintf("%c%d", col, i)
  10045. style, _ := f.NewStyle(&excelizexuri.Style{
  10046. Border: border, Alignment: &excelizexuri.Alignment{
  10047. Vertical: "center",
  10048. Horizontal: "center",
  10049. ShrinkToFit: true,
  10050. WrapText: true,
  10051. },
  10052. })
  10053. f.SetCellStyle(sheetName, cellName, cellName, style)
  10054. }
  10055. }
  10056. }
  10057. for col := 'A'; col <= 'K'; col++ {
  10058. colName := string(col)
  10059. switch colName {
  10060. case "A", "B": // 牧场名称、TMR列
  10061. f.SetColWidth(sheetName, colName, colName, 10)
  10062. case "C": // 操作编号列
  10063. f.SetColWidth(sheetName, colName, colName, 10)
  10064. case "D", "E": // 计划重量、实际重量列
  10065. f.SetColWidth(sheetName, colName, colName, 12)
  10066. case "F": // 代表成分/投料位置列
  10067. f.SetColWidth(sheetName, colName, colName, 20)
  10068. case "G", "H": // 误差数、准确率列
  10069. f.SetColWidth(sheetName, colName, colName, 12)
  10070. case "I": // 完成时间列
  10071. f.SetColWidth(sheetName, colName, colName, 15)
  10072. case "J", "K": // 起始读数重量、完成读数重量列
  10073. f.SetColWidth(sheetName, colName, colName, 15)
  10074. }
  10075. }
  10076. // 设置响应头
  10077. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10078. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10079. c.Header("Content-Transfer-Encoding", "binary")
  10080. // 写入 Excel 文件到响应
  10081. if err := f.Write(c.Writer); err != nil {
  10082. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10083. return
  10084. }
  10085. }
  10086. func RestartMqtt(c *gin.Context) {
  10087. appG := app.Gin{C: c}
  10088. // 发送 GET 请求到 MQTT 重启接口
  10089. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10090. if err != nil {
  10091. logging.Error("RestartMqtt request failed:", err)
  10092. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10093. return
  10094. }
  10095. defer resp.Body.Close()
  10096. // 读取响应内容f
  10097. body, err := ioutil.ReadAll(resp.Body)
  10098. if err != nil {
  10099. logging.Error("RestartMqtt read response failed:", err)
  10100. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10101. return
  10102. }
  10103. // 检查响应状态码
  10104. if resp.StatusCode != http.StatusOK {
  10105. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10106. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10107. return
  10108. }
  10109. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10110. }
  10111. func FpdBatchEditByWeight(c *gin.Context) {
  10112. appG := app.Gin{C: c}
  10113. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10114. fsions := gofasion.NewFasion(string(dataByte))
  10115. barList := fsions.Get("barList").Array()
  10116. pastureid := fsions.Get("pastureId").ValueStr()
  10117. tx := restful.Engine.NewSession()
  10118. defer tx.Close()
  10119. 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
  10120. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10121. if err != nil {
  10122. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10123. return
  10124. }
  10125. for _, barFsions := range barList {
  10126. dataexcel := make(map[string]interface{}, 0)
  10127. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10128. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10129. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10130. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10131. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10132. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10133. continue
  10134. }
  10135. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10136. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10137. // if err != nil {
  10138. // logs.Error(err)
  10139. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10140. // return
  10141. // }
  10142. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10143. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10144. // if err != nil {
  10145. // logs.Error(err)
  10146. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10147. // return
  10148. // }
  10149. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10150. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10151. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10152. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10153. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10154. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10155. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10156. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10157. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10158. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10159. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10160. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10161. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10162. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10163. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10164. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10165. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10166. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10167. if err != nil {
  10168. logs.Error(err)
  10169. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10170. return
  10171. }
  10172. if !ftexist {
  10173. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10174. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10175. if err != nil {
  10176. logs.Error(err)
  10177. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10178. return
  10179. }
  10180. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10181. if err != nil {
  10182. logs.Error(err)
  10183. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10184. return
  10185. }
  10186. }
  10187. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10188. if err != nil {
  10189. logs.Error(err)
  10190. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10191. return
  10192. }
  10193. if !exist {
  10194. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10195. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10196. if err != nil {
  10197. logs.Error(err)
  10198. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10199. return
  10200. }
  10201. }
  10202. var feedpargs []interface{}
  10203. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10204. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10205. if _, ok := dataexcel["ftname"]; ok {
  10206. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10207. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10208. // upFeedpSql += `,ftweight = ? `
  10209. // feedpargs = append(feedpargs, weight)
  10210. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10211. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10212. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10213. } else {
  10214. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10215. }
  10216. // if _, ok := dataexcel["ptsfname"]; ok {
  10217. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10218. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10219. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10220. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10221. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10222. // } else {
  10223. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10224. // }
  10225. upFeedpSql += " where barname = ? and pastureid = ? "
  10226. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10227. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10228. if err != nil {
  10229. logs.Error(err)
  10230. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10231. return
  10232. }
  10233. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10234. if err != nil {
  10235. logs.Error(err)
  10236. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10237. return
  10238. }
  10239. if !exist1 {
  10240. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10241. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10242. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10243. if err != nil {
  10244. logs.Error(err)
  10245. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10246. return
  10247. }
  10248. }
  10249. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10250. if err != nil {
  10251. logs.Error(err)
  10252. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10253. return
  10254. }
  10255. if !exist2 {
  10256. _, 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) `,
  10257. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10258. if err != nil {
  10259. logs.Error(err)
  10260. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10261. return
  10262. }
  10263. }
  10264. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10265. if err != nil {
  10266. logs.Error(err)
  10267. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10268. return
  10269. }
  10270. if !exist3 {
  10271. _, 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) `,
  10272. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10273. if err != nil {
  10274. logs.Error(err)
  10275. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10276. return
  10277. }
  10278. }
  10279. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10280. if err != nil {
  10281. logs.Error(err)
  10282. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10283. return
  10284. }
  10285. if !exist4 {
  10286. _, 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) `,
  10287. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10288. if err != nil {
  10289. logs.Error(err)
  10290. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10291. return
  10292. }
  10293. }
  10294. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10295. if err != nil {
  10296. logs.Error(err)
  10297. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10298. return
  10299. }
  10300. if !exist5 {
  10301. _, 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) `,
  10302. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10303. if err != nil {
  10304. logs.Error(err)
  10305. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10306. return
  10307. }
  10308. }
  10309. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10310. if err != nil {
  10311. logs.Error(err)
  10312. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10313. return
  10314. }
  10315. if !exist6 {
  10316. _, 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) `,
  10317. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10318. if err != nil {
  10319. logs.Error(err)
  10320. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10321. return
  10322. }
  10323. }
  10324. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10325. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10326. and pastureid = ? and times = ?`
  10327. var fpdargs1 []interface{}
  10328. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10329. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10330. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10331. if err != nil {
  10332. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10333. return
  10334. }
  10335. var fpdargs2 []interface{}
  10336. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10337. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10338. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10339. if err != nil {
  10340. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10341. return
  10342. }
  10343. var fpdargs3 []interface{}
  10344. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10345. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10346. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10347. if err != nil {
  10348. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10349. return
  10350. }
  10351. var fpdargs4 []interface{}
  10352. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10353. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10354. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10355. if err != nil {
  10356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10357. return
  10358. }
  10359. var fpdargs5 []interface{}
  10360. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10361. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10362. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10363. if err != nil {
  10364. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10365. return
  10366. }
  10367. var fpdargs6 []interface{}
  10368. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10369. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10370. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10371. if err != nil {
  10372. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10373. return
  10374. }
  10375. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10376. 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()
  10377. if err != nil {
  10378. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10379. return
  10380. }
  10381. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10382. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10383. upFpdetailList := make([]*upFpdetail, 0)
  10384. for _, newfpd := range newList {
  10385. for _, oldfpd := range oldFpdList {
  10386. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10387. var oldweight, newweight float64
  10388. if oldfpd["weight"] != nil {
  10389. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10390. }
  10391. if newfpd["weight"] != nil {
  10392. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10393. }
  10394. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10395. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10396. Old: oldweight,
  10397. New: newweight,
  10398. Times: newfpd["times"].(int64),
  10399. Ptid: newfpd["ptid"].(int64),
  10400. Fweight: fweight,
  10401. Id: oldfpd["id"].(int64),
  10402. })
  10403. break
  10404. }
  10405. }
  10406. }
  10407. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10408. }
  10409. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10410. }
  10411. func FtImportExcel(c *gin.Context) {
  10412. appG := app.Gin{C: c}
  10413. inputdata := ""
  10414. c.Request.ParseForm()
  10415. params := c.Request.Form
  10416. file, _, err := c.Request.FormFile("file")
  10417. if err != nil {
  10418. appG.Response(http.StatusOK, e.ERROR, err)
  10419. return
  10420. }
  10421. sqlnamestrs := params.Get("name")
  10422. sheetname := params.Get("sheetname")
  10423. pastureid := params.Get("pastureid")
  10424. //importParams := params.Get("importParams")
  10425. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10426. // 必输项参数 (字符串格式 "field1,field2,field3")
  10427. requiredParams := params.Get("requiredParams")
  10428. // 日期参数
  10429. dateParams := params.Get("dateParams")
  10430. // 数字参数
  10431. numParams := params.Get("numParams")
  10432. //将字符串分割开
  10433. dateParamslist := strings.Split(dateParams, ",")
  10434. requiredParamslist := strings.Split(requiredParams, ",")
  10435. numParamslist := strings.Split(numParams, ",")
  10436. queryData := make([]interface{}, 0)
  10437. sqlslist := strings.Split(sqlnamestrs, ",")
  10438. xlsx1, err := excelize.OpenReader(file)
  10439. if err != nil {
  10440. fmt.Println(err)
  10441. return
  10442. }
  10443. ok := 0
  10444. error := 0
  10445. isdone := true
  10446. rows := xlsx1.GetRows(sheetname)
  10447. // 限制10000条,多余的截取掉
  10448. if len(rows) > 10000 {
  10449. rows = rows[:10000]
  10450. }
  10451. tx := restful.Engine.NewSession()
  10452. ftNameList := make(map[string]interface{})
  10453. var ftNames []interface{}
  10454. for i, row := range rows {
  10455. if i > 0 {
  10456. entry := make(map[string]interface{})
  10457. outentry := make(map[string]interface{})
  10458. for j, colCell := range rows[0] {
  10459. for k, colCell1 := range row {
  10460. if j == k {
  10461. outentry[colCell] = colCell1
  10462. entry[colCell] = colCell1
  10463. }
  10464. }
  10465. }
  10466. inputdata = ""
  10467. a := ""
  10468. fmt.Println(outentry, entry)
  10469. //校验日期格式
  10470. for _, v := range dateParamslist {
  10471. if v == "" {
  10472. continue
  10473. }
  10474. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10475. dtime, err := TransfTime(d.(string))
  10476. if err != nil {
  10477. a = strings.Trim(v, " ")
  10478. break
  10479. }
  10480. outentry[strings.Trim(v, " ")] = dtime
  10481. }
  10482. }
  10483. if a != "" {
  10484. outentry["error_msg"] = a + " 格式错误"
  10485. error++
  10486. queryData = append(queryData, outentry)
  10487. continue
  10488. }
  10489. a = ""
  10490. //校验必填格式
  10491. for _, v := range requiredParamslist {
  10492. if v == "" {
  10493. continue
  10494. }
  10495. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10496. a = strings.Trim(v, " ")
  10497. break
  10498. }
  10499. }
  10500. if a != "" {
  10501. outentry["error_msg"] = a + " 未填或格式错误"
  10502. error++
  10503. queryData = append(queryData, outentry)
  10504. continue
  10505. }
  10506. a = ""
  10507. //校验数字格式
  10508. for _, v := range numParamslist {
  10509. if v == "" {
  10510. continue
  10511. }
  10512. d, ok := outentry[strings.Trim(v, " ")]
  10513. if !ok || d == "" {
  10514. outentry[strings.Trim(v, " ")] = 0
  10515. } else {
  10516. var fl float64
  10517. switch d.(type) {
  10518. case string:
  10519. fl, err = strconv.ParseFloat(d.(string), 64)
  10520. }
  10521. if err != nil || fl < 0 {
  10522. a = strings.Trim(v, " ")
  10523. break
  10524. }
  10525. }
  10526. }
  10527. if a != "" {
  10528. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10529. error++
  10530. queryData = append(queryData, outentry)
  10531. continue
  10532. }
  10533. err := tx.Begin()
  10534. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10535. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10536. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10537. }
  10538. for _, sqlnamestr := range sqlslist {
  10539. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  10540. paramslist := strings.Split(paramslists, ",")
  10541. if len(paramslist) > 0 {
  10542. s_params := make([]interface{}, 0)
  10543. for _, value := range paramslist {
  10544. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  10545. if tempv, exists := c.Get("jwt_username"); exists {
  10546. s_params = append(s_params, tempv.(string))
  10547. } else {
  10548. s_params = append(s_params, "")
  10549. }
  10550. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  10551. s_params = append(s_params, pastureid)
  10552. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  10553. ids, err := setting.SnowIds.NextId()
  10554. if err != nil {
  10555. ids = time.Now().UnixNano()
  10556. logging.Info("create SnowIds err", err)
  10557. }
  10558. s_params = append(s_params, ids)
  10559. } else {
  10560. if outentry[strings.Trim(value, " ")] == nil {
  10561. s_params = append(s_params, "")
  10562. } else {
  10563. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  10564. }
  10565. }
  10566. }
  10567. outentry["input"] = inputdata
  10568. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  10569. if err != nil {
  10570. if tx != nil {
  10571. tx.Rollback()
  10572. }
  10573. if tx != nil {
  10574. tx.Close()
  10575. }
  10576. msg := geterrmsg(err.Error())
  10577. outentry["error_msg"] = msg
  10578. error++
  10579. queryData = append(queryData, outentry)
  10580. isdone = true
  10581. break
  10582. } else {
  10583. if len(returnmsgmap1) > 0 {
  10584. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  10585. if tx != nil {
  10586. tx.Rollback()
  10587. }
  10588. if tx != nil {
  10589. tx.Close()
  10590. }
  10591. msg := geterrmsg(va.(string))
  10592. outentry["error_msg"] = msg
  10593. error++
  10594. queryData = append(queryData, outentry)
  10595. isdone = true
  10596. break
  10597. }
  10598. }
  10599. isdone = false
  10600. }
  10601. }
  10602. }
  10603. ftNames = append(ftNames, outentry["配方名称"])
  10604. switch {
  10605. case err != nil:
  10606. if tx != nil {
  10607. tx.Rollback()
  10608. }
  10609. default:
  10610. if tx != nil {
  10611. err = tx.Commit()
  10612. }
  10613. }
  10614. if tx != nil {
  10615. tx.Close()
  10616. }
  10617. }
  10618. if !isdone {
  10619. ok++
  10620. isdone = true
  10621. }
  10622. }
  10623. go ftSync(ftNames, pastureid)
  10624. data := make(map[string]interface{})
  10625. data["result"] = queryData
  10626. data["success"] = ok
  10627. data["err_count"] = error
  10628. appG.Response(http.StatusOK, e.SUCCESS, data)
  10629. }
  10630. func ftSync(ftNameList []interface{}, pastureId string) {
  10631. tx := restful.Engine.NewSession()
  10632. defer tx.Close()
  10633. for _, ftName := range ftNameList {
  10634. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  10635. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  10636. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  10637. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  10638. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  10639. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  10640. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  10641. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  10642. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  10643. FpdBatchEditGrfd(pastureId, values1)
  10644. }
  10645. }
  10646. func CopyFeedtemplet(c *gin.Context) {
  10647. appG := app.Gin{C: c}
  10648. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10649. fsion := gofasion.NewFasion(string(dataByte))
  10650. pastureid := fsion.Get("pastureid").ValueStr()
  10651. newName := fsion.Get("newName").ValueStr()
  10652. id := fsion.Get("id").ValueStr()
  10653. tx := restful.Engine.NewSession()
  10654. defer tx.Close()
  10655. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  10656. if err != nil {
  10657. appG.Response(http.StatusOK, e.ERROR, err)
  10658. return
  10659. }
  10660. if count > 0 {
  10661. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  10662. return
  10663. }
  10664. type ftCode struct {
  10665. Tcode string `xorm:"tcode"`
  10666. }
  10667. code := new(ftCode)
  10668. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  10669. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  10670. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  10671. if err != nil {
  10672. appG.Response(http.StatusOK, e.ERROR, err)
  10673. return
  10674. }
  10675. if code.Tcode == "" {
  10676. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  10677. return
  10678. }
  10679. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  10680. remark,enable,sort,volume,autozone)
  10681. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  10682. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  10683. if err != nil {
  10684. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  10685. return
  10686. }
  10687. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  10688. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  10689. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  10690. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  10691. from ftdetail where ftid = ? `, code.Tcode, id)
  10692. if err != nil {
  10693. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  10694. return
  10695. }
  10696. appG.Response(http.StatusOK, e.SUCCESS, true)
  10697. }