db.go 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "../../pkg/app"
  19. "../../pkg/e"
  20. "../../pkg/logging"
  21. "../../pkg/setting"
  22. "../../routers/restful"
  23. "github.com/360EntSecGroup-Skylar/excelize"
  24. "github.com/Anderson-Lu/gofasion/gofasion"
  25. "github.com/astaxie/beego/logs"
  26. "github.com/gin-gonic/gin"
  27. "github.com/tealeg/xlsx"
  28. "github.com/xormplus/xorm"
  29. )
  30. // @Summary 根据SQL执行得到数据集
  31. // @Tags getData
  32. // @Accept json
  33. // @Produce json
  34. // @Param sql query string true "sql"
  35. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  36. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  37. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  38. // @Router /data/getdata [POST]
  39. func GetData(c *gin.Context) {
  40. appG := app.Gin{C: c}
  41. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  42. fsion := gofasion.NewFasion(string(dataByte))
  43. sqlstr := fsion.Get("sql").ValueStr()
  44. offset := fsion.Get("offset").ValueDefaultInt(0)
  45. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  46. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  47. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  48. if err != nil {
  49. appG.Response(http.StatusOK, e.ERROR, err.Error())
  50. } else {
  51. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  52. }
  53. }
  54. func Testpartitions(c *gin.Context) {
  55. appG := app.Gin{C: c}
  56. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  57. fsion := gofasion.NewFasion(string(dataByte))
  58. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  59. user := fsion.Get("user").ValueStr() //获取新数据库用户
  60. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  61. host := fsion.Get("host").ValueStr() //获取新数据库名称
  62. port := fsion.Get("port").ValueStr() //获取新数据库名称
  63. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  64. if sqls == nil || err1 != nil {
  65. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  66. }
  67. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  68. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  69. mydb, err := sql.Open("mysql", connecting) //连接新连接
  70. if err != nil {
  71. println("err1", err.Error())
  72. }
  73. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  74. if err != nil {
  75. println("err2", err.Error())
  76. }
  77. mydb.Close()
  78. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  79. mydb, err = sql.Open("mysql", connecting)
  80. if err != nil {
  81. println("err3", err.Error())
  82. }
  83. defer mydb.Close()
  84. if err == nil {
  85. mydb.SetMaxOpenConns(10)
  86. mydb.SetMaxIdleConns(10)
  87. }
  88. errmsg := ""
  89. if err == nil {
  90. //tx ,_ :=mydb.Begin()
  91. for _, sqlstr := range sqlstrs {
  92. //println("sqlstr---",sqlstr)
  93. if sqlstr == "" {
  94. continue
  95. }
  96. _, err = mydb.Exec(sqlstr)
  97. if err != nil {
  98. println("err4", err.Error())
  99. errmsg = err.Error()
  100. //err1 :=tx.Rollback()
  101. }
  102. }
  103. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  104. //err =tx.Commit()
  105. }
  106. if errmsg == "" {
  107. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  108. } else {
  109. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  110. }
  111. }
  112. func TestData(c *gin.Context) {
  113. appG := app.Gin{C: c}
  114. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  115. fsion := gofasion.NewFasion(string(dataByte))
  116. sqlstr := fsion.Get("sql").ValueStr()
  117. token := ""
  118. if tempv, exists := c.Get("jwt_username"); exists {
  119. token = tempv.(string)
  120. }
  121. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  122. }
  123. // @Summary 根据APISQL表中SQL执行得到数据集
  124. // @Tags GetDataByName
  125. // @Accept json
  126. // @Produce json
  127. // @Param sqlname body string true "sqlname"
  128. // @Param offset body int true "offset"
  129. // @Param pagecount body int true "pagecount"
  130. // @Param returntype body string true "returntype"
  131. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  132. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  133. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  134. // @Router /data/GetDataByName [POST]
  135. func GetDataByName(c *gin.Context) {
  136. appG := app.Gin{C: c}
  137. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  138. fsion := gofasion.NewFasion(string(dataByte))
  139. sqlnamestr := fsion.Get("name").ValueStr()
  140. offset := fsion.Get("offset").ValueDefaultInt(0)
  141. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  142. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  143. tx := restful.Engine.NewSession()
  144. err := tx.Begin()
  145. defer func() {
  146. switch {
  147. case err != nil:
  148. logging.Error("tx.Begin 事务启动失败__error:", err)
  149. if tx != nil {
  150. tx.Rollback()
  151. }
  152. default:
  153. if tx != nil {
  154. err = tx.Commit()
  155. }
  156. }
  157. if tx != nil {
  158. tx.Close()
  159. }
  160. }()
  161. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  162. if sql != "" {
  163. s_params := make([]interface{}, 0)
  164. if fsion.HasKey("parammaps") {
  165. parammaps := fsion.Get("parammaps")
  166. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  167. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  168. }
  169. paramslist := strings.Split(p, ",")
  170. if len(paramslist) > 0 && p != "" {
  171. for _, value := range paramslist {
  172. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  173. if tempv, exists := c.Get("jwt_username"); exists {
  174. s_params = append(s_params, tempv.(string))
  175. } else {
  176. s_params = append(s_params, "")
  177. }
  178. } else {
  179. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  180. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  181. // tmrNameList := []string{}
  182. // for _, tmr := range tmrArray {
  183. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  184. // }
  185. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  186. // } else {
  187. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  188. // }
  189. }
  190. }
  191. }
  192. } else if fsion.HasKey("params") {
  193. params := fsion.Get("params").Array()
  194. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  195. for _, v_params := range params {
  196. s_params = append(s_params, v_params.ValueStr())
  197. }
  198. }
  199. if returntype == "xlsx" {
  200. var xlsxfile *xlsx.File
  201. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  202. //c.File("c:/dd.xlsx")
  203. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  204. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  205. c.Header("Content-Transfer-Encoding", "binary")
  206. _ = xlsxfile.Write(c.Writer)
  207. } else {
  208. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  209. if err != nil {
  210. logging.Error("GetDataByName err: ", err)
  211. msg := geterrmsg(err.Error())
  212. appG.Response(http.StatusOK, e.ERROR, msg)
  213. } else {
  214. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  215. }
  216. }
  217. } else {
  218. appG.Response(http.StatusOK, e.SUCCESS, nil)
  219. }
  220. }
  221. // @Summary 根据APISQL表中SQL执行得到数据集
  222. // @Tags GetDataByName
  223. // @Accept json
  224. // @Produce json
  225. // @Param sqlname body string true "sqlname"
  226. // @Param offset body int true "offset"
  227. // @Param pagecount body int true "pagecount"
  228. // @Param returntype body string true "returntype"
  229. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  230. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  231. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  232. // @Router /data/GetDataByName [POST]
  233. func GetDataBySqlIN(c *gin.Context) {
  234. appG := app.Gin{C: c}
  235. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  236. fsion := gofasion.NewFasion(string(dataByte))
  237. sqlnamestr := fsion.Get("name").ValueStr()
  238. offset := fsion.Get("offset").ValueDefaultInt(0)
  239. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  240. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  241. tx := restful.Engine.NewSession()
  242. err := tx.Begin()
  243. defer func() {
  244. switch {
  245. case err != nil:
  246. logging.Error("tx.Begin 事务启动失败__error:", err)
  247. if tx != nil {
  248. tx.Rollback()
  249. }
  250. default:
  251. if tx != nil {
  252. err = tx.Commit()
  253. }
  254. }
  255. if tx != nil {
  256. tx.Close()
  257. }
  258. }()
  259. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  260. if sql != "" {
  261. s_params := make([]interface{}, 0)
  262. if fsion.HasKey("parammaps") {
  263. parammaps := fsion.Get("parammaps")
  264. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  265. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  266. }
  267. paramslist := strings.Split(p, ",")
  268. if len(paramslist) > 0 && p != "" {
  269. for _, value := range paramslist {
  270. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  271. if tempv, exists := c.Get("jwt_username"); exists {
  272. s_params = append(s_params, tempv.(string))
  273. } else {
  274. s_params = append(s_params, "")
  275. }
  276. } else {
  277. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  278. }
  279. }
  280. }
  281. } else if fsion.HasKey("params") {
  282. params := fsion.Get("params").Array()
  283. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  284. for _, v_params := range params {
  285. s_params = append(s_params, v_params.ValueStr())
  286. }
  287. }
  288. if returntype == "xlsx" {
  289. var xlsxfile *xlsx.File
  290. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  291. //c.File("c:/dd.xlsx")
  292. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  293. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  294. c.Header("Content-Transfer-Encoding", "binary")
  295. _ = xlsxfile.Write(c.Writer)
  296. } else {
  297. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  298. if err != nil {
  299. logging.Error("GetDataByName err: ", err)
  300. msg := geterrmsg(err.Error())
  301. appG.Response(http.StatusOK, e.ERROR, msg)
  302. } else {
  303. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  304. }
  305. }
  306. } else {
  307. appG.Response(http.StatusOK, e.SUCCESS, nil)
  308. }
  309. }
  310. // 错误处理
  311. // 将报错信息处理成汉字
  312. func geterrmsg(errstr string) (msgstr string) {
  313. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  314. rs := []rune(errstr)
  315. if hzRegexp.MatchString(string(rs[0])) {
  316. msgstr = errstr
  317. return
  318. }
  319. if strings.Contains(errstr, "Duplicate entry") {
  320. strs := strings.Split(errstr, ` key '`)
  321. if len(strs) > 1 {
  322. if len(strs[len(strs)-1]) > 1 {
  323. errstr = "Duplicate entry :" + strs[len(strs)-1]
  324. }
  325. }
  326. }
  327. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  328. if err != nil {
  329. msgstr = errstr
  330. return
  331. }
  332. if msg == nil || len(msg) == 0 {
  333. var param []interface{}
  334. param = append(param, errstr, errstr)
  335. go func() {
  336. tx := restful.Engine.NewSession()
  337. err := tx.Begin()
  338. defer func() {
  339. switch {
  340. case err != nil:
  341. logging.Error("tx.Begin 事务启动失败__error:", err)
  342. if tx != nil {
  343. tx.Rollback()
  344. }
  345. default:
  346. if tx != nil {
  347. err = tx.Commit()
  348. }
  349. }
  350. if tx != nil {
  351. tx.Close()
  352. }
  353. }()
  354. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  355. if err != nil {
  356. logging.Error("insert into err_msg(err,msg) err", err)
  357. }
  358. }()
  359. msgstr = errstr
  360. } else {
  361. msgstr = msg[0]["msg"]
  362. }
  363. return
  364. }
  365. // @Summary 根据APISQL表中SQL执行得到数据集
  366. // @Tags GetDataByNameForm
  367. // @Accept json
  368. // @Produce json
  369. // @Param sqlname body json true "sqlname"
  370. // @Param offset query int true "offset"
  371. // @Param pagecount query int true "pagecount"
  372. // @Param returntype query string true "returntype"
  373. // @Param s formData json true "ss"
  374. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  375. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  376. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  377. // @Router /data/GetDataByNameForm [POST]
  378. func GetDataByNameForm(c *gin.Context) {
  379. appG := app.Gin{C: c}
  380. //sqlnamestr := c.PostForm("measureNumber")
  381. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  382. //fsion := gofasion.NewFasion(string(dataByte))
  383. //sqlnamestr := fsion.Get("name").ValueStr()
  384. //offset := fsion.Get("offset").ValueInt()
  385. //pagecount := fsion.Get("pagecount").ValueInt()
  386. //returntype := fsion.Get("returntype").ValueStr()
  387. //params := fsion.Get("params").Array()
  388. c.Request.ParseForm()
  389. params := c.Request.Form
  390. offset := 0
  391. pageSize_ := 0
  392. returntype := params.Get("page")
  393. if returntype == "" {
  394. returntype = "0"
  395. }
  396. if tempv, exists := c.Get("jwt_username"); exists {
  397. params.Set("JwtUserName", tempv.(string))
  398. } else {
  399. params.Set("JwtUserName", "")
  400. }
  401. sqlnamestr := params.Get("name")
  402. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  403. s_params := make([]interface{}, 0)
  404. if returntype == "1" {
  405. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  406. if error != nil {
  407. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  408. }
  409. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  410. if error != nil {
  411. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  412. }
  413. pageSize_ = pageSize
  414. offset = pageNum
  415. }
  416. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  417. paramslist := strings.Split(p, ",")
  418. if len(paramslist) > 0 && p != "" {
  419. for _, value := range paramslist {
  420. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  421. }
  422. }
  423. if sql != "" {
  424. if returntype == "xlsx" {
  425. var xlsxfile *xlsx.File
  426. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  427. c.Header("Content-Type", "application/octet-stream")
  428. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  429. c.Header("Content-Transfer-Encoding", "binary")
  430. _ = xlsxfile.Write(c.Writer)
  431. } else {
  432. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  433. if err != nil {
  434. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  435. } else {
  436. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  437. }
  438. }
  439. } else {
  440. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  441. }
  442. }
  443. // @Summary 递归获取所有
  444. // @Tags menu
  445. // @Accept json
  446. // @Produce json
  447. // @Param Ton query string true "Ton"
  448. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  449. // @Router /authdata/GetRoleMenus [GET]
  450. func GetRecuDataByName(c *gin.Context) {
  451. appG := app.Gin{C: c}
  452. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  453. fsion := gofasion.NewFasion(string(dataByte))
  454. sqlnamestr := fsion.Get("name").ValueStr()
  455. parentidname := fsion.Get("idname").ValueStr()
  456. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  457. params := make(map[string]interface{})
  458. s_params := make([]interface{}, 0)
  459. if fsion.HasKey("params") {
  460. for _, v_params := range fsion.Get("params").Array() {
  461. s_params = append(s_params, v_params.ValueStr())
  462. }
  463. params["params"] = s_params
  464. } else {
  465. jparams := fsion.Get("parammaps")
  466. paramslist := strings.Split(p, ",")
  467. if len(paramslist) > 0 && p != "" {
  468. for _, value := range paramslist {
  469. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  470. if tempv, exists := c.Get("jwt_username"); exists {
  471. params[value] = tempv.(string)
  472. } else {
  473. params[value] = ""
  474. }
  475. } else {
  476. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  477. }
  478. }
  479. }
  480. }
  481. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  482. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  483. if err != nil {
  484. appG.Response(http.StatusOK, e.ERROR, err.Error())
  485. }
  486. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  487. }
  488. // @Summary 根据APISQL表中SQL执行得到数据集
  489. // @Tags GetDataByNames
  490. // @Accept json
  491. // @Produce json
  492. // @RequestBody sqlname query string true "sqlname"
  493. // @Param offset query int true "offset"
  494. // @Param pagecount query int true "pagecount"
  495. // @Param returntype query string true "returntype"
  496. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  497. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  498. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  499. // @Router /data/GetDataByNames [POST]
  500. func GetDataByNames(c *gin.Context) {
  501. appG := app.Gin{C: c}
  502. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  503. fsion := gofasion.NewFasion(string(dataByte))
  504. sqlParams := fsion.Array()
  505. queryData := make(map[string]interface{})
  506. for _, v := range sqlParams {
  507. fsion2 := gofasion.NewFasion(v.Json())
  508. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  509. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  510. if sql == "" {
  511. errorm := make(map[string]interface{})
  512. errorm["code"] = e.ERROR
  513. errorm["message"] = "sql没找到"
  514. queryData[fsion2.Get("name").ValueStr()] = errorm
  515. continue
  516. } else if sql != "" {
  517. offset := fsion2.Get("offset").ValueInt()
  518. pagecount := fsion2.Get("pagecount").ValueInt()
  519. returntype := fsion2.Get("returntype").ValueStr()
  520. s_params := make([]interface{}, 0)
  521. if fsion2.HasKey("parammaps") {
  522. parammaps := fsion2.Get("parammaps")
  523. paramslist := strings.Split(p, ",")
  524. if len(paramslist) > 0 && p != "" {
  525. for _, value := range paramslist {
  526. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  527. if tempv, exists := c.Get("jwt_username"); exists {
  528. s_params = append(s_params, tempv.(string))
  529. } else {
  530. s_params = append(s_params, "")
  531. }
  532. } else {
  533. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  534. }
  535. }
  536. }
  537. } else if fsion2.HasKey("params") {
  538. params := fsion2.Get("params").Array()
  539. for _, v_params := range params {
  540. s_params = append(s_params, v_params.ValueStr())
  541. }
  542. }
  543. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  544. if err != nil {
  545. errorm := make(map[string]interface{})
  546. errorm["code"] = e.ERROR
  547. errorm["message"] = err.Error()
  548. queryData[fsion2.Get("name").ValueStr()] = errorm
  549. logging.Error("GetDataByNames err: ", err)
  550. continue
  551. } else {
  552. queryData[fsion2.Get("name").ValueStr()] = queryData1
  553. }
  554. }
  555. }
  556. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  557. }
  558. // @Summary 根据APISQL表中SQL执行得到数据集
  559. // @Tags PostDataByNameForm
  560. // @Accept json
  561. // @Produce json
  562. // @Param sqlname query string true "sqlname"
  563. // @Param offset query int true "offset"
  564. // @Param pagecount query int true "pagecount"
  565. // @Param returntype query string true "returntype"
  566. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  567. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  568. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  569. // @Router /data/PostDataByNameForm [POST]
  570. func PostDataByNameForm(c *gin.Context) {
  571. appG := app.Gin{C: c}
  572. c.Request.ParseForm()
  573. params := c.Request.Form
  574. sqlnamestr := params.Get("name")
  575. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  576. s_params := make([]interface{}, 0)
  577. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  578. paramslist := strings.Split(p, ",")
  579. if len(paramslist) > 0 {
  580. for _, value := range paramslist {
  581. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  582. }
  583. }
  584. if sql != "" {
  585. queryData, err := execDataBySql(sql, s_params)
  586. if err != nil {
  587. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  588. } else {
  589. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  590. }
  591. } else {
  592. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  593. }
  594. }
  595. // @Summary 将数据集转换格式
  596. // @Tags PostDataByNameForm
  597. // @Accept json
  598. // @Produce json
  599. // @Param sqlname query string true "sqlname"
  600. // @Param offset query int true "offset"
  601. // @Param pagecount query int true "pagecount"
  602. // @Param returntype query string true "returntype"
  603. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  604. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  605. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  606. func GetReportform(c *gin.Context) {
  607. appG := app.Gin{C: c}
  608. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  609. fsion := gofasion.NewFasion(string(dataByte))
  610. sqlnamestr := fsion.Get("name").ValueStr()
  611. checked := fsion.Get("checked").ValueStr()
  612. offset := fsion.Get("offset").ValueDefaultInt(0)
  613. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  614. parammaps := fsion.Get("parammaps")
  615. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  616. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  617. tx := restful.Engine.NewSession()
  618. err := tx.Begin()
  619. defer func() {
  620. switch {
  621. case err != nil:
  622. if tx != nil {
  623. tx.Rollback()
  624. }
  625. default:
  626. if tx != nil {
  627. err = tx.Commit()
  628. }
  629. }
  630. if tx != nil {
  631. tx.Close()
  632. }
  633. }()
  634. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea)
  635. if err != nil {
  636. appG.Response(http.StatusOK, e.ERROR, err.Error())
  637. } else {
  638. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  639. }
  640. }
  641. //保养计划
  642. func GetUpkeepPlan(c *gin.Context) {
  643. appG := app.Gin{C: c}
  644. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  645. fsion := gofasion.NewFasion(string(dataByte))
  646. sqlnamestr := fsion.Get("name").ValueStr()
  647. offset := fsion.Get("offset").ValueDefaultInt(0)
  648. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  649. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  650. month := fsion.Get("month").ValueDefaultStr("map")
  651. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  652. tx := restful.Engine.NewSession()
  653. err := tx.Begin()
  654. defer func() {
  655. switch {
  656. case err != nil:
  657. if tx != nil {
  658. tx.Rollback()
  659. }
  660. default:
  661. if tx != nil {
  662. err = tx.Commit()
  663. }
  664. }
  665. if tx != nil {
  666. tx.Close()
  667. }
  668. }()
  669. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  670. if sql != "" {
  671. s_params := make([]interface{}, 0)
  672. if fsion.HasKey("parammaps") {
  673. parammaps := fsion.Get("parammaps")
  674. paramslist := strings.Split(p, ",")
  675. if len(paramslist) > 0 && p != "" {
  676. for _, value := range paramslist {
  677. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  678. if tempv, exists := c.Get("jwt_username"); exists {
  679. s_params = append(s_params, tempv.(string))
  680. } else {
  681. s_params = append(s_params, "")
  682. }
  683. } else {
  684. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  685. }
  686. }
  687. }
  688. } else if fsion.HasKey("params") {
  689. params := fsion.Get("params").Array()
  690. for _, v_params := range params {
  691. s_params = append(s_params, v_params.ValueStr())
  692. }
  693. }
  694. if returntype == "xlsx" {
  695. var xlsxfile *xlsx.File
  696. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  697. //c.File("c:/dd.xlsx")
  698. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  699. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  700. c.Header("Content-Transfer-Encoding", "binary")
  701. _ = xlsxfile.Write(c.Writer)
  702. } else {
  703. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  704. if err != nil {
  705. appG.Response(http.StatusOK, e.ERROR, err.Error())
  706. } else {
  707. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  708. if v, ok := value["id"]; ok {
  709. //month = "2020-03"
  710. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  711. if seviceplans != nil {
  712. for _, va := range seviceplans { //根据保养计划获取保养单
  713. //day,_ :=strconv.Atoi(va["day"])
  714. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  715. //buk := make(map[string]map[string]string)
  716. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  717. jstr := ""
  718. if bu["plantime"][8:9] == "0" {
  719. jstr = "m" + bu["plantime"][9:]
  720. } else {
  721. jstr = "m" + bu["plantime"][8:]
  722. }
  723. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  724. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  725. } else {
  726. if bu["flowCompeleted"] >= "2" {
  727. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  728. } else {
  729. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  730. }
  731. }
  732. }
  733. }
  734. }
  735. }
  736. }
  737. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  738. }
  739. }
  740. } else {
  741. appG.Response(http.StatusOK, e.SUCCESS, nil)
  742. }
  743. }
  744. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  745. // todo 优化性能 children统一查询
  746. // @Tags PostDataByNameForm
  747. // @Accept json
  748. // @Produce json
  749. // @Param sqlname query string true "sqlname"
  750. // @Param offset query int true "offset"
  751. // @Param pagecount query int true "pagecount"
  752. // @Param returntype query string true "returntype"
  753. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  754. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  755. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  756. func GetArrList(c *gin.Context) {
  757. appG := app.Gin{C: c}
  758. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  759. fsion := gofasion.NewFasion(string(dataByte))
  760. sqlnamestr := fsion.Get("name").ValueStr()
  761. sqlnamestr1 := fsion.Get("name1").ValueStr()
  762. offset := fsion.Get("offset").ValueDefaultInt(0)
  763. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  764. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  765. month := fsion.Get("month").ValueDefaultStr("map")
  766. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  767. tx := restful.Engine.NewSession()
  768. err := tx.Begin()
  769. defer func() {
  770. switch {
  771. case err != nil:
  772. if tx != nil {
  773. tx.Rollback()
  774. }
  775. default:
  776. if tx != nil {
  777. err = tx.Commit()
  778. }
  779. }
  780. if tx != nil {
  781. tx.Close()
  782. }
  783. }()
  784. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  785. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  786. if sql != "" {
  787. s_params := make([]interface{}, 0)
  788. if fsion.HasKey("parammaps") {
  789. parammaps := fsion.Get("parammaps")
  790. paramslist := strings.Split(p, ",")
  791. if len(paramslist) > 0 && p != "" {
  792. for _, value := range paramslist {
  793. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  794. if tempv, exists := c.Get("jwt_username"); exists {
  795. s_params = append(s_params, tempv.(string))
  796. } else {
  797. s_params = append(s_params, "")
  798. }
  799. } else {
  800. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  801. }
  802. }
  803. }
  804. }
  805. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  806. if err != nil {
  807. appG.Response(http.StatusOK, e.ERROR, err.Error())
  808. } else {
  809. paramslist1 := strings.Split(p1, ",")
  810. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  811. s_params1 := make([]interface{}, 0)
  812. if len(paramslist1) > 0 && p1 != "" {
  813. for _, v := range paramslist1 {
  814. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  815. }
  816. }
  817. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  818. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  819. }
  820. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  821. }
  822. } else {
  823. appG.Response(http.StatusOK, e.SUCCESS, nil)
  824. }
  825. }
  826. func GetAccount(c *gin.Context) {
  827. appG := app.Gin{C: c}
  828. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  829. fsion := gofasion.NewFasion(string(dataByte))
  830. sqlnamestr := fsion.Get("name").ValueStr()
  831. offset := fsion.Get("offset").ValueDefaultInt(0)
  832. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  833. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  834. tx := restful.Engine.NewSession()
  835. err := tx.Begin()
  836. defer func() {
  837. switch {
  838. case err != nil:
  839. logging.Error("tx.Begin 事务启动失败__error:", err)
  840. if tx != nil {
  841. tx.Rollback()
  842. }
  843. default:
  844. if tx != nil {
  845. err = tx.Commit()
  846. }
  847. }
  848. if tx != nil {
  849. tx.Close()
  850. }
  851. }()
  852. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  853. if sql != "" {
  854. s_params := make([]interface{}, 0)
  855. if fsion.HasKey("parammaps") {
  856. parammaps := fsion.Get("parammaps")
  857. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  858. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  859. }
  860. paramslist := strings.Split(p, ",")
  861. if len(paramslist) > 0 && p != "" {
  862. for _, value := range paramslist {
  863. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  864. if tempv, exists := c.Get("jwt_username"); exists {
  865. s_params = append(s_params, tempv.(string))
  866. } else {
  867. s_params = append(s_params, "")
  868. }
  869. } else {
  870. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  871. }
  872. }
  873. }
  874. } else if fsion.HasKey("params") {
  875. params := fsion.Get("params").Array()
  876. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  877. for _, v_params := range params {
  878. s_params = append(s_params, v_params.ValueStr())
  879. }
  880. }
  881. if returntype == "xlsx" {
  882. var xlsxfile *xlsx.File
  883. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  884. //c.File("c:/dd.xlsx")
  885. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  886. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  887. c.Header("Content-Transfer-Encoding", "binary")
  888. _ = xlsxfile.Write(c.Writer)
  889. } else {
  890. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  891. if err != nil {
  892. logging.Error("GetDataByName err: ", err)
  893. msg := geterrmsg(err.Error())
  894. appG.Response(http.StatusOK, e.ERROR, msg)
  895. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  896. } else {
  897. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  898. }
  899. }
  900. } else {
  901. appG.Response(http.StatusOK, e.SUCCESS, nil)
  902. }
  903. }
  904. // @Summary 根据APISQL表中SQL执行得到数据集
  905. // @Tags PostDataByName
  906. // @Accept json
  907. // @Produce json
  908. // @Param sqlname query string true "sqlname"
  909. // @Param offset query int true "offset"
  910. // @Param pagecount query int true "pagecount"
  911. // @Param returntype query string true "returntype"
  912. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  913. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  914. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  915. // @Router /data/PostDataByName [POST]
  916. func PostDataByName(c *gin.Context) {
  917. appG := app.Gin{C: c}
  918. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  919. fsion := gofasion.NewFasion(string(dataByte))
  920. sqlnamestr := fsion.Get("name").ValueStr()
  921. s_params := make([]interface{}, 0)
  922. tx := restful.Engine.NewSession()
  923. err := tx.Begin()
  924. defer func() {
  925. switch {
  926. case err != nil:
  927. if tx != nil {
  928. tx.Rollback()
  929. }
  930. default:
  931. if tx != nil {
  932. err = tx.Commit()
  933. }
  934. }
  935. if tx != nil {
  936. tx.Close()
  937. }
  938. }()
  939. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  940. if sql != "" {
  941. if fsion.HasKey("parammaps") {
  942. parammaps := fsion.Get("parammaps")
  943. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  944. paramslist := strings.Split(p, ",")
  945. if len(paramslist) > 0 && p != "" {
  946. for _, value := range paramslist {
  947. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  948. if tempv, exists := c.Get("jwt_username"); exists {
  949. s_params = append(s_params, tempv.(string))
  950. } else {
  951. s_params = append(s_params, "")
  952. }
  953. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  954. ids, err := setting.SnowIds.NextId()
  955. if err != nil {
  956. ids = time.Now().UnixNano()
  957. logging.Info("create SnowIds err", err)
  958. }
  959. s_params = append(s_params, ids)
  960. } else {
  961. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  962. }
  963. }
  964. }
  965. } else if fsion.HasKey("params") {
  966. params := fsion.Get("params").Array()
  967. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  968. //ids,err := setting.SnowIds.NextId()
  969. //if err !=nil{
  970. // ids = time.Now().UnixNano()
  971. // logging.Info("create SnowIds err",err)
  972. //}
  973. //s_params = append(s_params, ids)
  974. for _, v_params := range params {
  975. s_params = append(s_params, v_params.ValueStr())
  976. }
  977. }
  978. queryData, err := execDataBySqlT(sql, s_params, tx)
  979. if err != nil {
  980. logging.Error("PostDataByName err: ", err)
  981. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  982. if (sqlnamestr == "copybarfeedremain" || sqlnamestr == "copyFtdry" || sqlnamestr == "copyPennsieve") &&
  983. strings.Contains(err.Error(), "Duplicate entry") {
  984. appG.Response(http.StatusOK, e.ERROR, "同一栏舍,同一班次不可重复录入")
  985. } else if (sqlnamestr == "copybarmilk" || sqlnamestr == "copyBodyscore" || sqlnamestr == "copyDungsieve" || sqlnamestr == "copyDungscore") &&
  986. strings.Contains(err.Error(), "Duplicate entry") {
  987. appG.Response(http.StatusOK, e.ERROR, "同一栏舍不可重复录入")
  988. } else {
  989. msg := geterrmsg(err.Error())
  990. appG.Response(http.StatusOK, e.ERROR, msg)
  991. }
  992. } else {
  993. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  994. }
  995. } else {
  996. appG.Response(http.StatusOK, e.SUCCESS, nil)
  997. }
  998. }
  999. //人脸识别/格润富德接口
  1000. func GetRJSBData(c *gin.Context) {
  1001. appG := app.Gin{C: c}
  1002. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1003. fsion := gofasion.NewFasion(string(dataByte))
  1004. sqlnamestr := fsion.Get("name").ValueStr()
  1005. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1006. offset := fsion.Get("offset").ValueDefaultInt(0)
  1007. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1008. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1009. month := fsion.Get("month").ValueDefaultStr("map")
  1010. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1011. tx := restful.Engine.NewSession()
  1012. err := tx.Begin()
  1013. defer func() {
  1014. switch {
  1015. case err != nil:
  1016. if tx != nil {
  1017. tx.Rollback()
  1018. }
  1019. default:
  1020. if tx != nil {
  1021. err = tx.Commit()
  1022. }
  1023. }
  1024. if tx != nil {
  1025. tx.Close()
  1026. }
  1027. }()
  1028. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1029. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1030. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1031. if sql != "" {
  1032. s_params := make([]interface{}, 0)
  1033. if fsion.HasKey("parammaps") {
  1034. parammaps := fsion.Get("parammaps")
  1035. paramslist := strings.Split(p, ",")
  1036. if len(paramslist) > 0 && p != "" {
  1037. for _, value := range paramslist {
  1038. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1039. if tempv, exists := c.Get("jwt_username"); exists {
  1040. s_params = append(s_params, tempv.(string))
  1041. } else {
  1042. s_params = append(s_params, "")
  1043. }
  1044. } else {
  1045. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1046. }
  1047. }
  1048. }
  1049. }
  1050. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1051. if err != nil {
  1052. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1053. } else {
  1054. paramslist1 := strings.Split(p1, ",")
  1055. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1056. s_params1 := make([]interface{}, 0)
  1057. if len(paramslist1) > 0 && p1 != "" {
  1058. for _, v := range paramslist1 {
  1059. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1060. }
  1061. }
  1062. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1063. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1064. }
  1065. var wg sync.WaitGroup
  1066. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1067. wg.Add(1)
  1068. go func(value map[string]interface{}) {
  1069. defer wg.Done()
  1070. _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1071. }(value)
  1072. }
  1073. wg.Wait()
  1074. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1075. }
  1076. } else {
  1077. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1078. }
  1079. }
  1080. func PostRJSBData(c *gin.Context) {
  1081. appG := app.Gin{C: c}
  1082. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1083. fsion := gofasion.NewFasion(string(dataByte))
  1084. logging.Info("PostRJSBData err: ", string(dataByte))
  1085. s_params := make([]interface{}, 0)
  1086. tx := restful.Engine.NewSession()
  1087. err := tx.Begin()
  1088. defer func() {
  1089. switch {
  1090. case err != nil:
  1091. if tx != nil {
  1092. tx.Rollback()
  1093. }
  1094. default:
  1095. if tx != nil {
  1096. err = tx.Commit()
  1097. }
  1098. }
  1099. if tx != nil {
  1100. tx.Close()
  1101. }
  1102. }()
  1103. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1104. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1105. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1106. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1107. if !fsion.HasKey("parammaps") {
  1108. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1109. return
  1110. }
  1111. parammaps := fsion.Get("parammaps")
  1112. paramslist := strings.Split(p, ",")
  1113. if len(paramslist) > 0 && p != "" {
  1114. for _, value := range paramslist {
  1115. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1116. }
  1117. }
  1118. _, err = tx.SQL(sql, s_params...).Execute()
  1119. if err != nil {
  1120. logging.Error("PostRJSBData err: ", err)
  1121. msg := geterrmsg(err.Error())
  1122. appG.Response(http.StatusOK, e.ERROR, msg)
  1123. return
  1124. }
  1125. s_params = make([]interface{}, 0)
  1126. paramslist = strings.Split(p1, ",")
  1127. if len(paramslist) > 0 && p1 != "" {
  1128. for _, value := range paramslist {
  1129. // if value == "ID" {
  1130. // id := parammaps.Get("ID").ValueStr()
  1131. // pastureid := parammaps.Get("pastureid").ValueStr()
  1132. // 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
  1133. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1134. // if err != nil {
  1135. // logging.Error("PostRJSBData err: ", err)
  1136. // msg := geterrmsg(err.Error())
  1137. // appG.Response(http.StatusOK, e.ERROR, msg)
  1138. // return
  1139. // }
  1140. // for _, item := range datalist {
  1141. // id = item["id"]
  1142. // }
  1143. // s_params = append(s_params, id)
  1144. // } else {
  1145. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1146. // }
  1147. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1148. }
  1149. }
  1150. _, err = tx.SQL(sql1, s_params...).Execute()
  1151. if err != nil {
  1152. logging.Error("PostRJSBData1 err: ", err)
  1153. msg := geterrmsg(err.Error())
  1154. appG.Response(http.StatusOK, e.ERROR, msg)
  1155. return
  1156. }
  1157. s_params = make([]interface{}, 0)
  1158. paramslist = strings.Split(p2, ",")
  1159. if len(paramslist) > 0 && p2 != "" {
  1160. for _, value := range paramslist {
  1161. if value == "ID" {
  1162. id := parammaps.Get("ID").ValueStr()
  1163. pastureid := parammaps.Get("pastureid").ValueStr()
  1164. 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
  1165. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1166. if err != nil {
  1167. logging.Error("PostRJSBData err: ", err)
  1168. msg := geterrmsg(err.Error())
  1169. appG.Response(http.StatusOK, e.ERROR, msg)
  1170. return
  1171. }
  1172. for _, item := range datalist {
  1173. id = item["id"]
  1174. }
  1175. s_params = append(s_params, id)
  1176. } else {
  1177. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1178. }
  1179. }
  1180. }
  1181. _, err = tx.SQL(sql2, s_params...).Execute()
  1182. if err != nil {
  1183. logging.Error("PostRJSBData2 err: ", err)
  1184. msg := geterrmsg(err.Error())
  1185. appG.Response(http.StatusOK, e.ERROR, msg)
  1186. return
  1187. }
  1188. s_params = make([]interface{}, 0)
  1189. paramslist = strings.Split(p3, ",")
  1190. if len(paramslist) > 0 && p3 != "" {
  1191. for _, value := range paramslist {
  1192. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1193. }
  1194. }
  1195. _, err = tx.SQL(sql3, s_params...).Execute()
  1196. if err != nil {
  1197. logging.Error("PostRJSBData3 err: ", err)
  1198. msg := geterrmsg(err.Error())
  1199. appG.Response(http.StatusOK, e.ERROR, msg)
  1200. return
  1201. }
  1202. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1203. }
  1204. func PostRJSBDatas(c *gin.Context) {
  1205. appG := app.Gin{C: c}
  1206. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1207. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1208. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1209. tx := restful.Engine.NewSession()
  1210. err := tx.Begin()
  1211. defer func() {
  1212. switch {
  1213. case err != nil:
  1214. if tx != nil {
  1215. tx.Rollback()
  1216. }
  1217. default:
  1218. if tx != nil {
  1219. err = tx.Commit()
  1220. }
  1221. }
  1222. if tx != nil {
  1223. tx.Close()
  1224. }
  1225. }()
  1226. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1227. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1228. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1229. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1230. for _, fsion := range fsions {
  1231. if !fsion.HasKey("parammaps") {
  1232. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1233. return
  1234. }
  1235. parammaps := fsion.Get("parammaps")
  1236. s_params := make([]interface{}, 0)
  1237. paramslist := strings.Split(p, ",")
  1238. if len(paramslist) > 0 && p != "" {
  1239. for _, value := range paramslist {
  1240. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1241. }
  1242. }
  1243. _, err = tx.SQL(sql, s_params...).Execute()
  1244. if err != nil {
  1245. logging.Error("PostRJSBData err: ", err)
  1246. msg := geterrmsg(err.Error())
  1247. appG.Response(http.StatusOK, e.ERROR, msg)
  1248. return
  1249. }
  1250. s_params = make([]interface{}, 0)
  1251. paramslist = strings.Split(p1, ",")
  1252. if len(paramslist) > 0 && p1 != "" {
  1253. for _, value := range paramslist {
  1254. // if value == "ID" {
  1255. // id := parammaps.Get("ID").ValueStr()
  1256. // pastureid := parammaps.Get("pastureid").ValueStr()
  1257. // 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
  1258. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1259. // if err != nil {
  1260. // logging.Error("PostRJSBData err: ", err)
  1261. // msg := geterrmsg(err.Error())
  1262. // appG.Response(http.StatusOK, e.ERROR, msg)
  1263. // return
  1264. // }
  1265. // for _, item := range datalist {
  1266. // id = item["id"]
  1267. // }
  1268. // s_params = append(s_params, id)
  1269. // } else {
  1270. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1271. // }
  1272. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1273. }
  1274. }
  1275. _, err = tx.SQL(sql1, s_params...).Execute()
  1276. if err != nil {
  1277. logging.Error("PostRJSBData1 err: ", err)
  1278. msg := geterrmsg(err.Error())
  1279. appG.Response(http.StatusOK, e.ERROR, msg)
  1280. return
  1281. }
  1282. s_params = make([]interface{}, 0)
  1283. paramslist = strings.Split(p2, ",")
  1284. if len(paramslist) > 0 && p2 != "" {
  1285. for _, value := range paramslist {
  1286. if value == "ID" {
  1287. id := parammaps.Get("ID").ValueStr()
  1288. pastureid := parammaps.Get("pastureid").ValueStr()
  1289. 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
  1290. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1291. if err != nil {
  1292. logging.Error("PostRJSBData err: ", err)
  1293. msg := geterrmsg(err.Error())
  1294. appG.Response(http.StatusOK, e.ERROR, msg)
  1295. return
  1296. }
  1297. for _, item := range datalist {
  1298. id = item["id"]
  1299. }
  1300. s_params = append(s_params, id)
  1301. } else {
  1302. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1303. }
  1304. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1305. }
  1306. }
  1307. _, err = tx.SQL(sql2, s_params...).Execute()
  1308. if err != nil {
  1309. logging.Error("PostRJSBData2 err: ", err)
  1310. msg := geterrmsg(err.Error())
  1311. appG.Response(http.StatusOK, e.ERROR, msg)
  1312. return
  1313. }
  1314. s_params = make([]interface{}, 0)
  1315. paramslist = strings.Split(p3, ",")
  1316. if len(paramslist) > 0 && p3 != "" {
  1317. for _, value := range paramslist {
  1318. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1319. }
  1320. }
  1321. _, err = tx.SQL(sql3, s_params...).Execute()
  1322. if err != nil {
  1323. logging.Error("PostRJSBData3 err: ", err)
  1324. msg := geterrmsg(err.Error())
  1325. appG.Response(http.StatusOK, e.ERROR, msg)
  1326. return
  1327. }
  1328. }
  1329. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1330. }
  1331. // @Summary 根据APISQL表中SQL执行得到数据集
  1332. // @Tags ExecDataByConfig
  1333. // @Accept json
  1334. // @Produce json
  1335. // @Param sqlname query string true "sqlname"
  1336. // @Param offset query int true "offset"
  1337. // @Param pagecount query int true "pagecount"
  1338. // @Param returntype query string true "returntype"
  1339. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1340. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1341. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1342. // @Router /data/PostDataByName [POST]
  1343. func ExecDataByConfig(c *gin.Context) {
  1344. appG := app.Gin{C: c}
  1345. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1346. tempval_ := make(map[string]interface{})
  1347. tempCommon := make(map[string]interface{})
  1348. tempval := make([]map[string]interface{}, 0)
  1349. err := json.Unmarshal(dataByte, &tempval_)
  1350. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1351. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1352. if err != nil {
  1353. } else {
  1354. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1355. tempCommon = v
  1356. }
  1357. if v, ok := tempval_["data"].([]interface{}); ok {
  1358. for _, Tvalue := range v {
  1359. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1360. tempval = append(tempval, v1)
  1361. }
  1362. }
  1363. }
  1364. tx := restful.Engine.NewSession()
  1365. err := tx.Begin()
  1366. if err != nil {
  1367. logging.Error("tx.Begin 事务启动失败__error:", err)
  1368. }
  1369. defer func() {
  1370. switch {
  1371. case err != nil:
  1372. if tx != nil {
  1373. tx.Rollback()
  1374. }
  1375. default:
  1376. if tx != nil {
  1377. err = tx.Commit()
  1378. }
  1379. }
  1380. if tx != nil {
  1381. tx.Close()
  1382. }
  1383. }()
  1384. if err == nil {
  1385. if tempv, exists := c.Get("jwt_username"); exists {
  1386. tempCommon["jwt_username"] = tempv.(string)
  1387. }
  1388. for _, paramvalue := range tempval {
  1389. if _, ok := paramvalue["resultname"]; !ok {
  1390. paramvalue["resultname"] = paramvalue["name"]
  1391. }
  1392. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1393. if err != nil {
  1394. logging.Error("ExecDataParam error:", err)
  1395. break
  1396. }
  1397. }
  1398. if err == nil {
  1399. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1400. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1401. } else {
  1402. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1403. }
  1404. } else {
  1405. msg := geterrmsg(err.Error())
  1406. appG.Response(http.StatusOK, e.ERROR, msg)
  1407. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1408. }
  1409. }
  1410. }
  1411. if err != nil {
  1412. msg := geterrmsg(err.Error())
  1413. appG.Response(http.StatusOK, e.ERROR, msg)
  1414. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1415. }
  1416. }
  1417. func interfacetostring(val interface{}) string {
  1418. switch val.(type) {
  1419. case string:
  1420. ss := val.(string)
  1421. return ss
  1422. break
  1423. case int:
  1424. ss := val.(int)
  1425. return strconv.Itoa(ss)
  1426. break
  1427. case int64:
  1428. ss := val.(int64)
  1429. return strconv.FormatInt(ss, 10)
  1430. break
  1431. case float64:
  1432. ss := val.(float64)
  1433. return strconv.FormatFloat(ss, 'E', -1, 32)
  1434. break
  1435. }
  1436. return ""
  1437. }
  1438. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1439. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1440. tempstrb := strings.IndexAny(valuestring, "@")
  1441. tempstre := strings.IndexAny(valuestring, ".")
  1442. if tempstrb > -1 && tempstre > -1 {
  1443. for _, ParamMapList := range ParamMap {
  1444. if v, ok := ParamMapList["resultname"]; ok {
  1445. if v == valuestring[tempstrb+1:tempstre] {
  1446. if v1, ok := ParamMapList["resultmaps"]; ok {
  1447. if newA, ok := v1.([]map[string]interface{}); ok {
  1448. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1449. } else if newA, ok := v1.(map[string]interface{}); ok {
  1450. return interfacetostring(newA[valuestring[tempstre+1:]])
  1451. }
  1452. }
  1453. }
  1454. }
  1455. }
  1456. } else {
  1457. return valuestring
  1458. }
  1459. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1460. return strconv.FormatInt(int64(valuestring), 10)
  1461. }
  1462. return ""
  1463. }
  1464. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1465. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1466. tempstrb := strings.IndexAny(valuestring, "@")
  1467. tempstre := strings.IndexAny(valuestring, ".")
  1468. if tempstrb > -1 && tempstre > -1 {
  1469. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1470. if s, ok := v.(string); ok {
  1471. return s
  1472. } else if s, ok := v.(float64); ok {
  1473. return strconv.FormatFloat(s, 'f', -1, 64)
  1474. // return strconv.FormatInt(int64(s), 10)
  1475. }
  1476. }
  1477. }
  1478. }
  1479. return ""
  1480. }
  1481. 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) {
  1482. sqlname := fasion["name"].(string)
  1483. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1484. if v, ok := fasion["type"]; ok {
  1485. sqltype = v.(string)
  1486. }
  1487. sql := ""
  1488. p := ""
  1489. s_params := make([]interface{}, 0)
  1490. if sqltype != "" {
  1491. sql, p = restful.GetSqlByName(sqlname, tx)
  1492. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1493. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1494. paramslist := strings.Split(p, ",")
  1495. if len(paramslist) > 0 && p != "" {
  1496. for _, value := range paramslist {
  1497. ss := ""
  1498. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1499. ids, err := setting.SnowIds.NextId()
  1500. if err != nil {
  1501. ids = time.Now().UnixNano()
  1502. logging.Info("create SnowIds err", err)
  1503. }
  1504. s_params = append(s_params, ids)
  1505. } else {
  1506. if ss == "" && CommonParamMap != nil {
  1507. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1508. ss = valuestring
  1509. tempstrb := strings.IndexAny(valuestring, "@")
  1510. tempstre := strings.IndexAny(valuestring, ".")
  1511. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1512. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1513. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1514. }
  1515. } else {
  1516. ss = ""
  1517. }
  1518. }
  1519. }
  1520. if ss == "" && ParentParamMap != nil {
  1521. ss = getParamValue_(v, value, ParentParamMap)
  1522. }
  1523. if ss == "" && sameParamMap != nil {
  1524. ss = getParamValue(v, value, sameParamMap)
  1525. }
  1526. if ss == "" && ParamMap != nil {
  1527. ss = getParamValue(v, value, ParamMap)
  1528. }
  1529. s_params = append(s_params, ss)
  1530. }
  1531. }
  1532. }
  1533. }
  1534. }
  1535. if sql == "" {
  1536. sqltype = ""
  1537. }
  1538. if sqltype == "s1" {
  1539. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1540. if v, ok := tempValParam.(map[string]interface{}); ok {
  1541. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1542. }
  1543. if err != nil {
  1544. return nil, err
  1545. }
  1546. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1547. if err != nil {
  1548. return nil, err
  1549. }
  1550. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1551. } else if sqltype == "sm" {
  1552. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1553. if v, ok := tempValParam.(map[string]interface{}); ok {
  1554. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1555. } else {
  1556. }
  1557. if err != nil {
  1558. return nil, err
  1559. }
  1560. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1561. if err != nil {
  1562. return nil, err
  1563. }
  1564. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1565. } else if sqltype == "v" {
  1566. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1567. if v, ok := tempValParam.(map[string]interface{}); ok {
  1568. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1569. } else {
  1570. }
  1571. if err != nil {
  1572. return nil, err
  1573. }
  1574. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1575. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1576. }
  1577. } else if sqltype == "e" {
  1578. tempVal_arrary := make([]map[string]interface{}, 0)
  1579. tempVal_map := make(map[string]interface{})
  1580. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1581. if err == nil {
  1582. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1583. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1584. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1585. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1586. return tempVal_arrary, err
  1587. }
  1588. return nil, err
  1589. } else {
  1590. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1591. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1592. if err != nil {
  1593. return nil, err
  1594. }
  1595. return nil, err
  1596. }
  1597. }
  1598. return nil, nil
  1599. }
  1600. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1601. var err error
  1602. subarray, ok := fasion["children"]
  1603. if ok {
  1604. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1605. tempVal_arrary := make([]map[string]interface{}, 0)
  1606. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1607. tempVal_ := make(map[string]interface{})
  1608. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1609. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1610. } else {
  1611. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1612. }
  1613. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1614. if err != nil {
  1615. return err
  1616. }
  1617. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1618. }
  1619. v.(map[string]interface{})["children"] = tempVal_arrary
  1620. }
  1621. }
  1622. return nil
  1623. }
  1624. // @Summary 删除图片
  1625. // @Tags RemovePicByName
  1626. // @Accept json
  1627. // @Produce json
  1628. // @Param sqlname query string true "sqlname"
  1629. // @Param offset query int true "offset"
  1630. // @Param pagecount query int true "pagecount"
  1631. // @Param returntype query string true "returntype"
  1632. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1633. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1634. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1635. // @Router /data/PostDataByName [POST]
  1636. func RemovePicByName(c *gin.Context) {
  1637. logging.Info("RemovePicByName ", c.Keys)
  1638. appG := app.Gin{C: c}
  1639. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1640. fsion := gofasion.NewFasion(string(dataByte))
  1641. sqlnamestr := fsion.Get("name").ValueStr()
  1642. picname := fsion.Get("picname").ValueStr()
  1643. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1644. params := fsion.Get("params").Array()
  1645. s_params := make([]interface{}, 0)
  1646. for _, v_params := range params {
  1647. s_params = append(s_params, v_params.ValueStr())
  1648. }
  1649. if sql != "" {
  1650. queryData, err := execDataBySql(sql, s_params)
  1651. if picname != "" {
  1652. // Destination
  1653. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1654. err := os.Remove(distPath) //删除文件test.txt
  1655. if err != nil {
  1656. //如果删除失败则输出 file remove Error!
  1657. fmt.Println("file remove Error!")
  1658. //输出错误详细信息
  1659. fmt.Printf("%s", err)
  1660. } else {
  1661. //如果删除成功则输出 file remove OK!
  1662. fmt.Print("file remove OK!")
  1663. }
  1664. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1665. err = os.Remove(distPath) //删除文件test.txt
  1666. if err != nil {
  1667. //如果删除失败则输出 file remove Error!
  1668. fmt.Println("file remove Error!")
  1669. //输出错误详细信息
  1670. fmt.Printf("%s", err)
  1671. } else {
  1672. //如果删除成功则输出 file remove OK!
  1673. fmt.Print("file remove OK!")
  1674. }
  1675. }
  1676. if err != nil {
  1677. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1678. } else {
  1679. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1680. }
  1681. } else {
  1682. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1683. }
  1684. }
  1685. // @Summary 删除文件
  1686. // @Tags RemoveFileByName
  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 RemoveFileByName(c *gin.Context) {
  1698. appG := app.Gin{C: c}
  1699. id := c.Param("id")
  1700. logging.Info("DownloadFile ", c.Keys, id)
  1701. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1702. if eqdoc == nil {
  1703. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1704. return
  1705. }
  1706. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1707. err = os.Remove(distPath) //删除文件test.txt
  1708. if err != nil {
  1709. //如果删除失败则输出 file remove Error!
  1710. fmt.Println("file remove Error!")
  1711. //输出错误详细信息
  1712. fmt.Printf("%s", err)
  1713. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1714. return
  1715. }
  1716. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1717. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1718. }
  1719. // @Summary 根据APISQL表中SQL执行得到数据集
  1720. // @Tags PostDataByName
  1721. // @Accept json
  1722. // @Produce json
  1723. // @Param sqlname query string true "sqlname"
  1724. // @Param offset query int true "offset"
  1725. // @Param pagecount query int true "pagecount"
  1726. // @Param returntype query string true "returntype"
  1727. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1728. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1729. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1730. // @Router /data/PostDataByName [POST]
  1731. func UpdateDataRelation(c *gin.Context) {
  1732. appG := app.Gin{C: c}
  1733. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1734. fsion := gofasion.NewFasion(string(dataByte))
  1735. tablename := fsion.Get("name").ValueStr()
  1736. dataname := fsion.Get("dataname").ValueStr()
  1737. datavalue := fsion.Get("datavalue").ValueStr()
  1738. valuename := fsion.Get("valuename").ValueStr()
  1739. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1740. values := fsion.Get("values").Array()
  1741. tx := restful.Engine.NewSession()
  1742. err := tx.Begin()
  1743. defer func() {
  1744. switch {
  1745. case err != nil:
  1746. if tx != nil {
  1747. tx.Rollback()
  1748. }
  1749. default:
  1750. if tx != nil {
  1751. err = tx.Commit()
  1752. }
  1753. }
  1754. if tx != nil {
  1755. tx.Close()
  1756. }
  1757. }()
  1758. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1759. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1760. d_params := make([]interface{}, 4)
  1761. d_params[0] = datavalue
  1762. s_params := ""
  1763. for _, v_values := range values {
  1764. d_params[1] = v_values.ValueStr()
  1765. if s_params == "" {
  1766. s_params = v_values.ValueStr()
  1767. } else {
  1768. s_params = s_params + "," + v_values.ValueStr()
  1769. }
  1770. d_params[2] = d_params[1]
  1771. d_params[3] = d_params[0]
  1772. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1773. if err != nil {
  1774. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1775. break
  1776. }
  1777. }
  1778. if s_params != "" {
  1779. deleteSqlstr := "delete from " + tablename + " " +
  1780. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1781. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1782. if err != nil {
  1783. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1784. } else if err == nil {
  1785. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1786. }
  1787. } else {
  1788. deleteSqlstr := "delete from " + tablename + " " +
  1789. " where " + dataname + " = " + datavalue
  1790. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1791. if err != nil {
  1792. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1793. } else if err == nil {
  1794. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1795. }
  1796. }
  1797. }
  1798. // @Summary 根据APISQL表中SQL执行得到数据集
  1799. // @Tags PostDatasByName
  1800. // @Accept json
  1801. // @Produce json
  1802. // @Param sqlname query string true "sqlname"
  1803. // @Param offset query int true "offset"
  1804. // @Param pagecount query int true "pagecount"
  1805. // @Param returntype query string true "returntype"
  1806. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1807. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1808. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1809. // @Router /data/PostDatasByName [POST]
  1810. func PostDataByNames(c *gin.Context) {
  1811. appG := app.Gin{C: c}
  1812. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1813. fsion := gofasion.NewFasion(string(dataByte))
  1814. sqlParams := fsion.Get("array").Array()
  1815. queryData := make(map[string]interface{})
  1816. for _, v := range sqlParams {
  1817. fsion2 := gofasion.NewFasion(v.Json())
  1818. ss := fsion2.Get("name")
  1819. aa := fsion2.Get("params")
  1820. fmt.Println(ss, aa)
  1821. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1822. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1823. if sql == "" {
  1824. errorm := make(map[string]interface{})
  1825. errorm["code"] = e.ERROR
  1826. errorm["message"] = "sql没有找到"
  1827. errorm["param"] = ""
  1828. queryData[fsion2.Get("name").ValueStr()] = errorm
  1829. continue
  1830. } else if sql != "" {
  1831. s_params := make([]interface{}, 0)
  1832. if fsion2.HasKey("parammaps") {
  1833. parammaps := fsion2.Get("parammaps")
  1834. paramslist := strings.Split(p, ",")
  1835. if len(paramslist) > 0 && p != "" {
  1836. for _, value := range paramslist {
  1837. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1838. if tempv, exists := c.Get("jwt_username"); exists {
  1839. s_params = append(s_params, tempv.(string))
  1840. } else {
  1841. s_params = append(s_params, "")
  1842. }
  1843. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1844. ids, err := setting.SnowIds.NextId()
  1845. if err != nil {
  1846. ids = time.Now().UnixNano()
  1847. logging.Info("create SnowIds err", err)
  1848. }
  1849. s_params = append(s_params, ids)
  1850. } else {
  1851. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1852. }
  1853. }
  1854. }
  1855. } else if fsion2.HasKey("params") {
  1856. params := fsion2.Get("params").Array()
  1857. //ids,err := setting.SnowIds.NextId()
  1858. //if err !=nil{
  1859. // ids = time.Now().UnixNano()
  1860. // logging.Info("create SnowIds err",err)
  1861. //}
  1862. //s_params = append(s_params, ids)
  1863. for _, v_params := range params {
  1864. s_params = append(s_params, v_params.ValueStr())
  1865. }
  1866. }
  1867. _, err := execDataBySql(sql, s_params)
  1868. if err != nil {
  1869. logging.Error("PostDataByName err: ", err)
  1870. errorm := make(map[string]interface{})
  1871. errorm["code"] = e.ERROR
  1872. errorm["message"] = err.Error()
  1873. errorm["param"] = s_params
  1874. queryData[fsion2.Get("name").ValueStr()] = errorm
  1875. continue
  1876. } else {
  1877. errorm := make(map[string]interface{})
  1878. errorm["code"] = e.SUCCESS
  1879. errorm["message"] = "success"
  1880. queryData[fsion2.Get("name").ValueStr()] = errorm
  1881. continue
  1882. }
  1883. } else {
  1884. errorm := make(map[string]interface{})
  1885. errorm["code"] = e.ERROR
  1886. errorm["message"] = "NO SQL"
  1887. errorm["param"] = ""
  1888. queryData[fsion2.Get("name").ValueStr()] = errorm
  1889. }
  1890. }
  1891. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1892. }
  1893. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1894. if offset > 0 {
  1895. offset = offset - 1
  1896. }
  1897. //if pagecount == 0 {
  1898. // pagecount = setting.AppSetting.PageSize
  1899. //}else if pagecount>setting.AppSetting.PageSize{
  1900. // pagecount = setting.AppSetting.PageSize
  1901. //}
  1902. if returntype == "list" {
  1903. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1904. return queryData, err
  1905. } else if returntype == "listlist" {
  1906. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1907. return queryData, err
  1908. } else {
  1909. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1910. return queryData, err
  1911. }
  1912. }
  1913. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1914. if offset > 0 {
  1915. offset = offset - 1
  1916. }
  1917. //if pagecount == 0 {
  1918. // pagecount = setting.AppSetting.PageSize
  1919. //}else if pagecount>setting.AppSetting.PageSize{
  1920. // pagecount = setting.AppSetting.PageSize
  1921. //}
  1922. if returntype == "list" {
  1923. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1924. return queryData, err
  1925. } else if returntype == "listlist" {
  1926. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1927. return queryData, err
  1928. } else {
  1929. fmt.Println(params)
  1930. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1931. return queryData, err
  1932. }
  1933. }
  1934. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1935. paramslist := strings.Split(Params, ",")
  1936. s_params := make([]interface{}, 0)
  1937. if isList {
  1938. for _, v_params := range thisParams["params"].([]interface{}) {
  1939. s_params = append(s_params, v_params)
  1940. }
  1941. } else {
  1942. paramslist := strings.Split(Params, ",")
  1943. if len(paramslist) > 0 && Params != "" {
  1944. for _, value := range paramslist {
  1945. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1946. }
  1947. }
  1948. }
  1949. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1950. for _, queryData_ := range queryData {
  1951. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1952. if isList {
  1953. if queryData_[idname] != nil {
  1954. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1955. }
  1956. } else {
  1957. if queryData_[idname] != nil {
  1958. thisParams[idname] = queryData_[idname].(interface{})
  1959. }
  1960. if len(paramslist) > 0 && Params != "" {
  1961. s_params = make([]interface{}, 0)
  1962. for _, value := range paramslist {
  1963. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1964. }
  1965. }
  1966. }
  1967. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1968. } else {
  1969. }
  1970. }
  1971. return queryData, err
  1972. }
  1973. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1974. queryData, err := restful.ExecQuery(sqlstr, params)
  1975. return queryData, err
  1976. }
  1977. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1978. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1979. return queryData, err
  1980. }
  1981. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1982. queryData, err := restful.ExecQuery(sqlstr, params)
  1983. return queryData, err
  1984. }
  1985. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1986. // @Tags ImportExcel
  1987. // @Accept json
  1988. // @Produce json
  1989. // @Param file query string true "文件名"
  1990. // @Param name header string true "执行sql的名字"
  1991. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1992. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1993. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1994. // @Router /data/ImportExcel [POST]
  1995. func ImportExcel(c *gin.Context) {
  1996. appG := app.Gin{C: c}
  1997. inputdata := ""
  1998. c.Request.ParseForm()
  1999. params := c.Request.Form
  2000. file, _, err := c.Request.FormFile("file")
  2001. if err != nil {
  2002. appG.Response(http.StatusOK, e.ERROR, err)
  2003. return
  2004. }
  2005. sqlnamestrs := params.Get("name")
  2006. sheetname := params.Get("sheetname")
  2007. pastureid := params.Get("pastureid")
  2008. //importParams := params.Get("importParams")
  2009. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2010. // 必输项参数 (字符串格式 "field1,field2,field3")
  2011. requiredParams := params.Get("requiredParams")
  2012. // 日期参数
  2013. dateParams := params.Get("dateParams")
  2014. // 数字参数
  2015. numParams := params.Get("numParams")
  2016. //将字符串分割开
  2017. dateParamslist := strings.Split(dateParams, ",")
  2018. requiredParamslist := strings.Split(requiredParams, ",")
  2019. numParamslist := strings.Split(numParams, ",")
  2020. queryData := make([]interface{}, 0)
  2021. sqlslist := strings.Split(sqlnamestrs, ",")
  2022. xlsx1, err := excelize.OpenReader(file)
  2023. if err != nil {
  2024. fmt.Println(err)
  2025. return
  2026. }
  2027. ok := 0
  2028. error := 0
  2029. isdone := true
  2030. rows, _ := xlsx1.GetRows(sheetname)
  2031. // 限制10000条,多余的截取掉
  2032. if len(rows) > 10000 {
  2033. rows = rows[:10000]
  2034. }
  2035. for i, row := range rows {
  2036. if i > 0 {
  2037. entry := make(map[string]interface{})
  2038. outentry := make(map[string]interface{})
  2039. for j, colCell := range rows[0] {
  2040. for k, colCell1 := range row {
  2041. if j == k {
  2042. outentry[colCell] = colCell1
  2043. entry[colCell] = colCell1
  2044. }
  2045. }
  2046. }
  2047. inputdata = ""
  2048. a := ""
  2049. fmt.Println(outentry, entry)
  2050. //校验日期格式
  2051. for _, v := range dateParamslist {
  2052. if v == "" {
  2053. continue
  2054. }
  2055. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2056. dtime, err := TransfTime(d.(string))
  2057. if err != nil {
  2058. a = strings.Trim(v, " ")
  2059. break
  2060. }
  2061. outentry[strings.Trim(v, " ")] = dtime
  2062. }
  2063. }
  2064. if a != "" {
  2065. outentry["error_msg"] = a + " 格式错误"
  2066. error++
  2067. queryData = append(queryData, outentry)
  2068. continue
  2069. }
  2070. a = ""
  2071. //校验必填格式
  2072. for _, v := range requiredParamslist {
  2073. if v == "" {
  2074. continue
  2075. }
  2076. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2077. a = strings.Trim(v, " ")
  2078. break
  2079. }
  2080. }
  2081. if a != "" {
  2082. outentry["error_msg"] = a + " 未填或格式错误"
  2083. error++
  2084. queryData = append(queryData, outentry)
  2085. continue
  2086. }
  2087. a = ""
  2088. //校验数字格式
  2089. for _, v := range numParamslist {
  2090. if v == "" {
  2091. continue
  2092. }
  2093. d, ok := outentry[strings.Trim(v, " ")]
  2094. if !ok || d == "" {
  2095. outentry[strings.Trim(v, " ")] = 0
  2096. } else {
  2097. var fl float64
  2098. switch d.(type) {
  2099. case string:
  2100. fl, err = strconv.ParseFloat(d.(string), 64)
  2101. }
  2102. if err != nil || fl < 0 {
  2103. a = strings.Trim(v, " ")
  2104. break
  2105. }
  2106. }
  2107. }
  2108. if a != "" {
  2109. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2110. error++
  2111. queryData = append(queryData, outentry)
  2112. continue
  2113. }
  2114. tx := restful.Engine.NewSession()
  2115. err := tx.Begin()
  2116. for _, sqlnamestr := range sqlslist {
  2117. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2118. paramslist := strings.Split(paramslists, ",")
  2119. if len(paramslist) > 0 {
  2120. s_params := make([]interface{}, 0)
  2121. for _, value := range paramslist {
  2122. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2123. if tempv, exists := c.Get("jwt_username"); exists {
  2124. s_params = append(s_params, tempv.(string))
  2125. } else {
  2126. s_params = append(s_params, "")
  2127. }
  2128. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2129. s_params = append(s_params, pastureid)
  2130. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2131. ids, err := setting.SnowIds.NextId()
  2132. if err != nil {
  2133. ids = time.Now().UnixNano()
  2134. logging.Info("create SnowIds err", err)
  2135. }
  2136. s_params = append(s_params, ids)
  2137. } else {
  2138. if outentry[strings.Trim(value, " ")] == nil {
  2139. s_params = append(s_params, "")
  2140. } else {
  2141. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2142. }
  2143. }
  2144. }
  2145. outentry["input"] = inputdata
  2146. fmt.Println(sql, s_params)
  2147. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2148. if err != nil {
  2149. if tx != nil {
  2150. tx.Rollback()
  2151. }
  2152. if tx != nil {
  2153. tx.Close()
  2154. }
  2155. msg := geterrmsg(err.Error())
  2156. outentry["error_msg"] = msg
  2157. error++
  2158. queryData = append(queryData, outentry)
  2159. isdone = true
  2160. break
  2161. } else {
  2162. if len(returnmsgmap1) > 0 {
  2163. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2164. if tx != nil {
  2165. tx.Rollback()
  2166. }
  2167. if tx != nil {
  2168. tx.Close()
  2169. }
  2170. msg := geterrmsg(va.(string))
  2171. outentry["error_msg"] = msg
  2172. error++
  2173. queryData = append(queryData, outentry)
  2174. isdone = true
  2175. break
  2176. }
  2177. }
  2178. isdone = false
  2179. }
  2180. }
  2181. }
  2182. switch {
  2183. case err != nil:
  2184. if tx != nil {
  2185. tx.Rollback()
  2186. }
  2187. default:
  2188. if tx != nil {
  2189. err = tx.Commit()
  2190. }
  2191. }
  2192. if tx != nil {
  2193. tx.Close()
  2194. }
  2195. }
  2196. if !isdone {
  2197. ok++
  2198. isdone = true
  2199. }
  2200. }
  2201. data := make(map[string]interface{})
  2202. data["result"] = queryData
  2203. data["success"] = ok
  2204. data["err_count"] = error
  2205. appG.Response(http.StatusOK, e.SUCCESS, data)
  2206. }
  2207. func TransfTime(timestr string) (string, error) {
  2208. if timestr == "" {
  2209. return time.Now().Format("2006-01-02"), nil
  2210. }
  2211. days, err := strconv.Atoi(timestr)
  2212. if err != nil {
  2213. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2214. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2215. }
  2216. _, err := time.Parse("2006-01-02", timestr)
  2217. if err != nil {
  2218. t, err := time.Parse("2006/01/02", timestr)
  2219. if err != nil {
  2220. t, err := time.Parse("2006.01.02", timestr)
  2221. if err != nil {
  2222. return "", err
  2223. } else {
  2224. return t.Format("2006-01-02"), nil
  2225. }
  2226. } else {
  2227. return t.Format("2006-01-02"), nil
  2228. }
  2229. } else {
  2230. return timestr, nil
  2231. }
  2232. }
  2233. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2234. times = times.AddDate(0, 0, days)
  2235. return times.Format("2006-01-02"), nil
  2236. }
  2237. func Createchart(c *gin.Context) {
  2238. appG := app.Gin{C: c}
  2239. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2240. fsion := gofasion.NewFasion(string(dataByte))
  2241. chart_name := fsion.Get("chart_name").ValueStr()
  2242. desc := fsion.Get("desc").ValueStr()
  2243. pastureid := fsion.Get("pastureid").ValueStr()
  2244. source_id := fsion.Get("source_id").ValueStr()
  2245. emp := fsion.Get("emp").ValueStr()
  2246. content := fsion.Get("content").Json()
  2247. var mapResult map[string]interface{}
  2248. err1 := json.Unmarshal([]byte(content), &mapResult)
  2249. if err1 != nil {
  2250. fmt.Println("JsonToMapDemo err: ", err1)
  2251. }
  2252. tx := restful.Engine.NewSession()
  2253. err := tx.Begin()
  2254. defer func() {
  2255. switch {
  2256. case err != nil:
  2257. logging.Error("tx.Begin 事务启动失败__error:", err)
  2258. if tx != nil {
  2259. tx.Rollback()
  2260. }
  2261. default:
  2262. if tx != nil {
  2263. err = tx.Commit()
  2264. }
  2265. }
  2266. if tx != nil {
  2267. tx.Close()
  2268. }
  2269. }()
  2270. ids, err := setting.SnowIds.NextId()
  2271. if err != nil {
  2272. ids = time.Now().UnixNano()
  2273. logging.Info("create SnowIds err", err)
  2274. }
  2275. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2276. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2277. if err != nil {
  2278. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2279. } else {
  2280. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2281. }
  2282. }
  2283. func Updatedashboard(c *gin.Context) {
  2284. appG := app.Gin{C: c}
  2285. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2286. fsion := gofasion.NewFasion(string(dataByte))
  2287. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2288. pastureid := fsion.Get("pastureid").ValueStr()
  2289. content := fsion.Get("content").Json()
  2290. var mapResult map[string]interface{}
  2291. err1 := json.Unmarshal([]byte(content), &mapResult)
  2292. if err1 != nil {
  2293. fmt.Println("JsonToMapDemo err: ", err1)
  2294. }
  2295. layout := mapResult["layout"]
  2296. tx := restful.Engine.NewSession()
  2297. err := tx.Begin()
  2298. defer func() {
  2299. switch {
  2300. case err != nil:
  2301. logging.Error("tx.Begin 事务启动失败__error:", err)
  2302. if tx != nil {
  2303. tx.Rollback()
  2304. }
  2305. default:
  2306. if tx != nil {
  2307. err = tx.Commit()
  2308. }
  2309. }
  2310. if tx != nil {
  2311. tx.Close()
  2312. }
  2313. }()
  2314. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2315. if err != nil {
  2316. println("2", err.Error())
  2317. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2318. } else {
  2319. if exec != nil {
  2320. if exec[0]["content"] == nil {
  2321. mapR := make(map[string]interface{})
  2322. mapR["layout"] = layout
  2323. mjson, _ := json.Marshal(mapR)
  2324. mString := string(mjson)
  2325. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2326. if err3 != nil {
  2327. println("3", err3.Error())
  2328. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2329. } else {
  2330. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2331. }
  2332. } else {
  2333. var mapR map[string]interface{}
  2334. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2335. if err1 != nil {
  2336. fmt.Println("JsonToMapDemo err: ", err2)
  2337. }
  2338. mapR["layout"] = layout
  2339. mjson, _ := json.Marshal(mapR)
  2340. mString := string(mjson)
  2341. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2342. if err3 != nil {
  2343. println("3", err3.Error())
  2344. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2345. } else {
  2346. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2347. }
  2348. }
  2349. } else {
  2350. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2351. }
  2352. }
  2353. }
  2354. func ExecSQL(c *gin.Context) {
  2355. appG := app.Gin{C: c}
  2356. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2357. fsion := gofasion.NewFasion(string(dataByte))
  2358. content := fsion.Get("content").Json()
  2359. pastureid := fsion.Get("pastureid").ValueStr()
  2360. var mapResult map[string]interface{}
  2361. err1 := json.Unmarshal([]byte(content), &mapResult)
  2362. if err1 != nil {
  2363. fmt.Println("JsonToMapDemo err: ", err1)
  2364. }
  2365. sqlstr := "select "
  2366. groupstr := " GROUP BY "
  2367. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2368. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2369. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2370. }
  2371. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2372. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2373. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2374. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2375. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2376. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2377. sqlstr = sqlstr + tem + ","
  2378. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2379. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2380. sqlstr = sqlstr + tem + ","
  2381. } else {
  2382. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2383. sqlstr = sqlstr + tem + ","
  2384. }
  2385. }
  2386. if _, ok := mapResult["selectedCalcul2"]; ok {
  2387. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2388. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2389. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2390. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2391. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2392. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2393. sqlstr = sqlstr + tem + ","
  2394. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2395. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2396. sqlstr = sqlstr + tem + ","
  2397. } else {
  2398. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2399. sqlstr = sqlstr + tem + ","
  2400. }
  2401. }
  2402. }
  2403. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2404. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2405. sqlstr = sqlstr + " where pastureid=" + pastureid
  2406. if len(mapResult["filters"].([]interface{})) > 0 {
  2407. sqlstr = sqlstr + " and "
  2408. }
  2409. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2410. for _, value := range mapResult["filters"].([]interface{}) {
  2411. switch value.(map[string]interface{})["filterOperator"].(string) {
  2412. case ">", "=", "<", ">=", "<=", "!=", "like":
  2413. 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 "
  2414. case "IN":
  2415. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2416. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2417. sqlstr = sqlstr + value1.(string) + ","
  2418. }
  2419. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2420. sqlstr = sqlstr + ")" + " AND "
  2421. case "BETWEEN":
  2422. 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 "
  2423. }
  2424. }
  2425. if len(mapResult["filters"].([]interface{})) > 0 {
  2426. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2427. }
  2428. //
  2429. groupstr = groupstr[0 : len(groupstr)-1]
  2430. sqlstr = sqlstr + groupstr + " "
  2431. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2432. sqlstr = sqlstr + " order by "
  2433. }
  2434. //
  2435. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2436. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2437. sqlstr = sqlstr + value.(string) + " "
  2438. } else {
  2439. sqlstr = sqlstr + value.(string) + ","
  2440. }
  2441. }
  2442. //
  2443. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2444. tx := restful.Engine.NewSession()
  2445. err := tx.Begin()
  2446. defer func() {
  2447. switch {
  2448. case err != nil:
  2449. logging.Error("tx.Begin 事务启动失败__error:", err)
  2450. if tx != nil {
  2451. tx.Rollback()
  2452. }
  2453. default:
  2454. if tx != nil {
  2455. err = tx.Commit()
  2456. }
  2457. }
  2458. if tx != nil {
  2459. tx.Close()
  2460. }
  2461. }()
  2462. exec, err := tx.SQL(sqlstr).Query().List()
  2463. if err != nil {
  2464. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2465. } else {
  2466. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2467. }
  2468. }
  2469. func Dashboards(c *gin.Context) {
  2470. appG := app.Gin{C: c}
  2471. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2472. fsion := gofasion.NewFasion(string(dataByte))
  2473. sqlnamestr := fsion.Get("name").ValueStr()
  2474. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2475. offset := fsion.Get("offset").ValueDefaultInt(0)
  2476. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2477. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2478. month := fsion.Get("month").ValueDefaultStr("map")
  2479. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2480. tx := restful.Engine.NewSession()
  2481. err := tx.Begin()
  2482. defer func() {
  2483. switch {
  2484. case err != nil:
  2485. if tx != nil {
  2486. tx.Rollback()
  2487. }
  2488. default:
  2489. if tx != nil {
  2490. err = tx.Commit()
  2491. }
  2492. }
  2493. if tx != nil {
  2494. tx.Close()
  2495. }
  2496. }()
  2497. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2498. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2499. if sql != "" {
  2500. s_params := make([]interface{}, 0)
  2501. if fsion.HasKey("parammaps") {
  2502. parammaps := fsion.Get("parammaps")
  2503. paramslist := strings.Split(p, ",")
  2504. if len(paramslist) > 0 && p != "" {
  2505. for _, value := range paramslist {
  2506. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2507. if tempv, exists := c.Get("jwt_username"); exists {
  2508. s_params = append(s_params, tempv.(string))
  2509. } else {
  2510. s_params = append(s_params, "")
  2511. }
  2512. } else {
  2513. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2514. }
  2515. }
  2516. }
  2517. }
  2518. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2519. if err != nil {
  2520. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2521. } else {
  2522. //paramslist1 := strings.Split(p1, ",")
  2523. dids := make([]interface{}, 0)
  2524. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2525. var mapResult map[string]interface{}
  2526. dids = append(dids, value["dashboard_id"])
  2527. if value["content"] != nil {
  2528. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2529. if err1 != nil {
  2530. println("JsonToMapDemo1 err: ", err1)
  2531. }
  2532. temap := make(map[string]interface{})
  2533. tem := mapResult["layout"].([]interface{})
  2534. if v, ok := value["chartids"]; ok {
  2535. chartids := strings.Split(v.(string), ",")
  2536. for _, va := range chartids {
  2537. a := false
  2538. for _, v2 := range tem {
  2539. if v2.(map[string]interface{})["id"].(string) == va {
  2540. a = true
  2541. //println("va1======",va)
  2542. }
  2543. }
  2544. if !a {
  2545. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2546. va + "\",\"id\":\"" + va +
  2547. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2548. var mapTem map[string]interface{}
  2549. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2550. if err1 != nil {
  2551. println("JsonToMapDemo err: ", err1)
  2552. }
  2553. tem = append(tem, mapTem)
  2554. }
  2555. }
  2556. temap["layout"] = tem
  2557. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2558. }
  2559. } else {
  2560. temap := make(map[string]interface{})
  2561. tem := make([]interface{}, 0)
  2562. if v, ok := value["chartids"]; ok {
  2563. chartids := strings.Split(v.(string), ",")
  2564. for _, va := range chartids {
  2565. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2566. va + "\",\"id\":\"" + va +
  2567. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2568. var mapTem map[string]interface{}
  2569. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2570. if err1 != nil {
  2571. println("JsonToMapDemo err: ", err1)
  2572. }
  2573. tem = append(tem, mapTem)
  2574. }
  2575. temap["layout"] = tem
  2576. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2577. }
  2578. }
  2579. }
  2580. queryData.(map[string]interface{})["order"] = dids
  2581. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2582. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2583. }
  2584. } else {
  2585. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2586. }
  2587. }
  2588. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2589. fsion := gofasion.NewFasion(parammaps)
  2590. sqlnamestr := fsion.Get("name").ValueStr()
  2591. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2592. offset := fsion.Get("offset").ValueDefaultInt(0)
  2593. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2594. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2595. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2596. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2597. body := []byte("")
  2598. if sql != "" {
  2599. s_params := make([]interface{}, 0)
  2600. if fsion.HasKey("parammaps") {
  2601. parammaps := fsion.Get("parammaps")
  2602. paramslist := strings.Split(p, ",")
  2603. if len(paramslist) > 0 && p != "" {
  2604. for _, value := range paramslist {
  2605. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2606. }
  2607. }
  2608. }
  2609. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2610. if err != nil {
  2611. } else {
  2612. paramslist1 := strings.Split(p1, ",")
  2613. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2614. s_params1 := make([]interface{}, 0)
  2615. if len(paramslist1) > 0 && p1 != "" {
  2616. for _, v := range paramslist1 {
  2617. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2618. }
  2619. }
  2620. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2621. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2622. body, _ = json.Marshal(queryData)
  2623. }
  2624. }
  2625. }
  2626. bs := bytes.NewBuffer(body)
  2627. client := &http.Client{}
  2628. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2629. req, err := http.NewRequest(RequestMethod,
  2630. url,
  2631. bs,
  2632. )
  2633. if err != nil {
  2634. }
  2635. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2636. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2637. if err != nil {
  2638. // handle error
  2639. }
  2640. resp, err := client.Do(req)
  2641. if err != nil {
  2642. return ""
  2643. }
  2644. defer resp.Body.Close()
  2645. result_body, err := ioutil.ReadAll(resp.Body)
  2646. if err != nil {
  2647. return ""
  2648. }
  2649. fmt.Println(string(result_body))
  2650. return ""
  2651. }
  2652. func GetSummary(c *gin.Context) {
  2653. appG := app.Gin{C: c}
  2654. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2655. fsion := gofasion.NewFasion(string(dataByte))
  2656. offset := fsion.Get("offset").ValueDefaultInt(0)
  2657. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2658. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2659. parammaps := fsion.Get("parammaps")
  2660. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2661. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2662. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2663. tx := restful.Engine.NewSession()
  2664. defer tx.Close()
  2665. sqlnamestr := ""
  2666. if genre == "0" {
  2667. if status == "0" {
  2668. sqlnamestr = "getAccuracyJSY"
  2669. } else if status == "1" {
  2670. sqlnamestr = "getAccuracyHFT"
  2671. } else if status == "2" {
  2672. sqlnamestr = "getAccuracyHNS"
  2673. } else if status == "3" {
  2674. sqlnamestr = "getAccuracyHSC"
  2675. } else if status == "4" {
  2676. sqlnamestr = "getAccuracyHCC"
  2677. } else if status == "5" {
  2678. sqlnamestr = "getAccuracyMC"
  2679. } else if status == "6" {
  2680. sqlnamestr = "getAccuracyFeedHL"
  2681. }
  2682. } else {
  2683. if status == "0" {
  2684. sqlnamestr = "getAccuracySCCJSY"
  2685. } else if status == "1" {
  2686. sqlnamestr = "getAccuracySFT"
  2687. } else if status == "2" {
  2688. sqlnamestr = "getAccuracySNS"
  2689. } else if status == "3" {
  2690. sqlnamestr = "getAccuracySSC"
  2691. } else if status == "4" {
  2692. sqlnamestr = "getAccuracySCC"
  2693. } else if status == "5" {
  2694. sqlnamestr = "getAccuracySLCL"
  2695. }
  2696. }
  2697. if isDate == "1" {
  2698. sqlnamestr += "Date"
  2699. }
  2700. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2701. // fmt.Println(sqlnamestr, sql)
  2702. if sql != "" {
  2703. s_params := make([]interface{}, 0)
  2704. // if fsion.HasKey("parammaps") {
  2705. fmt.Println(s_params, "222", p)
  2706. paramslist := strings.Split(p, ",")
  2707. if len(paramslist) > 0 && p != "" {
  2708. for _, value := range paramslist {
  2709. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2710. if tempv, exists := c.Get("jwt_username"); exists {
  2711. s_params = append(s_params, tempv.(string))
  2712. } else {
  2713. s_params = append(s_params, "")
  2714. }
  2715. } else {
  2716. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2717. }
  2718. }
  2719. }
  2720. if returntype == "xlsx" {
  2721. var xlsxfile *xlsx.File
  2722. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2723. //c.File("c:/dd.xlsx")
  2724. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2725. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2726. c.Header("Content-Transfer-Encoding", "binary")
  2727. _ = xlsxfile.Write(c.Writer)
  2728. } else {
  2729. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2730. if err != nil {
  2731. logging.Error("GetDataByName err: ", err)
  2732. msg := geterrmsg(err.Error())
  2733. appG.Response(http.StatusOK, e.ERROR, msg)
  2734. } else {
  2735. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2736. }
  2737. }
  2738. } else {
  2739. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2740. }
  2741. }
  2742. // type lpplanStruct struct {
  2743. // Id int64 `xorm:"id"`
  2744. // Tmrname string `xorm:"tmrname"`
  2745. // Tmrid int64 `xorm:"tmrid"`
  2746. // Sort int64 `xorm:"sort"`
  2747. // Sel int64 `xorm:"sel"`
  2748. // Times int64 `xorm:"times"`
  2749. // Ftname string `xorm:"ftname"`
  2750. // Ftid int64 `xorm:"ftid"`
  2751. // Maxweight float64 `xorm:"maxweight"`
  2752. // Sumweight float64 `xorm:"sumweight"`
  2753. // Sumcowcount int64 `xorm:"sumcowcount"`
  2754. // Pastureid string `xorm:"pastureid"`
  2755. // Display string `xorm:"display"`
  2756. // Issplit int64 `xorm:"issplit"`
  2757. // BeginTime string `xorm:"begintime"`
  2758. // }
  2759. func UpdateFTdetail(c *gin.Context) {
  2760. appG := app.Gin{C: c}
  2761. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2762. tempval_ := make(map[string]interface{})
  2763. tempCommon := make(map[string]interface{})
  2764. tempval := make([]map[string]interface{}, 0)
  2765. fTChange := make(map[string]interface{}, 0)
  2766. fpdOldDataList := make([]map[string]interface{}, 0)
  2767. fpdDataList := make([]map[string]interface{}, 0)
  2768. fsion := gofasion.NewFasion(string(dataByte))
  2769. // parammaps := fsion.Get("parammaps")
  2770. createdate := fsion.Get("createdate").ValueStr()
  2771. err := json.Unmarshal(dataByte, &tempval_)
  2772. if err != nil {
  2773. appG.Response(http.StatusOK, e.ERROR, false)
  2774. return
  2775. }
  2776. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2777. tx := restful.Engine.NewSession()
  2778. if v, ok := tempval_["data"].([]interface{}); ok {
  2779. for _, Tvalue := range v {
  2780. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2781. if v1["name"] == "updateFPbyFTChange" {
  2782. fTChange = v1
  2783. continue
  2784. }
  2785. tempval = append(tempval, v1)
  2786. }
  2787. }
  2788. }
  2789. parammaps := fTChange["parammaps"].(map[string]interface{})
  2790. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2791. // if err != nil {
  2792. // logs.Error(err)
  2793. // appG.Response(http.StatusOK, e.ERROR, false)
  2794. // return
  2795. // }
  2796. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2797. // if err != nil {
  2798. // logs.Error(err)
  2799. // appG.Response(http.StatusOK, e.ERROR, false)
  2800. // return
  2801. // }
  2802. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2803. // if err != nil {
  2804. // logs.Error(err)
  2805. // appG.Response(http.StatusOK, e.ERROR, false)
  2806. // return
  2807. // }
  2808. err = tx.Begin()
  2809. if err != nil {
  2810. logging.Error("tx.Begin 事务启动失败__error:", err)
  2811. }
  2812. defer func() {
  2813. if err != nil {
  2814. if tx != nil {
  2815. tx.Rollback()
  2816. }
  2817. }
  2818. if tx != nil {
  2819. tx.Close()
  2820. }
  2821. }()
  2822. if err != nil {
  2823. } else {
  2824. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2825. tempCommon = v
  2826. }
  2827. 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 ,
  2828. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2829. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2830. UNION
  2831. 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 ,
  2832. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2833. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2834. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2835. if err == nil {
  2836. if tempv, exists := c.Get("jwt_username"); exists {
  2837. tempCommon["jwt_username"] = tempv.(string)
  2838. }
  2839. for _, paramvalue := range tempval {
  2840. if _, ok := paramvalue["resultname"]; !ok {
  2841. paramvalue["resultname"] = paramvalue["name"]
  2842. }
  2843. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2844. if err != nil {
  2845. logging.Error("ExecDataParam error:", err)
  2846. break
  2847. }
  2848. }
  2849. if err != nil {
  2850. msg := geterrmsg(err.Error())
  2851. appG.Response(http.StatusOK, e.ERROR, msg)
  2852. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2853. }
  2854. }
  2855. }
  2856. tx.Commit()
  2857. // go func() {
  2858. if fTChange != nil {
  2859. parammaps := fTChange["parammaps"].(map[string]interface{})
  2860. if parammaps["type"].(float64) == 1 {
  2861. _, err = tx.SQL(`UPDATE feedp fp
  2862. set
  2863. fp.ftweight= IFNULL(IF(
  2864. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2865. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2866. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2867. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2868. ),0),fp.feedweight = IFNULL(IF(
  2869. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2870. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2871. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2872. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2873. ),0) +ifnull(fp.supplyweight,0)
  2874. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2875. _, err = tx.SQL(`UPDATE fpdetail fpd
  2876. INNER JOIN feedp fp
  2877. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2878. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2879. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2880. } else {
  2881. _, err = tx.SQL(`UPDATE feedp fp
  2882. SET
  2883. fp.supplyweight= IFNULL(IF(
  2884. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2885. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2886. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2887. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2888. ),0),fp.feedweight = IFNULL(IF(
  2889. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2890. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2891. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2892. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2893. ),0) +ifnull(fp.supplyweight,0)
  2894. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2895. _, err = tx.SQL(`UPDATE fpdetail fpd
  2896. INNER JOIN feedp fp
  2897. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2898. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2899. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2900. }
  2901. 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(ptid) ptid,TRIM(ptsid ) ptsid ,
  2902. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2903. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2904. UNION
  2905. 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 ,
  2906. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2907. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2908. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2909. lpplanList := make([]*lpplanStruct, 0)
  2910. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2911. if err != nil {
  2912. logs.Error(err, 1)
  2913. return
  2914. }
  2915. lppidlist := []string{}
  2916. for _, lpp := range lpplanList {
  2917. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2918. }
  2919. if len(lppidlist) <= 0 {
  2920. appG.Response(http.StatusOK, e.SUCCESS, true)
  2921. return
  2922. }
  2923. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2924. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2925. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2926. if err != nil {
  2927. // tx.Rollback()
  2928. logs.Error(err, 2, parammaps["pastureid"])
  2929. return
  2930. }
  2931. var wg sync.WaitGroup
  2932. for _, old := range fpdOldDataList {
  2933. for _, fpd := range fpdDataList {
  2934. wg.Add(1)
  2935. go func(old, fpd map[string]interface{}) {
  2936. updateLppandList := make([]*lpplandtl1, 0)
  2937. defer wg.Done()
  2938. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2939. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2940. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2941. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2942. var w float64
  2943. var status int
  2944. if fpd["barname"].(string) == "D1" {
  2945. fmt.Println("1")
  2946. }
  2947. if weight < oldweight {
  2948. if weight >= 0 {
  2949. return
  2950. }
  2951. w = weight
  2952. status = 0
  2953. } else {
  2954. if oldweight > 0 {
  2955. return
  2956. }
  2957. w = weight
  2958. status = 1
  2959. }
  2960. // fweight = w
  2961. for _, lpp := range lpplanList {
  2962. var fweight float64
  2963. var lweight float64
  2964. lpplandtl1List := make([]*lpplandtl1, 0)
  2965. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2966. for _, lppland := range lpplandtl1AllList {
  2967. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2968. lpplandtl1List = append(lpplandtl1List, lppland)
  2969. }
  2970. }
  2971. if len(lpplandtl1List) == 0 {
  2972. continue
  2973. }
  2974. for _, lppland := range lpplandtl1List {
  2975. lweight += lppland.Lweight
  2976. }
  2977. if status == 0 {
  2978. if lweight <= 0 {
  2979. continue
  2980. }
  2981. } else {
  2982. if lpp.Maxweight <= lweight {
  2983. continue
  2984. }
  2985. }
  2986. for _, lppland := range lpplandtl1List {
  2987. if fpdid == lppland.Fpdid {
  2988. if status == 1 {
  2989. // if w <= lppland.Lweight {
  2990. if lpp.Maxweight <= lweight {
  2991. continue
  2992. }
  2993. if w+lweight <= lpp.Maxweight {
  2994. lppland.Lweight += w
  2995. lweight += w
  2996. fweight += w
  2997. w = 0
  2998. } else {
  2999. w = w - (lpp.Maxweight - lweight)
  3000. n := (lpp.Maxweight - lweight)
  3001. lppland.Lweight = lppland.Lweight + n
  3002. lweight += n
  3003. fweight += n
  3004. }
  3005. } else {
  3006. if lppland.Lweight == 0 {
  3007. continue
  3008. }
  3009. if w+lppland.Lweight >= 0 {
  3010. lppland.Lweight = lppland.Lweight + w
  3011. lweight = lweight + w
  3012. fweight = fweight + w
  3013. w = 0
  3014. } else {
  3015. w = w + lppland.Lweight
  3016. lweight = lweight - lppland.Lweight
  3017. fweight = fweight - lppland.Lweight
  3018. lppland.Lweight = 0
  3019. }
  3020. }
  3021. updateLppandList = append(updateLppandList, lppland)
  3022. break
  3023. }
  3024. }
  3025. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3026. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3027. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3028. if err != nil {
  3029. // tx.Rollback()
  3030. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3031. return
  3032. }
  3033. for _, lppland := range updateLppandList {
  3034. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3035. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3036. if err != nil {
  3037. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3038. // tx.Rollback()
  3039. logs.Error(err, 3)
  3040. return
  3041. }
  3042. // defer wg.Done()
  3043. }
  3044. updateLppandList = []*lpplandtl1{}
  3045. if w == 0 {
  3046. break
  3047. }
  3048. }
  3049. }
  3050. }(old, fpd)
  3051. }
  3052. }
  3053. wg.Wait()
  3054. }
  3055. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3056. if err != nil {
  3057. logs.Error(err)
  3058. appG.Response(http.StatusOK, e.ERROR, false)
  3059. return
  3060. }
  3061. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3062. if err != nil {
  3063. logs.Error(err)
  3064. appG.Response(http.StatusOK, e.ERROR, false)
  3065. return
  3066. }
  3067. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3068. if err != nil {
  3069. logs.Error(err)
  3070. appG.Response(http.StatusOK, e.ERROR, false)
  3071. return
  3072. }
  3073. now := createdate
  3074. // for _, oldFpd := range oldFpdDataList {
  3075. for _, newFpd := range newFpdDataList {
  3076. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3077. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3078. // go func() {
  3079. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  3080. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3081. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3082. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  3083. if err != nil {
  3084. logs.Error(err)
  3085. appG.Response(http.StatusOK, e.ERROR, false)
  3086. return
  3087. }
  3088. // }()
  3089. }
  3090. // break
  3091. // }
  3092. // }
  3093. // }
  3094. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3095. for _, newLpplandtl1 := range newLpplandtl1List {
  3096. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3097. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3098. // go func() {
  3099. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3100. background,cowcount,ccountradio,lweighthis,createdate)
  3101. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3102. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3103. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3104. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3105. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3106. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3107. if err != nil {
  3108. logs.Error(err)
  3109. appG.Response(http.StatusOK, e.ERROR, false)
  3110. return
  3111. }
  3112. // }()
  3113. // }
  3114. // break
  3115. // }
  3116. // }
  3117. }
  3118. // for _, oldFeedp := range oldFeedpList {
  3119. for _, newFeedp := range newFeedpList {
  3120. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3121. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3122. // go func() {
  3123. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3124. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  3125. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3126. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3127. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3128. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3129. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3130. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  3131. if err != nil {
  3132. logs.Error(err)
  3133. appG.Response(http.StatusOK, e.ERROR, false)
  3134. return
  3135. }
  3136. // }()
  3137. // }
  3138. // }
  3139. }
  3140. appG.Response(http.StatusOK, e.SUCCESS, true)
  3141. }
  3142. type lpplandtlInfo struct {
  3143. Id int64 `xorm:"id"`
  3144. Pastureid int64 `xorm:"pastureid"`
  3145. Lppid int64 `xorm:"lppid"`
  3146. Barid int64 `xorm:"barid"`
  3147. Barname string `xorm:"barname"`
  3148. Fpdid int64 `xorm:"fpdid"`
  3149. Fttype int64 `xorm:"fttype"`
  3150. Lweight float64 `xorm:"lweight"`
  3151. Sort int64 `xorm:"sort"`
  3152. Tmrid int64 `xorm:"tmrid"`
  3153. Tmrname string `xorm:"tmrname"`
  3154. Cowcount int64 `xorm:"cowcount"`
  3155. Ccountradio float64 `xorm:"ccountradio"`
  3156. Background string `xorm:"background"`
  3157. Lweighthis float64 `xorm:"lweighthis"`
  3158. Maxweight float64 `xorm:"maxweight"`
  3159. }
  3160. func UpdateFpdetailBar(c *gin.Context) {
  3161. appG := app.Gin{C: c}
  3162. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3163. fsion := gofasion.NewFasion(string(dataByte))
  3164. pastureid := fsion.Get("pastureid").ValueStr()
  3165. id := fsion.Get("id").ValueStr()
  3166. tx := restful.Engine.NewSession()
  3167. tx.Begin()
  3168. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse from fpdetail where pastureid = ? and barid = ? order by times `,
  3169. pastureid, id).Query().List()
  3170. if err != nil {
  3171. logs.Error(err)
  3172. }
  3173. for _, fpd := range fpdList {
  3174. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3175. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3176. pastureid, fpd["id"]).Query().List()
  3177. if err != nil {
  3178. tx.Rollback()
  3179. logs.Error(err)
  3180. appG.Response(http.StatusOK, e.ERROR, false)
  3181. return
  3182. }
  3183. var lweight float64
  3184. for _, lppland := range lpplandList {
  3185. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3186. lweight += lweight1
  3187. }
  3188. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3189. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3190. if fpdweight >= ptuse && lweight == ptuse {
  3191. continue
  3192. } else {
  3193. if lweight <= fpdweight {
  3194. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3195. if err != nil {
  3196. tx.Rollback()
  3197. logs.Error(err)
  3198. appG.Response(http.StatusOK, e.ERROR, false)
  3199. return
  3200. }
  3201. } else {
  3202. weight := fpdweight - lweight
  3203. for _, lppland := range lpplandList {
  3204. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3205. if weight >= lpplandlweight {
  3206. weight = weight - lpplandlweight
  3207. _, err := tx.SQL(` delete from lppland where id = ? `, lppland["id"]).Execute()
  3208. if err != nil {
  3209. tx.Rollback()
  3210. logs.Error(err)
  3211. appG.Response(http.StatusOK, e.ERROR, false)
  3212. return
  3213. }
  3214. } else {
  3215. _, err := tx.SQL(` update lppland set lweight = ? where id = ? `, lppland["lweight"].(float64)-weight, lppland["id"]).Execute()
  3216. if err != nil {
  3217. tx.Rollback()
  3218. logs.Error(err)
  3219. appG.Response(http.StatusOK, e.ERROR, false)
  3220. return
  3221. }
  3222. weight = 0
  3223. break
  3224. }
  3225. }
  3226. }
  3227. }
  3228. }
  3229. for _, list := range fsion.Get("data").Array() {
  3230. ftmap := make(map[string]interface{})
  3231. ftmap["old"] = list.Get("old").ValueFloat64()
  3232. ftmap["new"] = list.Get("new").ValueFloat64()
  3233. ftmap["times"] = list.Get("times").ValueInt64()
  3234. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3235. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3236. // fmt.Println(ftmap)
  3237. fpdDataList, err := tx.SQL(`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 ,
  3238. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3239. WHERE fpdetail.pastureid = ? and barid = ? and times = ?
  3240. UNION
  3241. 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 ,
  3242. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3243. WHERE fpdetail.pastureid = ? and barid = ? and times = ? ) t
  3244. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3245. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3246. if err != nil {
  3247. tx.Rollback()
  3248. logs.Error(err)
  3249. }
  3250. for _, fpd := range fpdDataList {
  3251. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3252. fttype := -1
  3253. if ftmap["ptid"].(string) != "-1" {
  3254. fttype = 1
  3255. }
  3256. var fweight float64
  3257. var lweight float64
  3258. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3259. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3260. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3261. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3262. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3263. if err != nil {
  3264. tx.Rollback()
  3265. logs.Error(err)
  3266. }
  3267. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3268. var w float64
  3269. var status int
  3270. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3271. if weight >= 0 {
  3272. continue
  3273. }
  3274. w = weight
  3275. status = 0
  3276. } else {
  3277. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  3278. continue
  3279. }
  3280. w = weight
  3281. status = 1
  3282. }
  3283. for _, lppland := range lpplandtl1List {
  3284. lweight += lppland.Lweight
  3285. }
  3286. for _, lppland := range lpplandtl1List {
  3287. if status == 1 {
  3288. // if w <= lppland.Lweight {
  3289. if lppland.Maxweight <= lweight {
  3290. continue
  3291. }
  3292. if w+lweight <= lppland.Maxweight {
  3293. lppland.Lweight += w
  3294. lweight += w
  3295. fweight += w
  3296. w = 0
  3297. } else {
  3298. w = w - (lppland.Maxweight - lweight)
  3299. n := (lppland.Maxweight - lweight)
  3300. lppland.Lweight = lppland.Lweight + n
  3301. lweight += n
  3302. fweight += n
  3303. }
  3304. } else {
  3305. if lppland.Lweight == 0 {
  3306. continue
  3307. }
  3308. if w+lppland.Lweight >= 0 {
  3309. lppland.Lweight = lppland.Lweight + w
  3310. lweight = lweight + w
  3311. fweight = fweight + w
  3312. w = 0
  3313. } else {
  3314. w = w + lppland.Lweight
  3315. lweight = lweight - lppland.Lweight
  3316. fweight = fweight - lppland.Lweight
  3317. lppland.Lweight = 0
  3318. }
  3319. }
  3320. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3321. if err != nil {
  3322. tx.Rollback()
  3323. logs.Error(err)
  3324. return
  3325. }
  3326. break
  3327. }
  3328. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3329. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3330. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3331. if err != nil {
  3332. tx.Rollback()
  3333. logs.Error(err)
  3334. }
  3335. if w == 0 {
  3336. break
  3337. }
  3338. }
  3339. }
  3340. }
  3341. tx.Commit()
  3342. now := time.Now()
  3343. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3344. if err != nil {
  3345. logs.Error(err)
  3346. appG.Response(http.StatusOK, e.ERROR, false)
  3347. return
  3348. }
  3349. // newFpdDataList, err := tx.SQL(` select * from fpdetail where barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3350. // if err != nil {
  3351. // logs.Error(err)
  3352. // appG.Response(http.StatusOK, e.ERROR, false)
  3353. // return
  3354. // }
  3355. // newFeedpList, err := tx.SQL(` select * from feedp where barid = ? and pastureid = ?`, id, pastureid).Query().List()
  3356. // if err != nil {
  3357. // logs.Error(err)
  3358. // appG.Response(http.StatusOK, e.ERROR, false)
  3359. // return
  3360. // }
  3361. for _, newLpplandtl1 := range newLpplandtl1List {
  3362. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3363. background,cowcount,ccountradio,lweighthis,createdate)
  3364. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3365. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3366. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3367. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3368. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3369. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3370. if err != nil {
  3371. logs.Error(err)
  3372. appG.Response(http.StatusOK, e.ERROR, false)
  3373. return
  3374. }
  3375. }
  3376. // for _, newFpd := range newFpdDataList {
  3377. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  3378. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3379. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3380. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  3381. // if err != nil {
  3382. // logs.Error(err)
  3383. // appG.Response(http.StatusOK, e.ERROR, false)
  3384. // return
  3385. // }
  3386. // }
  3387. // for _, newFeedp := range newFeedpList {
  3388. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3389. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  3390. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3391. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3392. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3393. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3394. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3395. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  3396. // if err != nil {
  3397. // logs.Error(err)
  3398. // appG.Response(http.StatusOK, e.ERROR, false)
  3399. // return
  3400. // }
  3401. // }
  3402. appG.Response(http.StatusOK, e.SUCCESS, true)
  3403. }
  3404. func GetProcessAnalysis(c *gin.Context) {
  3405. appG := app.Gin{C: c}
  3406. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3407. fsion := gofasion.NewFasion(string(dataByte))
  3408. sqlnamestr := fsion.Get("name").ValueStr()
  3409. offset := fsion.Get("offset").ValueDefaultInt(0)
  3410. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3411. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3412. parammaps := fsion.Get("parammaps")
  3413. tx := restful.Engine.NewSession()
  3414. err := tx.Begin()
  3415. defer func() {
  3416. switch {
  3417. case err != nil:
  3418. logging.Error("tx.Begin 事务启动失败__error:", err)
  3419. if tx != nil {
  3420. tx.Rollback()
  3421. }
  3422. default:
  3423. if tx != nil {
  3424. err = tx.Commit()
  3425. }
  3426. }
  3427. if tx != nil {
  3428. tx.Close()
  3429. }
  3430. }()
  3431. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3432. s_params := make([]interface{}, 0)
  3433. paramslist := strings.Split(p, ",")
  3434. if len(paramslist) > 0 && p != "" {
  3435. for _, value := range paramslist {
  3436. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3437. if tempv, exists := c.Get("jwt_username"); exists {
  3438. s_params = append(s_params, tempv.(string))
  3439. } else {
  3440. s_params = append(s_params, "")
  3441. }
  3442. } else {
  3443. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3444. }
  3445. }
  3446. }
  3447. tmrtnameStr := ""
  3448. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3449. if len(tmrtnameStr) == 0 {
  3450. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3451. } else {
  3452. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3453. }
  3454. }
  3455. if len(tmrtnameStr) > 0 {
  3456. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3457. }
  3458. sql += " ORDER BY d.intime"
  3459. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3460. if err != nil {
  3461. logging.Error("GetDataByName err: ", err)
  3462. msg := geterrmsg(err.Error())
  3463. appG.Response(http.StatusOK, e.ERROR, msg)
  3464. } else {
  3465. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3466. }
  3467. }
  3468. func UpdateFeedtempletStatus(c *gin.Context) {
  3469. appG := app.Gin{C: c}
  3470. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3471. fsion := gofasion.NewFasion(string(dataByte))
  3472. parammaps := fsion.Get("parammaps")
  3473. tx := restful.Engine.NewSession()
  3474. tx.Begin()
  3475. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3476. if err != nil {
  3477. tx.Rollback()
  3478. logs.Error(err)
  3479. appG.Response(http.StatusOK, e.ERROR, err)
  3480. return
  3481. }
  3482. tx.Commit()
  3483. appG.Response(http.StatusOK, e.SUCCESS, true)
  3484. }
  3485. func AddFtdry(c *gin.Context) {
  3486. appG := app.Gin{C: c}
  3487. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3488. fsion := gofasion.NewFasion(string(dataByte))
  3489. sqlnamestr := fsion.Get("name").ValueStr()
  3490. s_params := make([]interface{}, 0)
  3491. tx := restful.Engine.NewSession()
  3492. err := tx.Begin()
  3493. defer func() {
  3494. switch {
  3495. case err != nil:
  3496. if tx != nil {
  3497. tx.Rollback()
  3498. }
  3499. default:
  3500. if tx != nil {
  3501. err = tx.Commit()
  3502. }
  3503. }
  3504. if tx != nil {
  3505. tx.Close()
  3506. }
  3507. }()
  3508. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3509. if sql != "" {
  3510. parammaps := fsion.Get("parammaps")
  3511. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3512. paramslist := strings.Split(p, ",")
  3513. if len(paramslist) > 0 && p != "" {
  3514. for _, value := range paramslist {
  3515. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3516. if tempv, exists := c.Get("jwt_username"); exists {
  3517. s_params = append(s_params, tempv.(string))
  3518. } else {
  3519. s_params = append(s_params, "")
  3520. }
  3521. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3522. ids, err := setting.SnowIds.NextId()
  3523. if err != nil {
  3524. ids = time.Now().UnixNano()
  3525. logging.Info("create SnowIds err", err)
  3526. }
  3527. s_params = append(s_params, ids)
  3528. } else {
  3529. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3530. }
  3531. }
  3532. }
  3533. var actweight float64
  3534. actweightList, err := tx.SQL(`select ROUND(avg(actweight),2) as actweight from ftdry
  3535. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3536. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3537. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3538. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3539. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3540. 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()
  3541. if err != nil {
  3542. logging.Error("AddFtdry err: ", err)
  3543. msg := geterrmsg(err.Error())
  3544. appG.Response(http.StatusOK, e.ERROR, msg)
  3545. }
  3546. if len(actweightList) > 0 {
  3547. for _, item := range actweightList {
  3548. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3549. if err != nil {
  3550. logging.Error("AddFtdry err: ", err)
  3551. msg := geterrmsg(err.Error())
  3552. appG.Response(http.StatusOK, e.ERROR, msg)
  3553. }
  3554. actweight = fl
  3555. }
  3556. } else {
  3557. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3558. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3559. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3560. if err != nil {
  3561. logging.Error("AddFtdry err: ", err)
  3562. msg := geterrmsg(err.Error())
  3563. appG.Response(http.StatusOK, e.ERROR, msg)
  3564. }
  3565. for _, item := range dryList {
  3566. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3567. if err != nil {
  3568. logging.Error("AddFtdry err: ", err)
  3569. msg := geterrmsg(err.Error())
  3570. appG.Response(http.StatusOK, e.ERROR, msg)
  3571. }
  3572. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3573. }
  3574. }
  3575. if sqlnamestr == "insertFtdry" {
  3576. s_params = append(s_params, actweight)
  3577. } else if sqlnamestr == "updateFtdry" {
  3578. sql = fmt.Sprintf(sql, actweight)
  3579. }
  3580. queryData, err := execDataBySqlT(sql, s_params, tx)
  3581. if err != nil {
  3582. logging.Error("AddFtdry err: ", err)
  3583. msg := geterrmsg(err.Error())
  3584. appG.Response(http.StatusOK, e.ERROR, msg)
  3585. } else {
  3586. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3587. }
  3588. } else {
  3589. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3590. }
  3591. }
  3592. func CheckDates(c *gin.Context) {
  3593. tx := restful.Engine.NewSession()
  3594. defer tx.Close()
  3595. appG := app.Gin{C: c}
  3596. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3597. tempval_ := make(map[string]interface{})
  3598. tempCommon := make(map[string]interface{})
  3599. tempval := make([]map[string]interface{}, 0)
  3600. err := json.Unmarshal(dataByte, &tempval_)
  3601. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3602. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3603. if err != nil {
  3604. } else {
  3605. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3606. tempCommon = v
  3607. }
  3608. if v, ok := tempval_["data"].([]interface{}); ok {
  3609. for _, Tvalue := range v {
  3610. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3611. tempval = append(tempval, v1)
  3612. }
  3613. }
  3614. }
  3615. if err == nil {
  3616. if tempv, exists := c.Get("jwt_username"); exists {
  3617. tempCommon["jwt_username"] = tempv.(string)
  3618. }
  3619. for _, paramvalue := range tempval {
  3620. if _, ok := paramvalue["resultname"]; !ok {
  3621. paramvalue["resultname"] = paramvalue["name"]
  3622. }
  3623. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3624. if err != nil {
  3625. logging.Error("ExecDataParam error:", err)
  3626. }
  3627. }
  3628. if err == nil {
  3629. vmsg := ""
  3630. for _, item := range tempval {
  3631. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3632. for _, childrenList := range list.([]interface{}) {
  3633. for k, children := range childrenList.(map[string]interface{}) {
  3634. if k != "children" {
  3635. continue
  3636. }
  3637. for _, v := range children.([]map[string]interface{}) {
  3638. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3639. if k1 == "list" {
  3640. for _, v2 := range v1.([]map[string]interface{}) {
  3641. if v2["vmsg"].(string) != "1" {
  3642. if len(vmsg) == 0 {
  3643. vmsg = v2["vmsg"].(string)
  3644. } else {
  3645. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3646. }
  3647. }
  3648. }
  3649. }
  3650. }
  3651. }
  3652. }
  3653. }
  3654. }
  3655. }
  3656. if len(vmsg) > 0 {
  3657. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3658. } else {
  3659. appG.Response(http.StatusOK, e.SUCCESS, true)
  3660. }
  3661. } else {
  3662. msg := geterrmsg(err.Error())
  3663. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3664. }
  3665. }
  3666. }
  3667. if err != nil {
  3668. msg := geterrmsg(err.Error())
  3669. appG.Response(http.StatusOK, e.ERROR, msg)
  3670. }
  3671. }
  3672. 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) {
  3673. sqlname := fasion["name"].(string)
  3674. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3675. if v, ok := fasion["type"]; ok {
  3676. sqltype = v.(string)
  3677. }
  3678. sql := ""
  3679. p := ""
  3680. s_params := make([]interface{}, 0)
  3681. if sqltype != "" {
  3682. sql, p = restful.GetSqlByName(sqlname, tx)
  3683. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3684. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3685. paramslist := strings.Split(p, ",")
  3686. if len(paramslist) > 0 && p != "" {
  3687. for _, value := range paramslist {
  3688. ss := ""
  3689. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3690. ids, err := setting.SnowIds.NextId()
  3691. if err != nil {
  3692. ids = time.Now().UnixNano()
  3693. logging.Info("create SnowIds err", err)
  3694. }
  3695. s_params = append(s_params, ids)
  3696. } else {
  3697. if ss == "" && CommonParamMap != nil {
  3698. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3699. ss = valuestring
  3700. tempstrb := strings.IndexAny(valuestring, "@")
  3701. tempstre := strings.IndexAny(valuestring, ".")
  3702. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3703. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3704. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3705. }
  3706. } else {
  3707. ss = ""
  3708. }
  3709. }
  3710. }
  3711. if ss == "" && ParentParamMap != nil {
  3712. ss = getParamValue_(v, value, ParentParamMap)
  3713. }
  3714. if ss == "" && sameParamMap != nil {
  3715. ss = getParamValue(v, value, sameParamMap)
  3716. }
  3717. if ss == "" && ParamMap != nil {
  3718. ss = getParamValue(v, value, ParamMap)
  3719. }
  3720. s_params = append(s_params, ss)
  3721. }
  3722. }
  3723. }
  3724. }
  3725. }
  3726. if sql == "" {
  3727. sqltype = ""
  3728. }
  3729. if sql != "" {
  3730. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3731. if err != nil {
  3732. return nil, err
  3733. }
  3734. // fmt.Println(tempValParam)
  3735. return tempValParam.(map[string]interface{}), nil
  3736. } else {
  3737. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3738. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3739. if err != nil {
  3740. return nil, err
  3741. }
  3742. return nil, err
  3743. }
  3744. }
  3745. return nil, nil
  3746. }
  3747. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3748. var err error
  3749. subarray, ok := fasion["children"]
  3750. if ok {
  3751. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3752. tempVal_arrary := make([]map[string]interface{}, 0)
  3753. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3754. tempVal_ := make(map[string]interface{})
  3755. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3756. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3757. } else {
  3758. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3759. }
  3760. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3761. if err != nil {
  3762. return err
  3763. }
  3764. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3765. }
  3766. v.(map[string]interface{})["children"] = tempVal_arrary
  3767. }
  3768. }
  3769. return nil
  3770. }
  3771. func FpdImportExcel(c *gin.Context) {
  3772. appG := app.Gin{C: c}
  3773. inputdata := ""
  3774. c.Request.ParseForm()
  3775. params := c.Request.Form
  3776. file, _, err := c.Request.FormFile("file")
  3777. if err != nil {
  3778. appG.Response(http.StatusOK, e.ERROR, err)
  3779. return
  3780. }
  3781. sqlnamestrs := params.Get("name")
  3782. sheetname := params.Get("sheetname")
  3783. pastureid := params.Get("pastureid")
  3784. // importParams := params.Get("importParams")
  3785. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3786. // 必输项参数 (字符串格式 "field1,field2,field3")
  3787. requiredParams := params.Get("requiredParams")
  3788. // 日期参数
  3789. dateParams := params.Get("dateParams")
  3790. // 数字参数
  3791. numParams := params.Get("numParams")
  3792. //将字符串分割开
  3793. dateParamslist := strings.Split(dateParams, ",")
  3794. requiredParamslist := strings.Split(requiredParams, ",")
  3795. numParamslist := strings.Split(numParams, ",")
  3796. queryData := make([]interface{}, 0)
  3797. sqlslist := strings.Split(sqlnamestrs, ",")
  3798. xlsx1, err := excelize.OpenReader(file)
  3799. if err != nil {
  3800. fmt.Println(err)
  3801. return
  3802. }
  3803. ok := 0
  3804. error := 0
  3805. isdone := true
  3806. tx := restful.Engine.NewSession()
  3807. defer tx.Close()
  3808. 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
  3809. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3810. if err != nil {
  3811. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3812. return
  3813. }
  3814. for _, item := range oldFpdList {
  3815. fmt.Println(item)
  3816. }
  3817. rows, _ := xlsx1.GetRows(sheetname)
  3818. // 限制10000条,多余的截取掉
  3819. if len(rows) > 10000 {
  3820. rows = rows[:10000]
  3821. }
  3822. for i, row := range rows {
  3823. if i > 0 {
  3824. entry := make(map[string]interface{})
  3825. outentry := make(map[string]interface{})
  3826. for j, colCell := range rows[0] {
  3827. for k, colCell1 := range row {
  3828. if j == k {
  3829. outentry[colCell] = colCell1
  3830. entry[colCell] = colCell1
  3831. }
  3832. }
  3833. }
  3834. inputdata = ""
  3835. a := ""
  3836. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3837. //校验日期格式
  3838. for _, v := range dateParamslist {
  3839. if v == "" {
  3840. continue
  3841. }
  3842. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3843. dtime, err := TransfTime(d.(string))
  3844. if err != nil {
  3845. a = strings.Trim(v, " ")
  3846. break
  3847. }
  3848. outentry[strings.Trim(v, " ")] = dtime
  3849. }
  3850. }
  3851. if a != "" {
  3852. outentry["error_msg"] = a + " 格式错误"
  3853. error++
  3854. queryData = append(queryData, outentry)
  3855. continue
  3856. }
  3857. a = ""
  3858. //校验必填格式
  3859. for _, v := range requiredParamslist {
  3860. if v == "" {
  3861. continue
  3862. }
  3863. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3864. a = strings.Trim(v, " ")
  3865. break
  3866. }
  3867. }
  3868. if a != "" {
  3869. outentry["error_msg"] = a + " 未填或格式错误"
  3870. error++
  3871. queryData = append(queryData, outentry)
  3872. continue
  3873. }
  3874. a = ""
  3875. //校验数字格式
  3876. for _, v := range numParamslist {
  3877. if v == "" {
  3878. continue
  3879. }
  3880. d, ok := outentry[strings.Trim(v, " ")]
  3881. if !ok || d == "" {
  3882. outentry[strings.Trim(v, " ")] = 0
  3883. } else {
  3884. var fl float64
  3885. switch d.(type) {
  3886. case string:
  3887. fl, err = strconv.ParseFloat(d.(string), 64)
  3888. }
  3889. if err != nil || fl < 0 {
  3890. a = strings.Trim(v, " ")
  3891. break
  3892. }
  3893. }
  3894. }
  3895. if a != "" {
  3896. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3897. error++
  3898. queryData = append(queryData, outentry)
  3899. continue
  3900. }
  3901. errExist := false
  3902. for _, sqlnamestr := range sqlslist {
  3903. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3904. paramslist := strings.Split(paramslists, ",")
  3905. if len(paramslist) > 0 {
  3906. s_params := make([]interface{}, 0)
  3907. for _, value := range paramslist {
  3908. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3909. if tempv, exists := c.Get("jwt_username"); exists {
  3910. s_params = append(s_params, tempv.(string))
  3911. } else {
  3912. s_params = append(s_params, "")
  3913. }
  3914. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3915. s_params = append(s_params, pastureid)
  3916. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3917. ids, err := setting.SnowIds.NextId()
  3918. if err != nil {
  3919. ids = time.Now().UnixNano()
  3920. logging.Info("create SnowIds err", err)
  3921. }
  3922. s_params = append(s_params, ids)
  3923. } else {
  3924. if outentry[strings.Trim(value, " ")] == nil {
  3925. s_params = append(s_params, "")
  3926. } else {
  3927. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3928. }
  3929. }
  3930. }
  3931. outentry["input"] = inputdata
  3932. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3933. if err != nil {
  3934. errExist = true
  3935. // if tx != nil {
  3936. // tx.Rollback()
  3937. // }
  3938. // if tx != nil {
  3939. // tx.Close()
  3940. // }
  3941. msg := geterrmsg(err.Error())
  3942. outentry["error_msg"] = msg
  3943. error++
  3944. queryData = append(queryData, outentry)
  3945. isdone = true
  3946. break
  3947. } else {
  3948. if len(returnmsgmap1) > 0 {
  3949. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3950. // if tx != nil {
  3951. // tx.Rollback()
  3952. // }
  3953. // if tx != nil {
  3954. // tx.Close()
  3955. // }
  3956. msg := geterrmsg(va.(string))
  3957. outentry["error_msg"] = msg
  3958. error++
  3959. queryData = append(queryData, outentry)
  3960. isdone = true
  3961. break
  3962. }
  3963. }
  3964. isdone = false
  3965. }
  3966. }
  3967. }
  3968. if !errExist {
  3969. dataexcel := make(map[string]interface{}, 0)
  3970. if _, ok := outentry["栏舍名称"]; ok {
  3971. dataexcel["barname"] = outentry["栏舍名称"]
  3972. }
  3973. if _, ok := outentry["实际牛头数"]; ok {
  3974. dataexcel["ccount"] = outentry["实际牛头数"]
  3975. }
  3976. if _, ok := outentry["系数(%)"]; ok {
  3977. dataexcel["ratio"] = outentry["系数(%)"]
  3978. }
  3979. if _, ok := outentry["配方模板"]; ok {
  3980. dataexcel["ftname"] = outentry["配方模板"]
  3981. }
  3982. if _, ok := outentry["补料配方"]; ok {
  3983. dataexcel["ptsfname"] = outentry["补料配方"]
  3984. }
  3985. if _, ok := outentry["第一班比例(%)"]; ok {
  3986. dataexcel["1"] = outentry["第一班比例(%)"]
  3987. }
  3988. if _, ok := outentry["第二班比例(%)"]; ok {
  3989. dataexcel["2"] = outentry["第二班比例(%)"]
  3990. }
  3991. if _, ok := outentry["第三班比例(%)"]; ok {
  3992. dataexcel["3"] = outentry["第三班比例(%)"]
  3993. }
  3994. if _, ok := outentry["第四班比例(%)"]; ok {
  3995. dataexcel["4"] = outentry["第四班比例(%)"]
  3996. }
  3997. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3998. if err != nil {
  3999. logs.Error(err)
  4000. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4001. return
  4002. }
  4003. if !existbar {
  4004. continue
  4005. }
  4006. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4007. if err != nil {
  4008. logs.Error(err)
  4009. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4010. return
  4011. }
  4012. if !ftexist {
  4013. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4014. if err != nil {
  4015. logs.Error(err)
  4016. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4017. return
  4018. }
  4019. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4020. if err != nil {
  4021. logs.Error(err)
  4022. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4023. return
  4024. }
  4025. }
  4026. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4027. if err != nil {
  4028. logs.Error(err)
  4029. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4030. return
  4031. }
  4032. if !exist {
  4033. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4034. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4035. if err != nil {
  4036. logs.Error(err)
  4037. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4038. return
  4039. }
  4040. }
  4041. var feedpargs []interface{}
  4042. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4043. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4044. if _, ok := dataexcel["ftname"]; ok {
  4045. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4046. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4047. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4048. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4049. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4050. } else {
  4051. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4052. }
  4053. if _, ok := dataexcel["ptsfname"]; ok {
  4054. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4055. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4056. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4057. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4058. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4059. } else {
  4060. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4061. }
  4062. upFeedpSql += " where barname = ? and pastureid = ? "
  4063. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4064. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4065. if err != nil {
  4066. logs.Error(err)
  4067. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4068. return
  4069. }
  4070. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4071. if err != nil {
  4072. logs.Error(err)
  4073. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4074. return
  4075. }
  4076. if !exist1 {
  4077. _, 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) `,
  4078. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4079. if err != nil {
  4080. logs.Error(err)
  4081. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4082. return
  4083. }
  4084. _, 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) `,
  4085. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4086. if err != nil {
  4087. logs.Error(err)
  4088. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4089. return
  4090. }
  4091. _, 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) `,
  4092. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4093. if err != nil {
  4094. logs.Error(err)
  4095. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4096. return
  4097. }
  4098. _, 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) `,
  4099. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4100. if err != nil {
  4101. logs.Error(err)
  4102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4103. return
  4104. }
  4105. }
  4106. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4107. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4108. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4109. and pastureid = ? and times = ?`
  4110. var fpdargs1 []interface{}
  4111. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4112. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4113. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4114. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4115. if err != nil {
  4116. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4117. return
  4118. }
  4119. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4120. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4121. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4122. // and pastureid = ? and times = ?`
  4123. var fpdargs2 []interface{}
  4124. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4125. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4126. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4127. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4128. if err != nil {
  4129. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4130. return
  4131. }
  4132. var fpdargs3 []interface{}
  4133. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4134. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4135. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4136. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4137. if err != nil {
  4138. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4139. return
  4140. }
  4141. var fpdargs4 []interface{}
  4142. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4143. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4144. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4145. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4146. if err != nil {
  4147. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4148. return
  4149. }
  4150. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4151. 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()
  4152. if err != nil {
  4153. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4154. return
  4155. }
  4156. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4157. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4158. upFpdetailList := make([]*upFpdetail, 0)
  4159. for _, newfpd := range newList {
  4160. for _, oldfpd := range oldFpdList {
  4161. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4162. var oldweight, newweight float64
  4163. if oldfpd["weight"] != nil {
  4164. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4165. }
  4166. if newfpd["weight"] != nil {
  4167. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4168. }
  4169. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4170. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4171. Old: oldweight,
  4172. New: newweight,
  4173. Times: newfpd["times"].(int64),
  4174. Ptid: newfpd["ptid"].(int64),
  4175. Fweight: fweight,
  4176. Id: oldfpd["id"].(int64),
  4177. })
  4178. break
  4179. }
  4180. }
  4181. }
  4182. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4183. }
  4184. }
  4185. if !isdone {
  4186. ok++
  4187. isdone = true
  4188. }
  4189. }
  4190. data := make(map[string]interface{})
  4191. data["result"] = queryData
  4192. data["success"] = ok
  4193. data["err_count"] = error
  4194. appG.Response(http.StatusOK, e.SUCCESS, data)
  4195. }
  4196. type upFpdetail struct {
  4197. Old float64
  4198. New float64
  4199. Times int64
  4200. Ptid int64
  4201. Fweight float64
  4202. Id int64
  4203. // Ptsid string
  4204. }
  4205. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4206. tx := restful.Engine.NewSession()
  4207. defer tx.Close()
  4208. tx.Begin()
  4209. for _, data := range dataList {
  4210. fttype := -1
  4211. if data.Ptid != -1 {
  4212. fttype = 1
  4213. }
  4214. var fweight float64
  4215. var lweight float64
  4216. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4217. err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4218. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4219. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4220. data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4221. if err != nil {
  4222. tx.Rollback()
  4223. logs.Error(err)
  4224. return err
  4225. }
  4226. weight := data.Fweight
  4227. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4228. var w float64
  4229. var status int
  4230. if data.New < data.Old {
  4231. if weight >= 0 {
  4232. continue
  4233. }
  4234. w = weight
  4235. status = 0
  4236. } else {
  4237. // if weight-(data.New-data.Old) > 0 {
  4238. // continue
  4239. // }
  4240. w = data.New - data.Old
  4241. status = 1
  4242. }
  4243. for _, lppland := range lpplandtl1List {
  4244. var lppdata lpplandtlInfo
  4245. tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4246. lppland.Lppid, pastureid).GetFirst(&lppdata)
  4247. if err != nil {
  4248. tx.Rollback()
  4249. logs.Error(err)
  4250. return err
  4251. }
  4252. lweight = lppdata.Lweight
  4253. if status == 1 {
  4254. // if w <= lppland.Lweight {
  4255. if lppland.Maxweight <= lweight {
  4256. continue
  4257. }
  4258. if w+lweight <= lppland.Maxweight {
  4259. lppland.Lweight += w
  4260. lweight += w
  4261. fweight += w
  4262. w = 0
  4263. } else {
  4264. w = w - (lppland.Maxweight - lweight)
  4265. n := (lppland.Maxweight - lweight)
  4266. lppland.Lweight = lppland.Lweight + n
  4267. lweight += n
  4268. fweight += n
  4269. }
  4270. } else {
  4271. if lppland.Lweight == 0 {
  4272. continue
  4273. }
  4274. if w+lppland.Lweight >= 0 {
  4275. lppland.Lweight = lppland.Lweight + w
  4276. lweight = lweight + w
  4277. fweight = fweight + w
  4278. w = 0
  4279. } else {
  4280. w = w + lppland.Lweight
  4281. lweight = lweight - lppland.Lweight
  4282. fweight = fweight - lppland.Lweight
  4283. lppland.Lweight = 0
  4284. }
  4285. }
  4286. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4287. if err != nil {
  4288. tx.Rollback()
  4289. logs.Error(err)
  4290. return err
  4291. }
  4292. break
  4293. }
  4294. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4295. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4296. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4297. if err != nil {
  4298. tx.Rollback()
  4299. logs.Error(err)
  4300. return err
  4301. }
  4302. // if w == 0 {
  4303. // break
  4304. // }
  4305. // }
  4306. }
  4307. err := tx.Commit()
  4308. if err != nil {
  4309. logs.Error(err)
  4310. tx.Rollback()
  4311. return err
  4312. }
  4313. now := time.Now()
  4314. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4315. if err != nil {
  4316. logs.Error(err)
  4317. return nil
  4318. }
  4319. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4320. if err != nil {
  4321. logs.Error(err)
  4322. return nil
  4323. }
  4324. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4325. if err != nil {
  4326. logs.Error(err)
  4327. return nil
  4328. }
  4329. for _, newLpplandtl1 := range newLpplandtl1List {
  4330. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4331. background,cowcount,ccountradio,lweighthis,createdate)
  4332. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4333. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4334. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4335. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4336. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4337. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4338. if err != nil {
  4339. logs.Error(err)
  4340. // appG.Response(http.StatusOK, e.ERROR, false)
  4341. return nil
  4342. }
  4343. }
  4344. for _, newFpd := range newFpdDataList {
  4345. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4346. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4347. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4348. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4349. if err != nil {
  4350. logs.Error(err)
  4351. // appG.Response(http.StatusOK, e.ERROR, false)
  4352. return nil
  4353. }
  4354. }
  4355. for _, newFeedp := range newFeedpList {
  4356. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4357. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4358. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4359. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4360. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4361. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4362. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4363. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4364. if err != nil {
  4365. logs.Error(err)
  4366. // appG.Response(http.StatusOK, e.ERROR, false)
  4367. return nil
  4368. }
  4369. }
  4370. return nil
  4371. }
  4372. func DeleteFTdetail(c *gin.Context) {
  4373. appG := app.Gin{C: c}
  4374. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4375. fsion := gofasion.NewFasion(string(dataByte))
  4376. parammaps := fsion.Get("parammaps")
  4377. pastureid := parammaps.Get("pastureid").ValueStr()
  4378. ftid := parammaps.Get("ftid").ValueStr()
  4379. tx := restful.Engine.NewSession()
  4380. defer tx.Close()
  4381. tx.Begin()
  4382. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4383. if err != nil {
  4384. tx.Rollback()
  4385. logs.Error(err)
  4386. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4387. return
  4388. }
  4389. if parammaps.Get("type").ValueStr() == "1" {
  4390. _, err := tx.SQL(`UPDATE feedp fp
  4391. set
  4392. fp.ftweight= IFNULL(IF(
  4393. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4394. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4395. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4396. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4397. ),0),fp.feedweight = IFNULL(IF(
  4398. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4399. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4400. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4401. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4402. ),0) +ifnull(fp.supplyweight,0)
  4403. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4404. if err != nil {
  4405. tx.Rollback()
  4406. logs.Error(err)
  4407. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4408. return
  4409. }
  4410. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4411. _, err = tx.SQL(`
  4412. UPDATE fpdetail fpd
  4413. INNER JOIN feedp fp
  4414. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4415. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4416. ptuse= 0
  4417. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4418. if err != nil {
  4419. tx.Rollback()
  4420. logs.Error(err)
  4421. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4422. return
  4423. }
  4424. } else {
  4425. _, err := tx.SQL(`UPDATE feedp fp
  4426. SET
  4427. fp.supplyweight= IFNULL(IF(
  4428. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4429. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4430. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4431. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4432. ),0),fp.feedweight = IFNULL(IF(
  4433. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4434. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4435. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4436. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4437. ),0) + ifnull(fp.supplyweight,0)
  4438. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4439. if err != nil {
  4440. tx.Rollback()
  4441. logs.Error(err)
  4442. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4443. return
  4444. }
  4445. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4446. _, err = tx.SQL(`
  4447. UPDATE fpdetail fpd
  4448. INNER JOIN feedp fp
  4449. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4450. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4451. ptsrate = 0
  4452. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4453. if err != nil {
  4454. tx.Rollback()
  4455. logs.Error(err)
  4456. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4457. return
  4458. }
  4459. }
  4460. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4461. if err != nil {
  4462. tx.Rollback()
  4463. logs.Error(err)
  4464. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4465. return
  4466. }
  4467. err = tx.Commit()
  4468. if err != nil {
  4469. tx.Rollback()
  4470. logs.Error(err)
  4471. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4472. return
  4473. }
  4474. appG.Response(http.StatusOK, e.SUCCESS, true)
  4475. }
  4476. func DeleteSpillageAll(c *gin.Context) {
  4477. appG := app.Gin{C: c}
  4478. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4479. fsion := gofasion.NewFasion(string(dataByte))
  4480. parammaps := fsion.Get("parammaps")
  4481. pastureid := parammaps.Get("pastureid").ValueStr()
  4482. times := parammaps.Get("times").ValueStr()
  4483. barid := parammaps.Get("barid").ValueStr()
  4484. tx := restful.Engine.NewSession()
  4485. defer tx.Close()
  4486. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4487. if err != nil {
  4488. logs.Error(err)
  4489. appG.Response(http.StatusOK, e.ERROR, false)
  4490. return
  4491. }
  4492. now := time.Now()
  4493. for _, item := range lpplandtl1List {
  4494. go func(item map[string]interface{}) {
  4495. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4496. background,cowcount,ccountradio,lweighthis,createdate)
  4497. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4498. item["pastureid"], item["lppid"], item["barid"],
  4499. item["barname"], item["fpdid"], item["fttype"],
  4500. item["lweight"], item["sort"], item["tmrid"],
  4501. item["tmrname"], item["background"], item["cowcount"],
  4502. item["ccountradio"], item["lweighthis"], now).Execute()
  4503. if err != nil {
  4504. logs.Error(err)
  4505. appG.Response(http.StatusOK, e.ERROR, false)
  4506. return
  4507. }
  4508. }(item)
  4509. }
  4510. tx.Begin()
  4511. _, 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()
  4512. if err != nil {
  4513. tx.Rollback()
  4514. logs.Error(err)
  4515. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4516. return
  4517. }
  4518. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4519. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4520. if err != nil {
  4521. tx.Rollback()
  4522. logs.Error(err)
  4523. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4524. return
  4525. }
  4526. err = tx.Commit()
  4527. if err != nil {
  4528. tx.Rollback()
  4529. logs.Error(err)
  4530. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4531. return
  4532. }
  4533. appG.Response(http.StatusOK, e.SUCCESS, true)
  4534. }
  4535. func GetTMRListEnableTypeAll(c *gin.Context) {
  4536. appG := app.Gin{C: c}
  4537. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4538. fsion := gofasion.NewFasion(string(dataByte))
  4539. parammaps := fsion.Get("parammaps")
  4540. pastureid := parammaps.Get("pastureid").ValueStr()
  4541. tx := restful.Engine.NewSession()
  4542. defer tx.Close()
  4543. dataList, err := tx.SQL(`SELECT
  4544. eqcode,
  4545. tname,
  4546. datacaptureno,
  4547. trim(tclassid) tclassid,
  4548. concat(tname,' / ',eqcode) tmrmix,
  4549. d.label tclassname,
  4550. maxstirfeed,
  4551. remark,
  4552. tmr.enable,
  4553. TRIM(tmr.id) id,
  4554. TRIM(tmr.pastureid)pastureid
  4555. FROM
  4556. tmr
  4557. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4558. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4559. ORDER BY id DESC`, pastureid).Query().List()
  4560. if err != nil {
  4561. logs.Error(err)
  4562. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4563. return
  4564. }
  4565. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4566. if err != nil {
  4567. logs.Error(err)
  4568. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4569. return
  4570. }
  4571. var carNum int64
  4572. for _, sysopt := range sysoptData {
  4573. if sysopt["inforvalue"] == nil {
  4574. carNum = 1
  4575. } else {
  4576. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4577. }
  4578. }
  4579. id := 200
  4580. n := 0
  4581. for i := carNum; i > 0; i-- {
  4582. id++
  4583. n++
  4584. data := make(map[string]interface{}, 0)
  4585. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4586. data["tname"] = fmt.Sprintf("任意车%d", n)
  4587. data["datacaptureno"] = -2
  4588. data["tclassid"] = -2
  4589. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4590. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4591. data["maxstirfeed"] = 100000
  4592. data["remark"] = fmt.Sprintf("任意车%d", n)
  4593. data["enable"] = 1
  4594. data["id"] = fmt.Sprintf("%d", id)
  4595. data["pastureid"] = pastureid
  4596. dataList = append(dataList, data)
  4597. }
  4598. // UNION ALL
  4599. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4600. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4601. }
  4602. func GetFeedpHistory(c *gin.Context) {
  4603. appG := app.Gin{C: c}
  4604. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4605. fsion := gofasion.NewFasion(string(dataByte))
  4606. // parammaps := fsion.Get("parammaps")
  4607. bar := fsion.Get("barname").ValueStr()
  4608. startDate := fsion.Get("startDate").ValueStr()
  4609. endDate := fsion.Get("endDate").ValueStr()
  4610. tx := restful.Engine.NewSession()
  4611. defer tx.Close()
  4612. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4613. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4614. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4615. if err != nil {
  4616. logs.Error(err)
  4617. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4618. return
  4619. }
  4620. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from fpdetailhistory where barname = ?
  4621. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4622. if err != nil {
  4623. logs.Error(err)
  4624. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4625. return
  4626. }
  4627. for _, feedp := range feedpList {
  4628. // LastftList, err := tx.SQL(` select tname ,id
  4629. // from feedtemplethistory where id = ?
  4630. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4631. // if err != nil {
  4632. // logs.Error(err)
  4633. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4634. // return
  4635. // }
  4636. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4637. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4638. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4639. if err != nil {
  4640. logs.Error(err)
  4641. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4642. return
  4643. }
  4644. var ftname interface{}
  4645. ftnamestatus := 0
  4646. ftname = feedp["ftname"]
  4647. var lastftid int64
  4648. if len(nextfeedpList) > 0 {
  4649. for _, ft := range nextfeedpList {
  4650. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4651. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4652. lastftid = ft["ftid"].(int64)
  4653. ftnamestatus = 1
  4654. break
  4655. }
  4656. }
  4657. }
  4658. for i, fpd := range fpdList {
  4659. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4660. fpd["weightstatus"] = 0
  4661. fpd["tratiostatus"] = 0
  4662. fpd["ftnamestatus"] = ftnamestatus
  4663. for k, fpd2 := range fpdList {
  4664. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4665. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4666. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4667. fpd["weightstatus"] = 1
  4668. }
  4669. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4670. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4671. fpd["tratiostatus"] = 1
  4672. }
  4673. break
  4674. }
  4675. }
  4676. fpd["barid"] = feedp["barid"]
  4677. fpd["barname"] = feedp["barname"]
  4678. fpd["ccount"] = feedp["ccount"]
  4679. fpd["ratio"] = feedp["ratio"]
  4680. fpd["ccountratio"] = feedp["ccountratio"]
  4681. fpd["ftid"] = feedp["ftid"]
  4682. fpd["ftname"] = ftname
  4683. fpd["ccountstatus"] = 0
  4684. fpd["ccountratiostatus"] = 0
  4685. fpd["ratiostatus"] = 0
  4686. fpd["ftnamestatus"] = 0
  4687. fpd["lastftid"] = lastftid
  4688. for _, next := range nextfeedpList {
  4689. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4690. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4691. fpd["ccountstatus"] = 1
  4692. }
  4693. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4694. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4695. fpd["ccountratiostatus"] = 1
  4696. }
  4697. if next["ratio"].(string) != fpd["ratio"].(string) {
  4698. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4699. fpd["ratiostatus"] = 1
  4700. }
  4701. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4702. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4703. // fpd["ftnamestatus"] = 1
  4704. // }
  4705. }
  4706. }
  4707. }
  4708. }
  4709. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4710. }
  4711. // func GetLpplandtl1History(c *gin.Context) {
  4712. // appG := app.Gin{C: c}
  4713. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4714. // fsion := gofasion.NewFasion(string(dataByte))
  4715. // // parammaps := fsion.Get("parammaps")
  4716. // barid := fsion.Get("barid").ValueStr()
  4717. // startDate := fsion.Get("startDate").ValueStr()
  4718. // endDate := fsion.Get("endDate").ValueStr()
  4719. // tx := restful.Engine.NewSession()
  4720. // defer tx.Close()
  4721. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4722. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4723. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4724. // // if err != nil {
  4725. // // logs.Error(err)
  4726. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4727. // // return
  4728. // // }
  4729. // // for _, feedp := range feedpList {
  4730. // // fmt.Println(feedp)
  4731. // // for i, fpd := range fpdList {
  4732. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4733. // // for k, fpd2 := range fpdList {
  4734. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4735. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4736. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4737. // // }
  4738. // // break
  4739. // // }
  4740. // // }
  4741. // // fpd["barid"] = feedp["barid"]
  4742. // // fpd["barname"] = feedp["barname"]
  4743. // // fpd["ccount"] = feedp["ccount"]
  4744. // // fpd["ratio"] = feedp["ratio"]
  4745. // // fpd["ccountratio"] = feedp["ccountratio"]
  4746. // // fpd["ftid"] = feedp["ftid"]
  4747. // // fpd["ftname"] = feedp["ftname"]
  4748. // // }
  4749. // // }
  4750. // // }
  4751. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4752. // }
  4753. func GetRemind(c *gin.Context) {
  4754. appG := app.Gin{C: c}
  4755. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4756. fsion := gofasion.NewFasion(string(dataByte))
  4757. parammaps := fsion.Get("parammaps")
  4758. pastureid := parammaps.Get("pastureid").ValueStr()
  4759. tx := restful.Engine.NewSession()
  4760. defer tx.Close()
  4761. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4762. if err != nil {
  4763. logs.Error(err)
  4764. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4765. return
  4766. }
  4767. // pastureid = "3"
  4768. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  4769. if err != nil {
  4770. logs.Error(err)
  4771. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4772. return
  4773. }
  4774. defer resp.Body.Close()
  4775. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4776. buf.ReadFrom(resp.Body)
  4777. fmt.Println(string(buf.Bytes()))
  4778. respMap := make(map[string]interface{}, 0)
  4779. err = json.Unmarshal(buf.Bytes(), &respMap)
  4780. if err != nil {
  4781. logs.Error(err)
  4782. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4783. return
  4784. }
  4785. for _, data := range dataList {
  4786. r := make(map[string]interface{}, 0)
  4787. r["sys_name"] = ""
  4788. r["service_id"] = ""
  4789. r["pasture_id"] = ""
  4790. r["type_name"] = ""
  4791. r["remind_type_id"] = ""
  4792. r["remind_type"] = ""
  4793. r["push_date"] = ""
  4794. r["push_time"] = ""
  4795. r["interval_time"] = ""
  4796. r["push_limit"] = ""
  4797. r["template_id"] = ""
  4798. r["roles_id"] = ""
  4799. r["users_id"] = ""
  4800. r["date_type"] = ""
  4801. r["cycle_type"] = ""
  4802. data["data"] = r
  4803. for _, resp := range respMap["data"].([]interface{}) {
  4804. resp1 := resp.(map[string]interface{})
  4805. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  4806. if resp1["push_time"] == nil {
  4807. resp1["push_time"] = ""
  4808. }
  4809. data["data"] = resp1
  4810. break
  4811. }
  4812. }
  4813. }
  4814. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4815. }
  4816. type NoticeMsgtype struct {
  4817. SysName string `json:"sys_name"`
  4818. PastureId int64 `json:"pasture_id"`
  4819. ServiceId int64 `json:"service_id"`
  4820. TypeName string `json:"type_name"`
  4821. RemindType int64 `json:"remind_type"`
  4822. PushDate int64 `json:"push_date"`
  4823. PushTime string `json:"push_time"`
  4824. IntervalTime int64 `json:"interval_time"`
  4825. PushLimit int64 `json:"push_limit"`
  4826. TemplateId string `json:"template_id"`
  4827. UsersId string `json:"users_id"`
  4828. DateType int64 `json:"date_type"`
  4829. CycleType int64 `json:"cycle_type"`
  4830. DelayTime int64 `json:"delay_time"`
  4831. Status int64 `json:"status"`
  4832. }
  4833. func UpdateRemind(c *gin.Context) {
  4834. appG := app.Gin{C: c}
  4835. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4836. parammaps := gofasion.NewFasion(string(dataByte))
  4837. // parammaps := fsion.Get("parammaps")
  4838. // user := parammaps.Get("user").ValueStr()
  4839. id := parammaps.Get("id").ValueInt64()
  4840. noticeMsgtype := new(NoticeMsgtype)
  4841. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  4842. noticeMsgtype.ServiceId = id
  4843. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  4844. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  4845. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  4846. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  4847. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  4848. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  4849. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  4850. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  4851. noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  4852. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  4853. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  4854. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  4855. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  4856. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  4857. //TODO
  4858. noticeMsgtype.SysName = "tmrWatch"
  4859. userList := parammaps.Get("user").Array()
  4860. var userstr []string
  4861. for _, user := range userList {
  4862. userstr = append(userstr, user.ValueStr())
  4863. }
  4864. tx := restful.Engine.NewSession()
  4865. defer tx.Close()
  4866. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  4867. if err != nil {
  4868. logs.Error(err)
  4869. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4870. return
  4871. }
  4872. // var jsonStr = []byte(noticeMsgtype
  4873. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  4874. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  4875. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  4876. req.Header.Set("Content-Type", "application/json")
  4877. client := &http.Client{}
  4878. resp, err := client.Do(req)
  4879. if err != nil {
  4880. logs.Error(err)
  4881. }
  4882. defer resp.Body.Close()
  4883. body, _ := ioutil.ReadAll(resp.Body)
  4884. fmt.Println("response Body:", string(body))
  4885. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  4886. if err != nil {
  4887. logs.Error(err)
  4888. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4889. return
  4890. }
  4891. defer getresp.Body.Close()
  4892. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4893. buf.ReadFrom(getresp.Body)
  4894. // fmt.Println(string(buf.Bytes()))
  4895. respMap := make(map[string]interface{}, 0)
  4896. err = json.Unmarshal(buf.Bytes(), &respMap)
  4897. if err != nil {
  4898. logs.Error(err)
  4899. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4900. return
  4901. }
  4902. for _, resp := range respMap["data"].([]interface{}) {
  4903. resp1 := resp.(map[string]interface{})
  4904. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  4905. if err != nil {
  4906. logs.Error(err)
  4907. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4908. return
  4909. }
  4910. }
  4911. appG.Response(http.StatusOK, e.SUCCESS, true)
  4912. }
  4913. func GetSpillageallHistory(c *gin.Context) {
  4914. appG := app.Gin{C: c}
  4915. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4916. parammaps := gofasion.NewFasion(string(dataByte))
  4917. barname := parammaps.Get("barname").ValueStr()
  4918. pastureid := parammaps.Get("pastureid").ValueStr()
  4919. startdate := parammaps.Get("startDate").ValueStr()
  4920. enddate := parammaps.Get("endDate").ValueStr()
  4921. tx := restful.Engine.NewSession()
  4922. defer tx.Close()
  4923. 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
  4924. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  4925. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  4926. if err != nil {
  4927. logs.Error(err)
  4928. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4929. return
  4930. }
  4931. respMap := make([]map[string]interface{}, 0)
  4932. data := make(map[interface{}]interface{})
  4933. for _, history := range historyList {
  4934. data[history["createdate"]] = history["createdate"]
  4935. }
  4936. createList := []string{}
  4937. for _, v := range data {
  4938. createList = append(createList, v.(string))
  4939. }
  4940. // sort.Sort()
  4941. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  4942. sort.Slice(createList, func(i, j int) bool {
  4943. return createList[i] > createList[j]
  4944. })
  4945. for _, v := range createList {
  4946. a := make(map[string]interface{})
  4947. a["createdate"] = data[v]
  4948. // createList = append(createList, v.(string))
  4949. respMap = append(respMap, a)
  4950. }
  4951. number := 0
  4952. dataMap := make([]interface{}, 0)
  4953. for k, resp := range respMap {
  4954. createdate := resp["createdate"].(string)
  4955. var nextcreatedate string
  4956. if len(respMap) > k+1 {
  4957. nextcreatedate = respMap[k+1]["createdate"].(string)
  4958. }
  4959. // dataList := make(map[string][]interface{})
  4960. // list := make(map[string]interface{})
  4961. times := make(map[interface{}]int)
  4962. for _, history := range historyList {
  4963. // List := make(map[interface{}][]interface{})
  4964. i := 0
  4965. if history["createdate"].(string) == createdate {
  4966. times[history["times"]]++
  4967. data := make(map[string]interface{})
  4968. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  4969. // exist := false
  4970. if nextcreatedate != "" {
  4971. for _, history1 := range historyList {
  4972. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  4973. history1["times"].(int64) == history["times"].(int64) {
  4974. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  4975. break
  4976. // exist = true
  4977. }
  4978. }
  4979. }
  4980. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  4981. i++
  4982. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  4983. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  4984. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  4985. // resp["times"] = history["times"]
  4986. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  4987. data1 := make(map[string]interface{})
  4988. data1["times"] = history["times"]
  4989. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  4990. data1["createdate"] = resp["createdate"]
  4991. // fmt.Println(dataList)
  4992. dataMap = append(dataMap, data1)
  4993. }
  4994. if i > number {
  4995. number = i
  4996. }
  4997. // respMap = append(respMap, dataList)
  4998. }
  4999. // for k, data := range dataList {
  5000. // resp[k] = data
  5001. // }
  5002. // resp["data"] = dataList
  5003. }
  5004. // resp := make(map[string]interface{})
  5005. // sort.Strings(createList)
  5006. //
  5007. // for _, create := range createList {
  5008. // for _, r := range respMap {
  5009. // if create == r["createdate"].(string) {
  5010. // resp[create] = r
  5011. // break
  5012. // }
  5013. // }
  5014. // }
  5015. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5016. var trainsList []interface{}
  5017. for i := 0; i < number; i++ {
  5018. trains := make(map[string]interface{})
  5019. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5020. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5021. trainsList = append(trainsList, trains)
  5022. }
  5023. respdata := make(map[string]interface{})
  5024. respdata["data"] = dataMap
  5025. respdata["trains"] = trainsList
  5026. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5027. }
  5028. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5029. appG := app.Gin{C: c}
  5030. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5031. parammaps := gofasion.NewFasion(string(dataByte))
  5032. ftid := parammaps.Get("ftid").ValueInt64()
  5033. lastftid := parammaps.Get("lastftid").ValueInt64()
  5034. pastureid := parammaps.Get("pastureid").ValueInt64()
  5035. // createdate := parammaps.Get("createdate").ValueStr()
  5036. tx := restful.Engine.NewSession()
  5037. defer tx.Close()
  5038. data := make(map[string]interface{})
  5039. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5040. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5041. if err != nil {
  5042. logs.Error(err)
  5043. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5044. return
  5045. }
  5046. feedtemplet := make(map[string]interface{})
  5047. for _, f := range feedtempletList {
  5048. feedtemplet = f
  5049. }
  5050. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5051. if err != nil {
  5052. logs.Error(err)
  5053. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5054. return
  5055. }
  5056. feedtemplet["fit"] = fitList
  5057. data["current"] = feedtemplet
  5058. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5059. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5060. if err != nil {
  5061. logs.Error(err)
  5062. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5063. return
  5064. }
  5065. lastfeedtemplet := make(map[string]interface{})
  5066. for _, f := range lastfeedtempletList {
  5067. lastfeedtemplet = f
  5068. }
  5069. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5070. if err != nil {
  5071. logs.Error(err)
  5072. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5073. return
  5074. }
  5075. lastfeedtemplet["fit"] = lastfitList
  5076. data["last"] = lastfeedtemplet
  5077. appG.Response(http.StatusOK, e.SUCCESS, data)
  5078. }
  5079. func GetFeedtempletHistory(c *gin.Context) {
  5080. appG := app.Gin{C: c}
  5081. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5082. parammaps := gofasion.NewFasion(string(dataByte))
  5083. ftid := parammaps.Get("ftid").ValueStr()
  5084. pastureid := parammaps.Get("pastureid").ValueInt64()
  5085. start := parammaps.Get("startdate").ValueStr()
  5086. end := parammaps.Get("enddate").ValueStr()
  5087. tx := restful.Engine.NewSession()
  5088. defer tx.Close()
  5089. ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1 from feedtemplethistory where createdate between ? and ?
  5090. and id = ? and pastureid = ? order by createdate desc `,
  5091. start, end, ftid, pastureid).Query().List()
  5092. if err != nil {
  5093. logs.Error(err)
  5094. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5095. return
  5096. }
  5097. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5098. ftid, pastureid).Query().List()
  5099. if err != nil {
  5100. logs.Error(err)
  5101. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5102. return
  5103. }
  5104. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5105. for i, ft := range ftList {
  5106. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5107. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5108. 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
  5109. where fit.fitid = ?
  5110. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5111. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5112. if err != nil {
  5113. logs.Error(err)
  5114. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5115. return
  5116. }
  5117. ft["createdate"] = ft["createdate1"]
  5118. // data["tname"] = ft["tname"]
  5119. // data["tcode"] = ft["tcode"]
  5120. // data["tcolor"] = ft["tcolor"]
  5121. // data["fttype"] = ft["fttype"]
  5122. // data["ccname"] = ft["ccname"]
  5123. // data["source"] = ft["source"]
  5124. // data["version"] = ft["version"]
  5125. // data["remark"] = ft["remark"]
  5126. for n, ft2 := range ftList {
  5127. if i < n {
  5128. if ft["tname"].(string) != ft2["tname"].(string) {
  5129. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5130. }
  5131. if _, ok := ft["tcode"]; ok {
  5132. if _, ok := ft2["tcode"]; ok {
  5133. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5134. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5135. }
  5136. }
  5137. }
  5138. if _, ok := ft["tcolor"]; ok {
  5139. if _, ok := ft2["tcolor"]; ok {
  5140. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5141. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5142. }
  5143. }
  5144. }
  5145. if _, ok := ft["fttype"]; ok {
  5146. if _, ok := ft2["fttype"]; ok {
  5147. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5148. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5149. }
  5150. }
  5151. }
  5152. if _, ok := ft["ccname"]; ok {
  5153. if _, ok := ft2["ccname"]; ok {
  5154. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5155. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5156. }
  5157. }
  5158. }
  5159. if _, ok := ft["source"]; ok {
  5160. if _, ok := ft2["source"]; ok {
  5161. if ft["source"].(string) != ft2["source"].(string) {
  5162. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5163. }
  5164. }
  5165. }
  5166. if _, ok := ft["version"]; ok {
  5167. if _, ok := ft2["version"]; ok {
  5168. if ft["version"].(int64) != ft2["version"].(int64) {
  5169. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5170. }
  5171. }
  5172. }
  5173. if _, ok := ft["remark"]; ok {
  5174. if _, ok := ft2["remark"]; ok {
  5175. if ft["remark"].(string) != ft2["remark"].(string) {
  5176. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5177. }
  5178. }
  5179. }
  5180. break
  5181. }
  5182. }
  5183. dataList := make([]map[string]interface{}, 0)
  5184. if len(fithisList) > 0 {
  5185. for _, fit := range fithisList {
  5186. data := make(map[string]interface{})
  5187. data["feedgroup"] = fit["feedgroup"]
  5188. data["fname"] = fit["fname"]
  5189. if fit["Eweight"] != nil {
  5190. if fit["Eweight"].(string) != fit["weight"].(string) {
  5191. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5192. } else {
  5193. data["fweight"] = fit["Eweight"]
  5194. }
  5195. data["fweightstatus"] = 1
  5196. } else {
  5197. data["fweight"] = fit["weight"]
  5198. data["fweightstatus"] = 0
  5199. }
  5200. data["autosecond"] = fit["autosecond"]
  5201. // data["tname"] = ft["tname"]
  5202. // data["tcode"] = ft["tcode"]
  5203. // data["tcolor"] = ft["tcolor"]
  5204. // data["fttype"] = ft["fttype"]
  5205. // data["ccname"] = ft["ccname"]
  5206. // data["source"] = ft["source"]
  5207. // data["version"] = ft["version"]
  5208. // data["remark"] = ft["remark"]
  5209. // data["createdate"] = ft["createdate1"]
  5210. // ft["fit"] = data
  5211. dataList = append(dataList, data)
  5212. }
  5213. } else {
  5214. for _, fit := range ftdetailList {
  5215. data := make(map[string]interface{})
  5216. data["feedgroup"] = fit["feedgroup"]
  5217. data["fname"] = fit["fname"]
  5218. // if fit["Eweight"] != nil {
  5219. // data["weight"] = fit["Eweight"]
  5220. // } else {
  5221. data["fweight"] = fit["fweight"]
  5222. // }
  5223. data["autosecond"] = fit["autosecond"]
  5224. // ft["fit"] = data
  5225. dataList = append(dataList, data)
  5226. }
  5227. }
  5228. ft["fit"] = dataList
  5229. }
  5230. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5231. }
  5232. func UpdateMaterialTMR(c *gin.Context) {
  5233. appG := app.Gin{C: c}
  5234. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5235. parammaps := gofasion.NewFasion(string(dataByte))
  5236. tmrid := parammaps.Get("tmrid").ValueStr()
  5237. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5238. lppid := parammaps.Get("lppid").ValueStr()
  5239. times := parammaps.Get("times").ValueStr()
  5240. pastureid := parammaps.Get("pastureid").ValueStr()
  5241. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5242. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5243. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5244. tx := restful.Engine.NewSession()
  5245. defer tx.Close()
  5246. tx.Begin()
  5247. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5248. if err != nil {
  5249. logs.Error(err)
  5250. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5251. return
  5252. }
  5253. var maxstirfeed float64
  5254. for _, tmr := range tmrList {
  5255. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5256. }
  5257. if status == 0 {
  5258. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5259. if err != nil {
  5260. tx.Rollback()
  5261. logs.Error(err)
  5262. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5263. return
  5264. }
  5265. var lweight float64
  5266. for _, item := range lpplandtl1List {
  5267. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5268. lweight += fl
  5269. }
  5270. if lweight > maxstirfeed {
  5271. lweight = lweight - maxstirfeed
  5272. } else {
  5273. lweight = 0
  5274. }
  5275. if lweight > 0 {
  5276. lweight1 := lweight / float64(len(lpplandtl1List))
  5277. number := 0
  5278. for _, item := range lpplandtl1List {
  5279. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5280. if lweight1 >= fl {
  5281. number++
  5282. }
  5283. }
  5284. lweight := lweight / float64((len(lpplandtl1List) - number))
  5285. for _, item := range lpplandtl1List {
  5286. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5287. if lweight1 >= fl {
  5288. continue
  5289. }
  5290. if tmrtype == "1" {
  5291. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5292. if err != nil {
  5293. tx.Rollback()
  5294. logs.Error(err)
  5295. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5296. return
  5297. }
  5298. } else if tmrtype == "2" {
  5299. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5300. if err != nil {
  5301. tx.Rollback()
  5302. logs.Error(err)
  5303. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5304. return
  5305. }
  5306. }
  5307. if item["fttype"].(int64) == 0 {
  5308. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5309. if err != nil {
  5310. tx.Rollback()
  5311. logs.Error(err)
  5312. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5313. return
  5314. }
  5315. } else {
  5316. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5317. if err != nil {
  5318. tx.Rollback()
  5319. logs.Error(err)
  5320. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5321. return
  5322. }
  5323. }
  5324. }
  5325. } else {
  5326. for _, item := range lpplandtl1List {
  5327. // 自走式
  5328. if tmrtype == "1" {
  5329. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5330. if err != nil {
  5331. logs.Error(err)
  5332. tx.Rollback()
  5333. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5334. return
  5335. }
  5336. } else if tmrtype == "2" {
  5337. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5338. if err != nil {
  5339. logs.Error(err)
  5340. tx.Rollback()
  5341. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5342. return
  5343. }
  5344. }
  5345. }
  5346. }
  5347. } else if status == 1 {
  5348. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5349. if err != nil {
  5350. logs.Error(err)
  5351. tx.Rollback()
  5352. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5353. return
  5354. }
  5355. var lweight float64
  5356. for _, item := range lpplandtl1List {
  5357. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5358. lweight += fl
  5359. }
  5360. if lweight > maxstirfeed {
  5361. lweight = lweight - maxstirfeed
  5362. } else {
  5363. lweight = 0
  5364. }
  5365. for _, item := range lpplandtl1List {
  5366. if lweight > 0 {
  5367. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5368. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5369. if fl >= lweight {
  5370. item["lweight"] = fl - lweight
  5371. lweight = 0
  5372. if tmrtype == "1" {
  5373. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5374. if err != nil {
  5375. logs.Error(err)
  5376. tx.Rollback()
  5377. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5378. return
  5379. }
  5380. } else if tmrtype == "2" {
  5381. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5382. if err != nil {
  5383. logs.Error(err)
  5384. tx.Rollback()
  5385. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5386. return
  5387. }
  5388. }
  5389. if item["fttype"].(int64) == 0 {
  5390. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5391. if err != nil {
  5392. logs.Error(err)
  5393. tx.Rollback()
  5394. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5395. return
  5396. }
  5397. } else {
  5398. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5399. if err != nil {
  5400. logs.Error(err)
  5401. tx.Rollback()
  5402. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5403. return
  5404. }
  5405. }
  5406. } else {
  5407. lweight = lweight - fl
  5408. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5409. if err != nil {
  5410. logs.Error(err)
  5411. tx.Rollback()
  5412. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5413. return
  5414. }
  5415. if item["fttype"].(int64) == 0 {
  5416. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5417. if err != nil {
  5418. logs.Error(err)
  5419. tx.Rollback()
  5420. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5421. return
  5422. }
  5423. } else {
  5424. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5425. if err != nil {
  5426. logs.Error(err)
  5427. tx.Rollback()
  5428. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5429. return
  5430. }
  5431. }
  5432. }
  5433. } else {
  5434. // 自走式
  5435. if tmrtype == "1" {
  5436. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5437. if err != nil {
  5438. logs.Error(err)
  5439. tx.Rollback()
  5440. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5441. return
  5442. }
  5443. } else if tmrtype == "2" {
  5444. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5445. if err != nil {
  5446. logs.Error(err)
  5447. tx.Rollback()
  5448. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5449. return
  5450. }
  5451. }
  5452. }
  5453. }
  5454. } else {
  5455. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5456. if err != nil {
  5457. logs.Error(err)
  5458. tx.Rollback()
  5459. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5460. return
  5461. }
  5462. for _, item := range lpplandtl1List {
  5463. if item["fttype"].(int64) == 0 {
  5464. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5465. if err != nil {
  5466. logs.Error(err)
  5467. tx.Rollback()
  5468. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5469. return
  5470. }
  5471. } else {
  5472. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5473. if err != nil {
  5474. logs.Error(err)
  5475. tx.Rollback()
  5476. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5477. return
  5478. }
  5479. }
  5480. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5481. if err != nil {
  5482. logs.Error(err)
  5483. tx.Rollback()
  5484. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5485. return
  5486. }
  5487. }
  5488. }
  5489. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5490. if err != nil {
  5491. logs.Error(err)
  5492. tx.Rollback()
  5493. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5494. return
  5495. }
  5496. err = tx.Commit()
  5497. if err != nil {
  5498. logs.Error(err)
  5499. tx.Rollback()
  5500. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5501. return
  5502. }
  5503. appG.Response(http.StatusOK, e.SUCCESS, true)
  5504. }
  5505. func UpdateMaterialTMRDate(c *gin.Context) {
  5506. appG := app.Gin{C: c}
  5507. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5508. parammaps := gofasion.NewFasion(string(dataByte))
  5509. tmrid := parammaps.Get("tmrid").ValueStr()
  5510. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5511. lppid := parammaps.Get("lppid").ValueStr()
  5512. times := parammaps.Get("times").ValueStr()
  5513. pastureid := parammaps.Get("pastureid").ValueStr()
  5514. date := parammaps.Get("date").ValueStr()
  5515. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5516. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5517. tx := restful.Engine.NewSession()
  5518. defer tx.Close()
  5519. tx.Begin()
  5520. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5521. if err != nil {
  5522. logs.Error(err)
  5523. tx.Rollback()
  5524. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5525. return
  5526. }
  5527. var maxstirfeed float64
  5528. for _, tmr := range tmrList {
  5529. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5530. }
  5531. if status == 0 {
  5532. 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()
  5533. if err != nil {
  5534. logs.Error(err)
  5535. tx.Rollback()
  5536. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5537. return
  5538. }
  5539. var lweight float64
  5540. for _, item := range lpplandtl1List {
  5541. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5542. lweight += fl
  5543. }
  5544. if lweight > maxstirfeed {
  5545. lweight = lweight - maxstirfeed
  5546. } else {
  5547. lweight = 0
  5548. }
  5549. if lweight > 0 {
  5550. lweight1 := lweight / float64(len(lpplandtl1List))
  5551. number := 0
  5552. for _, item := range lpplandtl1List {
  5553. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5554. if lweight1 >= fl {
  5555. number++
  5556. }
  5557. }
  5558. lweight := lweight / float64((len(lpplandtl1List) - number))
  5559. for _, item := range lpplandtl1List {
  5560. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5561. if lweight1 >= fl {
  5562. continue
  5563. }
  5564. if tmrtype == "1" {
  5565. _, 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()
  5566. if err != nil {
  5567. logs.Error(err)
  5568. tx.Rollback()
  5569. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5570. return
  5571. }
  5572. } else if tmrtype == "2" {
  5573. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5574. if err != nil {
  5575. logs.Error(err)
  5576. tx.Rollback()
  5577. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5578. return
  5579. }
  5580. }
  5581. if item["fttype"].(int64) == 0 {
  5582. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5583. if err != nil {
  5584. logs.Error(err)
  5585. tx.Rollback()
  5586. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5587. return
  5588. }
  5589. } else {
  5590. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5591. if err != nil {
  5592. logs.Error(err)
  5593. tx.Rollback()
  5594. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5595. return
  5596. }
  5597. }
  5598. }
  5599. } else {
  5600. for _, item := range lpplandtl1List {
  5601. // 自走式
  5602. if tmrtype == "1" {
  5603. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5604. if err != nil {
  5605. logs.Error(err)
  5606. tx.Rollback()
  5607. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5608. return
  5609. }
  5610. } else if tmrtype == "2" {
  5611. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5612. if err != nil {
  5613. logs.Error(err)
  5614. tx.Rollback()
  5615. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5616. return
  5617. }
  5618. }
  5619. }
  5620. }
  5621. } else if status == 1 {
  5622. 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()
  5623. if err != nil {
  5624. logs.Error(err)
  5625. tx.Rollback()
  5626. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5627. return
  5628. }
  5629. var lweight float64
  5630. for _, item := range lpplandtl1List {
  5631. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5632. lweight += fl
  5633. }
  5634. if lweight > maxstirfeed {
  5635. lweight = lweight - maxstirfeed
  5636. } else {
  5637. lweight = 0
  5638. }
  5639. for _, item := range lpplandtl1List {
  5640. if lweight > 0 {
  5641. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5642. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5643. if fl >= lweight {
  5644. item["lweight"] = fl - lweight
  5645. lweight = 0
  5646. if tmrtype == "1" {
  5647. _, 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()
  5648. if err != nil {
  5649. logs.Error(err)
  5650. tx.Rollback()
  5651. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5652. return
  5653. }
  5654. } else if tmrtype == "2" {
  5655. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5656. if err != nil {
  5657. logs.Error(err)
  5658. tx.Rollback()
  5659. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5660. return
  5661. }
  5662. }
  5663. if item["fttype"].(int64) == 0 {
  5664. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5665. if err != nil {
  5666. logs.Error(err)
  5667. tx.Rollback()
  5668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5669. return
  5670. }
  5671. } else {
  5672. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5673. if err != nil {
  5674. logs.Error(err)
  5675. tx.Rollback()
  5676. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5677. return
  5678. }
  5679. }
  5680. } else {
  5681. lweight = lweight - fl
  5682. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5683. if err != nil {
  5684. logs.Error(err)
  5685. tx.Rollback()
  5686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5687. return
  5688. }
  5689. if item["fttype"].(int64) == 0 {
  5690. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5691. if err != nil {
  5692. logs.Error(err)
  5693. tx.Rollback()
  5694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5695. return
  5696. }
  5697. } else {
  5698. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5699. if err != nil {
  5700. logs.Error(err)
  5701. tx.Rollback()
  5702. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5703. return
  5704. }
  5705. }
  5706. }
  5707. } else {
  5708. // 自走式
  5709. if tmrtype == "1" {
  5710. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5711. if err != nil {
  5712. logs.Error(err)
  5713. tx.Rollback()
  5714. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5715. return
  5716. }
  5717. } else if tmrtype == "2" {
  5718. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5719. if err != nil {
  5720. logs.Error(err)
  5721. tx.Rollback()
  5722. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5723. return
  5724. }
  5725. }
  5726. }
  5727. }
  5728. } else {
  5729. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  5730. if err != nil {
  5731. logs.Error(err)
  5732. tx.Rollback()
  5733. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5734. return
  5735. }
  5736. for _, item := range lpplandtl1List {
  5737. if item["fttype"].(int64) == 0 {
  5738. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5739. if err != nil {
  5740. logs.Error(err)
  5741. tx.Rollback()
  5742. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5743. return
  5744. }
  5745. } else {
  5746. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5747. if err != nil {
  5748. logs.Error(err)
  5749. tx.Rollback()
  5750. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5751. return
  5752. }
  5753. }
  5754. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5755. if err != nil {
  5756. logs.Error(err)
  5757. tx.Rollback()
  5758. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5759. return
  5760. }
  5761. }
  5762. }
  5763. _, 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()
  5764. if err != nil {
  5765. logs.Error(err)
  5766. tx.Rollback()
  5767. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5768. return
  5769. }
  5770. err = tx.Commit()
  5771. if err != nil {
  5772. logs.Error(err)
  5773. tx.Rollback()
  5774. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5775. return
  5776. }
  5777. appG.Response(http.StatusOK, e.SUCCESS, true)
  5778. }