db.go 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207
  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. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? `, id).Query().List()
  3168. // if err != nil {
  3169. // logs.Error(err)
  3170. // appG.Response(http.StatusOK, e.ERROR, false)
  3171. // return
  3172. // }
  3173. tx.Begin()
  3174. for _, list := range fsion.Get("data").Array() {
  3175. ftmap := make(map[string]interface{})
  3176. ftmap["old"] = list.Get("old").ValueFloat64()
  3177. ftmap["new"] = list.Get("new").ValueFloat64()
  3178. ftmap["times"] = list.Get("times").ValueInt64()
  3179. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3180. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3181. // fmt.Println(ftmap)
  3182. 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 ,
  3183. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3184. WHERE fpdetail.pastureid = ? and barid = ? and times = ?
  3185. UNION
  3186. 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 ,
  3187. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3188. WHERE fpdetail.pastureid = ? and barid = ? and times = ? ) t
  3189. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3190. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3191. if err != nil {
  3192. tx.Rollback()
  3193. logs.Error(err)
  3194. }
  3195. for _, fpd := range fpdDataList {
  3196. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3197. fttype := -1
  3198. if ftmap["ptid"].(string) != "-1" {
  3199. fttype = 1
  3200. }
  3201. var fweight float64
  3202. var lweight float64
  3203. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3204. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3205. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3206. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3207. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3208. if err != nil {
  3209. tx.Rollback()
  3210. logs.Error(err)
  3211. }
  3212. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3213. var w float64
  3214. var status int
  3215. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3216. if weight >= 0 {
  3217. continue
  3218. }
  3219. w = weight
  3220. status = 0
  3221. } else {
  3222. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  3223. continue
  3224. }
  3225. w = weight
  3226. status = 1
  3227. }
  3228. for _, lppland := range lpplandtl1List {
  3229. lweight += lppland.Lweight
  3230. }
  3231. for _, lppland := range lpplandtl1List {
  3232. if status == 1 {
  3233. // if w <= lppland.Lweight {
  3234. if lppland.Maxweight <= lweight {
  3235. continue
  3236. }
  3237. if w+lweight <= lppland.Maxweight {
  3238. lppland.Lweight += w
  3239. lweight += w
  3240. fweight += w
  3241. w = 0
  3242. } else {
  3243. w = w - (lppland.Maxweight - lweight)
  3244. n := (lppland.Maxweight - lweight)
  3245. lppland.Lweight = lppland.Lweight + n
  3246. lweight += n
  3247. fweight += n
  3248. }
  3249. } else {
  3250. if lppland.Lweight == 0 {
  3251. continue
  3252. }
  3253. if w+lppland.Lweight >= 0 {
  3254. lppland.Lweight = lppland.Lweight + w
  3255. lweight = lweight + w
  3256. fweight = fweight + w
  3257. w = 0
  3258. } else {
  3259. w = w + lppland.Lweight
  3260. lweight = lweight - lppland.Lweight
  3261. fweight = fweight - lppland.Lweight
  3262. lppland.Lweight = 0
  3263. }
  3264. }
  3265. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3266. if err != nil {
  3267. tx.Rollback()
  3268. logs.Error(err)
  3269. return
  3270. }
  3271. break
  3272. }
  3273. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3274. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3275. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3276. if err != nil {
  3277. tx.Rollback()
  3278. logs.Error(err)
  3279. }
  3280. if w == 0 {
  3281. break
  3282. }
  3283. }
  3284. }
  3285. }
  3286. tx.Commit()
  3287. now := time.Now()
  3288. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3289. if err != nil {
  3290. logs.Error(err)
  3291. appG.Response(http.StatusOK, e.ERROR, false)
  3292. return
  3293. }
  3294. // newFpdDataList, err := tx.SQL(` select * from fpdetail where barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3295. // if err != nil {
  3296. // logs.Error(err)
  3297. // appG.Response(http.StatusOK, e.ERROR, false)
  3298. // return
  3299. // }
  3300. // newFeedpList, err := tx.SQL(` select * from feedp where barid = ? and pastureid = ?`, id, pastureid).Query().List()
  3301. // if err != nil {
  3302. // logs.Error(err)
  3303. // appG.Response(http.StatusOK, e.ERROR, false)
  3304. // return
  3305. // }
  3306. for _, newLpplandtl1 := range newLpplandtl1List {
  3307. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3308. background,cowcount,ccountradio,lweighthis,createdate)
  3309. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3310. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3311. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3312. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3313. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3314. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3315. if err != nil {
  3316. logs.Error(err)
  3317. appG.Response(http.StatusOK, e.ERROR, false)
  3318. return
  3319. }
  3320. }
  3321. // for _, newFpd := range newFpdDataList {
  3322. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  3323. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3324. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3325. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  3326. // if err != nil {
  3327. // logs.Error(err)
  3328. // appG.Response(http.StatusOK, e.ERROR, false)
  3329. // return
  3330. // }
  3331. // }
  3332. // for _, newFeedp := range newFeedpList {
  3333. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3334. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  3335. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3336. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3337. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3338. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3339. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3340. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  3341. // if err != nil {
  3342. // logs.Error(err)
  3343. // appG.Response(http.StatusOK, e.ERROR, false)
  3344. // return
  3345. // }
  3346. // }
  3347. appG.Response(http.StatusOK, e.SUCCESS, true)
  3348. }
  3349. func GetProcessAnalysis(c *gin.Context) {
  3350. appG := app.Gin{C: c}
  3351. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3352. fsion := gofasion.NewFasion(string(dataByte))
  3353. sqlnamestr := fsion.Get("name").ValueStr()
  3354. offset := fsion.Get("offset").ValueDefaultInt(0)
  3355. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3356. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3357. parammaps := fsion.Get("parammaps")
  3358. tx := restful.Engine.NewSession()
  3359. err := tx.Begin()
  3360. defer func() {
  3361. switch {
  3362. case err != nil:
  3363. logging.Error("tx.Begin 事务启动失败__error:", err)
  3364. if tx != nil {
  3365. tx.Rollback()
  3366. }
  3367. default:
  3368. if tx != nil {
  3369. err = tx.Commit()
  3370. }
  3371. }
  3372. if tx != nil {
  3373. tx.Close()
  3374. }
  3375. }()
  3376. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3377. s_params := make([]interface{}, 0)
  3378. paramslist := strings.Split(p, ",")
  3379. if len(paramslist) > 0 && p != "" {
  3380. for _, value := range paramslist {
  3381. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3382. if tempv, exists := c.Get("jwt_username"); exists {
  3383. s_params = append(s_params, tempv.(string))
  3384. } else {
  3385. s_params = append(s_params, "")
  3386. }
  3387. } else {
  3388. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3389. }
  3390. }
  3391. }
  3392. tmrtnameStr := ""
  3393. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3394. if len(tmrtnameStr) == 0 {
  3395. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3396. } else {
  3397. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3398. }
  3399. }
  3400. if len(tmrtnameStr) > 0 {
  3401. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3402. }
  3403. sql += " ORDER BY d.intime"
  3404. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3405. if err != nil {
  3406. logging.Error("GetDataByName err: ", err)
  3407. msg := geterrmsg(err.Error())
  3408. appG.Response(http.StatusOK, e.ERROR, msg)
  3409. } else {
  3410. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3411. }
  3412. }
  3413. func UpdateFeedtempletStatus(c *gin.Context) {
  3414. appG := app.Gin{C: c}
  3415. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3416. fsion := gofasion.NewFasion(string(dataByte))
  3417. parammaps := fsion.Get("parammaps")
  3418. tx := restful.Engine.NewSession()
  3419. tx.Begin()
  3420. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3421. if err != nil {
  3422. tx.Rollback()
  3423. logs.Error(err)
  3424. appG.Response(http.StatusOK, e.ERROR, err)
  3425. return
  3426. }
  3427. tx.Commit()
  3428. appG.Response(http.StatusOK, e.SUCCESS, true)
  3429. }
  3430. func AddFtdry(c *gin.Context) {
  3431. appG := app.Gin{C: c}
  3432. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3433. fsion := gofasion.NewFasion(string(dataByte))
  3434. sqlnamestr := fsion.Get("name").ValueStr()
  3435. s_params := make([]interface{}, 0)
  3436. tx := restful.Engine.NewSession()
  3437. err := tx.Begin()
  3438. defer func() {
  3439. switch {
  3440. case err != nil:
  3441. if tx != nil {
  3442. tx.Rollback()
  3443. }
  3444. default:
  3445. if tx != nil {
  3446. err = tx.Commit()
  3447. }
  3448. }
  3449. if tx != nil {
  3450. tx.Close()
  3451. }
  3452. }()
  3453. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3454. if sql != "" {
  3455. parammaps := fsion.Get("parammaps")
  3456. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3457. paramslist := strings.Split(p, ",")
  3458. if len(paramslist) > 0 && p != "" {
  3459. for _, value := range paramslist {
  3460. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3461. if tempv, exists := c.Get("jwt_username"); exists {
  3462. s_params = append(s_params, tempv.(string))
  3463. } else {
  3464. s_params = append(s_params, "")
  3465. }
  3466. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3467. ids, err := setting.SnowIds.NextId()
  3468. if err != nil {
  3469. ids = time.Now().UnixNano()
  3470. logging.Info("create SnowIds err", err)
  3471. }
  3472. s_params = append(s_params, ids)
  3473. } else {
  3474. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3475. }
  3476. }
  3477. }
  3478. var actweight float64
  3479. actweightList, err := tx.SQL(`select ROUND(avg(actweight),2) as actweight from ftdry
  3480. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3481. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3482. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3483. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3484. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3485. 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()
  3486. if err != nil {
  3487. logging.Error("AddFtdry err: ", err)
  3488. msg := geterrmsg(err.Error())
  3489. appG.Response(http.StatusOK, e.ERROR, msg)
  3490. }
  3491. if len(actweightList) > 0 {
  3492. for _, item := range actweightList {
  3493. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3494. if err != nil {
  3495. logging.Error("AddFtdry err: ", err)
  3496. msg := geterrmsg(err.Error())
  3497. appG.Response(http.StatusOK, e.ERROR, msg)
  3498. }
  3499. actweight = fl
  3500. }
  3501. } else {
  3502. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3503. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3504. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3505. if err != nil {
  3506. logging.Error("AddFtdry err: ", err)
  3507. msg := geterrmsg(err.Error())
  3508. appG.Response(http.StatusOK, e.ERROR, msg)
  3509. }
  3510. for _, item := range dryList {
  3511. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3512. if err != nil {
  3513. logging.Error("AddFtdry err: ", err)
  3514. msg := geterrmsg(err.Error())
  3515. appG.Response(http.StatusOK, e.ERROR, msg)
  3516. }
  3517. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3518. }
  3519. }
  3520. if sqlnamestr == "insertFtdry" {
  3521. s_params = append(s_params, actweight)
  3522. } else if sqlnamestr == "updateFtdry" {
  3523. sql = fmt.Sprintf(sql, actweight)
  3524. }
  3525. queryData, err := execDataBySqlT(sql, s_params, tx)
  3526. if err != nil {
  3527. logging.Error("AddFtdry err: ", err)
  3528. msg := geterrmsg(err.Error())
  3529. appG.Response(http.StatusOK, e.ERROR, msg)
  3530. } else {
  3531. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3532. }
  3533. } else {
  3534. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3535. }
  3536. }
  3537. func CheckDates(c *gin.Context) {
  3538. tx := restful.Engine.NewSession()
  3539. defer tx.Close()
  3540. appG := app.Gin{C: c}
  3541. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3542. tempval_ := make(map[string]interface{})
  3543. tempCommon := make(map[string]interface{})
  3544. tempval := make([]map[string]interface{}, 0)
  3545. err := json.Unmarshal(dataByte, &tempval_)
  3546. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3547. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3548. if err != nil {
  3549. } else {
  3550. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3551. tempCommon = v
  3552. }
  3553. if v, ok := tempval_["data"].([]interface{}); ok {
  3554. for _, Tvalue := range v {
  3555. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3556. tempval = append(tempval, v1)
  3557. }
  3558. }
  3559. }
  3560. if err == nil {
  3561. if tempv, exists := c.Get("jwt_username"); exists {
  3562. tempCommon["jwt_username"] = tempv.(string)
  3563. }
  3564. for _, paramvalue := range tempval {
  3565. if _, ok := paramvalue["resultname"]; !ok {
  3566. paramvalue["resultname"] = paramvalue["name"]
  3567. }
  3568. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3569. if err != nil {
  3570. logging.Error("ExecDataParam error:", err)
  3571. }
  3572. }
  3573. if err == nil {
  3574. vmsg := ""
  3575. for _, item := range tempval {
  3576. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3577. for _, childrenList := range list.([]interface{}) {
  3578. for k, children := range childrenList.(map[string]interface{}) {
  3579. if k != "children" {
  3580. continue
  3581. }
  3582. for _, v := range children.([]map[string]interface{}) {
  3583. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3584. if k1 == "list" {
  3585. for _, v2 := range v1.([]map[string]interface{}) {
  3586. if v2["vmsg"].(string) != "1" {
  3587. if len(vmsg) == 0 {
  3588. vmsg = v2["vmsg"].(string)
  3589. } else {
  3590. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3591. }
  3592. }
  3593. }
  3594. }
  3595. }
  3596. }
  3597. }
  3598. }
  3599. }
  3600. }
  3601. if len(vmsg) > 0 {
  3602. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3603. } else {
  3604. appG.Response(http.StatusOK, e.SUCCESS, true)
  3605. }
  3606. } else {
  3607. msg := geterrmsg(err.Error())
  3608. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3609. }
  3610. }
  3611. }
  3612. if err != nil {
  3613. msg := geterrmsg(err.Error())
  3614. appG.Response(http.StatusOK, e.ERROR, msg)
  3615. }
  3616. }
  3617. 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) {
  3618. sqlname := fasion["name"].(string)
  3619. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3620. if v, ok := fasion["type"]; ok {
  3621. sqltype = v.(string)
  3622. }
  3623. sql := ""
  3624. p := ""
  3625. s_params := make([]interface{}, 0)
  3626. if sqltype != "" {
  3627. sql, p = restful.GetSqlByName(sqlname, tx)
  3628. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3629. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3630. paramslist := strings.Split(p, ",")
  3631. if len(paramslist) > 0 && p != "" {
  3632. for _, value := range paramslist {
  3633. ss := ""
  3634. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3635. ids, err := setting.SnowIds.NextId()
  3636. if err != nil {
  3637. ids = time.Now().UnixNano()
  3638. logging.Info("create SnowIds err", err)
  3639. }
  3640. s_params = append(s_params, ids)
  3641. } else {
  3642. if ss == "" && CommonParamMap != nil {
  3643. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3644. ss = valuestring
  3645. tempstrb := strings.IndexAny(valuestring, "@")
  3646. tempstre := strings.IndexAny(valuestring, ".")
  3647. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3648. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3649. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3650. }
  3651. } else {
  3652. ss = ""
  3653. }
  3654. }
  3655. }
  3656. if ss == "" && ParentParamMap != nil {
  3657. ss = getParamValue_(v, value, ParentParamMap)
  3658. }
  3659. if ss == "" && sameParamMap != nil {
  3660. ss = getParamValue(v, value, sameParamMap)
  3661. }
  3662. if ss == "" && ParamMap != nil {
  3663. ss = getParamValue(v, value, ParamMap)
  3664. }
  3665. s_params = append(s_params, ss)
  3666. }
  3667. }
  3668. }
  3669. }
  3670. }
  3671. if sql == "" {
  3672. sqltype = ""
  3673. }
  3674. if sql != "" {
  3675. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3676. if err != nil {
  3677. return nil, err
  3678. }
  3679. // fmt.Println(tempValParam)
  3680. return tempValParam.(map[string]interface{}), nil
  3681. } else {
  3682. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3683. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3684. if err != nil {
  3685. return nil, err
  3686. }
  3687. return nil, err
  3688. }
  3689. }
  3690. return nil, nil
  3691. }
  3692. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3693. var err error
  3694. subarray, ok := fasion["children"]
  3695. if ok {
  3696. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3697. tempVal_arrary := make([]map[string]interface{}, 0)
  3698. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3699. tempVal_ := make(map[string]interface{})
  3700. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3701. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3702. } else {
  3703. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3704. }
  3705. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3706. if err != nil {
  3707. return err
  3708. }
  3709. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3710. }
  3711. v.(map[string]interface{})["children"] = tempVal_arrary
  3712. }
  3713. }
  3714. return nil
  3715. }
  3716. func FpdImportExcel(c *gin.Context) {
  3717. appG := app.Gin{C: c}
  3718. inputdata := ""
  3719. c.Request.ParseForm()
  3720. params := c.Request.Form
  3721. file, _, err := c.Request.FormFile("file")
  3722. if err != nil {
  3723. appG.Response(http.StatusOK, e.ERROR, err)
  3724. return
  3725. }
  3726. sqlnamestrs := params.Get("name")
  3727. sheetname := params.Get("sheetname")
  3728. pastureid := params.Get("pastureid")
  3729. // importParams := params.Get("importParams")
  3730. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3731. // 必输项参数 (字符串格式 "field1,field2,field3")
  3732. requiredParams := params.Get("requiredParams")
  3733. // 日期参数
  3734. dateParams := params.Get("dateParams")
  3735. // 数字参数
  3736. numParams := params.Get("numParams")
  3737. //将字符串分割开
  3738. dateParamslist := strings.Split(dateParams, ",")
  3739. requiredParamslist := strings.Split(requiredParams, ",")
  3740. numParamslist := strings.Split(numParams, ",")
  3741. queryData := make([]interface{}, 0)
  3742. sqlslist := strings.Split(sqlnamestrs, ",")
  3743. xlsx1, err := excelize.OpenReader(file)
  3744. if err != nil {
  3745. fmt.Println(err)
  3746. return
  3747. }
  3748. ok := 0
  3749. error := 0
  3750. isdone := true
  3751. tx := restful.Engine.NewSession()
  3752. defer tx.Close()
  3753. 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
  3754. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3755. if err != nil {
  3756. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3757. return
  3758. }
  3759. for _, item := range oldFpdList {
  3760. fmt.Println(item)
  3761. }
  3762. rows, _ := xlsx1.GetRows(sheetname)
  3763. // 限制10000条,多余的截取掉
  3764. if len(rows) > 10000 {
  3765. rows = rows[:10000]
  3766. }
  3767. for i, row := range rows {
  3768. if i > 0 {
  3769. entry := make(map[string]interface{})
  3770. outentry := make(map[string]interface{})
  3771. for j, colCell := range rows[0] {
  3772. for k, colCell1 := range row {
  3773. if j == k {
  3774. outentry[colCell] = colCell1
  3775. entry[colCell] = colCell1
  3776. }
  3777. }
  3778. }
  3779. inputdata = ""
  3780. a := ""
  3781. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3782. //校验日期格式
  3783. for _, v := range dateParamslist {
  3784. if v == "" {
  3785. continue
  3786. }
  3787. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3788. dtime, err := TransfTime(d.(string))
  3789. if err != nil {
  3790. a = strings.Trim(v, " ")
  3791. break
  3792. }
  3793. outentry[strings.Trim(v, " ")] = dtime
  3794. }
  3795. }
  3796. if a != "" {
  3797. outentry["error_msg"] = a + " 格式错误"
  3798. error++
  3799. queryData = append(queryData, outentry)
  3800. continue
  3801. }
  3802. a = ""
  3803. //校验必填格式
  3804. for _, v := range requiredParamslist {
  3805. if v == "" {
  3806. continue
  3807. }
  3808. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3809. a = strings.Trim(v, " ")
  3810. break
  3811. }
  3812. }
  3813. if a != "" {
  3814. outentry["error_msg"] = a + " 未填或格式错误"
  3815. error++
  3816. queryData = append(queryData, outentry)
  3817. continue
  3818. }
  3819. a = ""
  3820. //校验数字格式
  3821. for _, v := range numParamslist {
  3822. if v == "" {
  3823. continue
  3824. }
  3825. d, ok := outentry[strings.Trim(v, " ")]
  3826. if !ok || d == "" {
  3827. outentry[strings.Trim(v, " ")] = 0
  3828. } else {
  3829. var fl float64
  3830. switch d.(type) {
  3831. case string:
  3832. fl, err = strconv.ParseFloat(d.(string), 64)
  3833. }
  3834. if err != nil || fl < 0 {
  3835. a = strings.Trim(v, " ")
  3836. break
  3837. }
  3838. }
  3839. }
  3840. if a != "" {
  3841. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3842. error++
  3843. queryData = append(queryData, outentry)
  3844. continue
  3845. }
  3846. errExist := false
  3847. for _, sqlnamestr := range sqlslist {
  3848. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3849. paramslist := strings.Split(paramslists, ",")
  3850. if len(paramslist) > 0 {
  3851. s_params := make([]interface{}, 0)
  3852. for _, value := range paramslist {
  3853. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3854. if tempv, exists := c.Get("jwt_username"); exists {
  3855. s_params = append(s_params, tempv.(string))
  3856. } else {
  3857. s_params = append(s_params, "")
  3858. }
  3859. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3860. s_params = append(s_params, pastureid)
  3861. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3862. ids, err := setting.SnowIds.NextId()
  3863. if err != nil {
  3864. ids = time.Now().UnixNano()
  3865. logging.Info("create SnowIds err", err)
  3866. }
  3867. s_params = append(s_params, ids)
  3868. } else {
  3869. if outentry[strings.Trim(value, " ")] == nil {
  3870. s_params = append(s_params, "")
  3871. } else {
  3872. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3873. }
  3874. }
  3875. }
  3876. outentry["input"] = inputdata
  3877. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3878. if err != nil {
  3879. errExist = true
  3880. // if tx != nil {
  3881. // tx.Rollback()
  3882. // }
  3883. // if tx != nil {
  3884. // tx.Close()
  3885. // }
  3886. msg := geterrmsg(err.Error())
  3887. outentry["error_msg"] = msg
  3888. error++
  3889. queryData = append(queryData, outentry)
  3890. isdone = true
  3891. break
  3892. } else {
  3893. if len(returnmsgmap1) > 0 {
  3894. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3895. // if tx != nil {
  3896. // tx.Rollback()
  3897. // }
  3898. // if tx != nil {
  3899. // tx.Close()
  3900. // }
  3901. msg := geterrmsg(va.(string))
  3902. outentry["error_msg"] = msg
  3903. error++
  3904. queryData = append(queryData, outentry)
  3905. isdone = true
  3906. break
  3907. }
  3908. }
  3909. isdone = false
  3910. }
  3911. }
  3912. }
  3913. if !errExist {
  3914. dataexcel := make(map[string]interface{}, 0)
  3915. if _, ok := outentry["栏舍名称"]; ok {
  3916. dataexcel["barname"] = outentry["栏舍名称"]
  3917. }
  3918. if _, ok := outentry["实际牛头数"]; ok {
  3919. dataexcel["ccount"] = outentry["实际牛头数"]
  3920. }
  3921. if _, ok := outentry["系数(%)"]; ok {
  3922. dataexcel["ratio"] = outentry["系数(%)"]
  3923. }
  3924. if _, ok := outentry["配方模板"]; ok {
  3925. dataexcel["ftname"] = outentry["配方模板"]
  3926. }
  3927. if _, ok := outentry["补料配方"]; ok {
  3928. dataexcel["ptsfname"] = outentry["补料配方"]
  3929. }
  3930. if _, ok := outentry["第一班比例(%)"]; ok {
  3931. dataexcel["1"] = outentry["第一班比例(%)"]
  3932. }
  3933. if _, ok := outentry["第二班比例(%)"]; ok {
  3934. dataexcel["2"] = outentry["第二班比例(%)"]
  3935. }
  3936. if _, ok := outentry["第三班比例(%)"]; ok {
  3937. dataexcel["3"] = outentry["第三班比例(%)"]
  3938. }
  3939. if _, ok := outentry["第四班比例(%)"]; ok {
  3940. dataexcel["4"] = outentry["第四班比例(%)"]
  3941. }
  3942. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3943. if err != nil {
  3944. logs.Error(err)
  3945. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3946. return
  3947. }
  3948. if !exist {
  3949. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  3950. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  3951. if err != nil {
  3952. logs.Error(err)
  3953. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3954. return
  3955. }
  3956. }
  3957. var feedpargs []interface{}
  3958. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  3959. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  3960. if _, ok := dataexcel["ftname"]; ok {
  3961. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  3962. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  3963. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  3964. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  3965. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  3966. } else {
  3967. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  3968. }
  3969. if _, ok := dataexcel["ptsfname"]; ok {
  3970. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  3971. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  3972. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  3973. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  3974. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  3975. } else {
  3976. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  3977. }
  3978. upFeedpSql += " where barname = ? and pastureid = ? "
  3979. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  3980. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  3981. if err != nil {
  3982. logs.Error(err)
  3983. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3984. return
  3985. }
  3986. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3987. if err != nil {
  3988. logs.Error(err)
  3989. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3990. return
  3991. }
  3992. if !exist1 {
  3993. _, 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) `,
  3994. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3995. if err != nil {
  3996. logs.Error(err)
  3997. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3998. return
  3999. }
  4000. _, 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) `,
  4001. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4002. if err != nil {
  4003. logs.Error(err)
  4004. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4005. return
  4006. }
  4007. _, 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) `,
  4008. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4009. if err != nil {
  4010. logs.Error(err)
  4011. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4012. return
  4013. }
  4014. _, 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) `,
  4015. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4016. if err != nil {
  4017. logs.Error(err)
  4018. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4019. return
  4020. }
  4021. }
  4022. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4023. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4024. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4025. and pastureid = ? and times = ?`
  4026. var fpdargs1 []interface{}
  4027. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4028. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4029. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4030. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4031. if err != nil {
  4032. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4033. return
  4034. }
  4035. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4036. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4037. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4038. // and pastureid = ? and times = ?`
  4039. var fpdargs2 []interface{}
  4040. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4041. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4042. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4043. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4044. if err != nil {
  4045. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4046. return
  4047. }
  4048. var fpdargs3 []interface{}
  4049. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4050. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4051. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4052. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4053. if err != nil {
  4054. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4055. return
  4056. }
  4057. var fpdargs4 []interface{}
  4058. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4059. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4060. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4061. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4062. if err != nil {
  4063. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4064. return
  4065. }
  4066. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4067. 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()
  4068. if err != nil {
  4069. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4070. return
  4071. }
  4072. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4073. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4074. upFpdetailList := make([]*upFpdetail, 0)
  4075. for _, newfpd := range newList {
  4076. for _, oldfpd := range oldFpdList {
  4077. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4078. var oldweight, newweight float64
  4079. if oldfpd["weight"] != nil {
  4080. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4081. }
  4082. if newfpd["weight"] != nil {
  4083. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4084. }
  4085. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4086. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4087. Old: oldweight,
  4088. New: newweight,
  4089. Times: newfpd["times"].(int64),
  4090. Ptid: newfpd["ptid"].(int64),
  4091. Fweight: fweight,
  4092. Id: oldfpd["id"].(int64),
  4093. })
  4094. break
  4095. }
  4096. }
  4097. }
  4098. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4099. }
  4100. }
  4101. if !isdone {
  4102. ok++
  4103. isdone = true
  4104. }
  4105. }
  4106. data := make(map[string]interface{})
  4107. data["result"] = queryData
  4108. data["success"] = ok
  4109. data["err_count"] = error
  4110. appG.Response(http.StatusOK, e.SUCCESS, data)
  4111. }
  4112. type upFpdetail struct {
  4113. Old float64
  4114. New float64
  4115. Times int64
  4116. Ptid int64
  4117. Fweight float64
  4118. Id int64
  4119. // Ptsid string
  4120. }
  4121. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4122. tx := restful.Engine.NewSession()
  4123. defer tx.Close()
  4124. tx.Begin()
  4125. for _, data := range dataList {
  4126. fttype := -1
  4127. if data.Ptid != -1 {
  4128. fttype = 1
  4129. }
  4130. var fweight float64
  4131. var lweight float64
  4132. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4133. err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4134. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4135. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4136. data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4137. if err != nil {
  4138. tx.Rollback()
  4139. logs.Error(err)
  4140. return err
  4141. }
  4142. weight := data.Fweight
  4143. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4144. var w float64
  4145. var status int
  4146. if data.New < data.Old {
  4147. if weight >= 0 {
  4148. continue
  4149. }
  4150. w = weight
  4151. status = 0
  4152. } else {
  4153. // if weight-(data.New-data.Old) > 0 {
  4154. // continue
  4155. // }
  4156. w = data.New - data.Old
  4157. status = 1
  4158. }
  4159. for _, lppland := range lpplandtl1List {
  4160. var lppdata lpplandtlInfo
  4161. tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4162. lppland.Lppid, pastureid).GetFirst(&lppdata)
  4163. if err != nil {
  4164. tx.Rollback()
  4165. logs.Error(err)
  4166. return err
  4167. }
  4168. lweight = lppdata.Lweight
  4169. if status == 1 {
  4170. // if w <= lppland.Lweight {
  4171. if lppland.Maxweight <= lweight {
  4172. continue
  4173. }
  4174. if w+lweight <= lppland.Maxweight {
  4175. lppland.Lweight += w
  4176. lweight += w
  4177. fweight += w
  4178. w = 0
  4179. } else {
  4180. w = w - (lppland.Maxweight - lweight)
  4181. n := (lppland.Maxweight - lweight)
  4182. lppland.Lweight = lppland.Lweight + n
  4183. lweight += n
  4184. fweight += n
  4185. }
  4186. } else {
  4187. if lppland.Lweight == 0 {
  4188. continue
  4189. }
  4190. if w+lppland.Lweight >= 0 {
  4191. lppland.Lweight = lppland.Lweight + w
  4192. lweight = lweight + w
  4193. fweight = fweight + w
  4194. w = 0
  4195. } else {
  4196. w = w + lppland.Lweight
  4197. lweight = lweight - lppland.Lweight
  4198. fweight = fweight - lppland.Lweight
  4199. lppland.Lweight = 0
  4200. }
  4201. }
  4202. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4203. if err != nil {
  4204. tx.Rollback()
  4205. logs.Error(err)
  4206. return err
  4207. }
  4208. break
  4209. }
  4210. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4211. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4212. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4213. if err != nil {
  4214. tx.Rollback()
  4215. logs.Error(err)
  4216. return err
  4217. }
  4218. // if w == 0 {
  4219. // break
  4220. // }
  4221. // }
  4222. }
  4223. err := tx.Commit()
  4224. if err != nil {
  4225. logs.Error(err)
  4226. tx.Rollback()
  4227. return err
  4228. }
  4229. now := time.Now()
  4230. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4231. if err != nil {
  4232. logs.Error(err)
  4233. return nil
  4234. }
  4235. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4236. if err != nil {
  4237. logs.Error(err)
  4238. return nil
  4239. }
  4240. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4241. if err != nil {
  4242. logs.Error(err)
  4243. return nil
  4244. }
  4245. for _, newLpplandtl1 := range newLpplandtl1List {
  4246. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4247. background,cowcount,ccountradio,lweighthis,createdate)
  4248. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4249. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4250. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4251. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4252. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4253. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4254. if err != nil {
  4255. logs.Error(err)
  4256. // appG.Response(http.StatusOK, e.ERROR, false)
  4257. return nil
  4258. }
  4259. }
  4260. for _, newFpd := range newFpdDataList {
  4261. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4262. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4263. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4264. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4265. if err != nil {
  4266. logs.Error(err)
  4267. // appG.Response(http.StatusOK, e.ERROR, false)
  4268. return nil
  4269. }
  4270. }
  4271. for _, newFeedp := range newFeedpList {
  4272. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4273. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4274. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4275. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4276. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4277. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4278. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4279. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4280. if err != nil {
  4281. logs.Error(err)
  4282. // appG.Response(http.StatusOK, e.ERROR, false)
  4283. return nil
  4284. }
  4285. }
  4286. return nil
  4287. }
  4288. func DeleteFTdetail(c *gin.Context) {
  4289. appG := app.Gin{C: c}
  4290. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4291. fsion := gofasion.NewFasion(string(dataByte))
  4292. parammaps := fsion.Get("parammaps")
  4293. pastureid := parammaps.Get("pastureid").ValueStr()
  4294. ftid := parammaps.Get("ftid").ValueStr()
  4295. tx := restful.Engine.NewSession()
  4296. defer tx.Close()
  4297. tx.Begin()
  4298. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4299. if err != nil {
  4300. tx.Rollback()
  4301. logs.Error(err)
  4302. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4303. return
  4304. }
  4305. if parammaps.Get("type").ValueStr() == "1" {
  4306. _, err := tx.SQL(`UPDATE feedp fp
  4307. set
  4308. fp.ftweight= IFNULL(IF(
  4309. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4310. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4311. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4312. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4313. ),0),fp.feedweight = IFNULL(IF(
  4314. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4315. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4316. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4317. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4318. ),0) +ifnull(fp.supplyweight,0)
  4319. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4320. if err != nil {
  4321. tx.Rollback()
  4322. logs.Error(err)
  4323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4324. return
  4325. }
  4326. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4327. _, err = tx.SQL(`
  4328. UPDATE fpdetail fpd
  4329. INNER JOIN feedp fp
  4330. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4331. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4332. ptuse= 0
  4333. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4334. if err != nil {
  4335. tx.Rollback()
  4336. logs.Error(err)
  4337. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4338. return
  4339. }
  4340. } else {
  4341. _, err := tx.SQL(`UPDATE feedp fp
  4342. SET
  4343. fp.supplyweight= IFNULL(IF(
  4344. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4345. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4346. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4347. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4348. ),0),fp.feedweight = IFNULL(IF(
  4349. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4350. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4351. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4352. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4353. ),0) + ifnull(fp.supplyweight,0)
  4354. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4355. if err != nil {
  4356. tx.Rollback()
  4357. logs.Error(err)
  4358. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4359. return
  4360. }
  4361. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4362. _, err = tx.SQL(`
  4363. UPDATE fpdetail fpd
  4364. INNER JOIN feedp fp
  4365. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4366. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4367. ptsrate = 0
  4368. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4369. if err != nil {
  4370. tx.Rollback()
  4371. logs.Error(err)
  4372. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4373. return
  4374. }
  4375. }
  4376. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4377. if err != nil {
  4378. tx.Rollback()
  4379. logs.Error(err)
  4380. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4381. return
  4382. }
  4383. err = tx.Commit()
  4384. if err != nil {
  4385. tx.Rollback()
  4386. logs.Error(err)
  4387. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4388. return
  4389. }
  4390. appG.Response(http.StatusOK, e.SUCCESS, true)
  4391. }
  4392. func DeleteSpillageAll(c *gin.Context) {
  4393. appG := app.Gin{C: c}
  4394. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4395. fsion := gofasion.NewFasion(string(dataByte))
  4396. parammaps := fsion.Get("parammaps")
  4397. pastureid := parammaps.Get("pastureid").ValueStr()
  4398. times := parammaps.Get("times").ValueStr()
  4399. tx := restful.Engine.NewSession()
  4400. defer tx.Close()
  4401. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4402. if err != nil {
  4403. logs.Error(err)
  4404. appG.Response(http.StatusOK, e.ERROR, false)
  4405. return
  4406. }
  4407. now := time.Now()
  4408. for _, item := range lpplandtl1List {
  4409. go func(item map[string]interface{}) {
  4410. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4411. background,cowcount,ccountradio,lweighthis,createdate)
  4412. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4413. item["pastureid"], item["lppid"], item["barid"],
  4414. item["barname"], item["fpdid"], item["fttype"],
  4415. item["lweight"], item["sort"], item["tmrid"],
  4416. item["tmrname"], item["background"], item["cowcount"],
  4417. item["ccountradio"], item["lweighthis"], now).Execute()
  4418. if err != nil {
  4419. logs.Error(err)
  4420. appG.Response(http.StatusOK, e.ERROR, false)
  4421. return
  4422. }
  4423. }(item)
  4424. }
  4425. tx.Begin()
  4426. _, err = tx.SQL(` delete from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ?) `, pastureid, pastureid, times).Execute()
  4427. if err != nil {
  4428. tx.Rollback()
  4429. logs.Error(err)
  4430. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4431. return
  4432. }
  4433. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4434. WHERE pastureid=? and times = ? `, pastureid, times).Execute()
  4435. if err != nil {
  4436. tx.Rollback()
  4437. logs.Error(err)
  4438. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4439. return
  4440. }
  4441. err = tx.Commit()
  4442. if err != nil {
  4443. tx.Rollback()
  4444. logs.Error(err)
  4445. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4446. return
  4447. }
  4448. appG.Response(http.StatusOK, e.SUCCESS, true)
  4449. }
  4450. func GetTMRListEnableTypeAll(c *gin.Context) {
  4451. appG := app.Gin{C: c}
  4452. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4453. fsion := gofasion.NewFasion(string(dataByte))
  4454. parammaps := fsion.Get("parammaps")
  4455. pastureid := parammaps.Get("pastureid").ValueStr()
  4456. tx := restful.Engine.NewSession()
  4457. defer tx.Close()
  4458. dataList, err := tx.SQL(`SELECT
  4459. eqcode,
  4460. tname,
  4461. datacaptureno,
  4462. trim(tclassid) tclassid,
  4463. concat(tname,' / ',eqcode) tmrmix,
  4464. d.label tclassname,
  4465. maxstirfeed,
  4466. remark,
  4467. tmr.enable,
  4468. TRIM(tmr.id) id,
  4469. TRIM(tmr.pastureid)pastureid
  4470. FROM
  4471. tmr
  4472. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4473. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4474. ORDER BY id DESC`, pastureid).Query().List()
  4475. if err != nil {
  4476. logs.Error(err)
  4477. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4478. return
  4479. }
  4480. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4481. if err != nil {
  4482. logs.Error(err)
  4483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4484. return
  4485. }
  4486. var carNum int64
  4487. for _, sysopt := range sysoptData {
  4488. if sysopt["inforvalue"] == nil {
  4489. carNum = 1
  4490. } else {
  4491. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4492. }
  4493. }
  4494. id := 200
  4495. n := 0
  4496. for i := carNum; i > 0; i-- {
  4497. id++
  4498. n++
  4499. data := make(map[string]interface{}, 0)
  4500. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4501. data["tname"] = fmt.Sprintf("任意车%d", n)
  4502. data["datacaptureno"] = -2
  4503. data["tclassid"] = -2
  4504. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4505. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4506. data["maxstirfeed"] = 100000
  4507. data["remark"] = fmt.Sprintf("任意车%d", n)
  4508. data["enable"] = 1
  4509. data["id"] = fmt.Sprintf("%d", id)
  4510. data["pastureid"] = pastureid
  4511. dataList = append(dataList, data)
  4512. }
  4513. // UNION ALL
  4514. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4515. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4516. }
  4517. func GetFeedpHistory(c *gin.Context) {
  4518. appG := app.Gin{C: c}
  4519. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4520. fsion := gofasion.NewFasion(string(dataByte))
  4521. // parammaps := fsion.Get("parammaps")
  4522. bar := fsion.Get("barname").ValueStr()
  4523. startDate := fsion.Get("startDate").ValueStr()
  4524. endDate := fsion.Get("endDate").ValueStr()
  4525. tx := restful.Engine.NewSession()
  4526. defer tx.Close()
  4527. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4528. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4529. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4530. if err != nil {
  4531. logs.Error(err)
  4532. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4533. return
  4534. }
  4535. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from fpdetailhistory where barname = ?
  4536. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4537. if err != nil {
  4538. logs.Error(err)
  4539. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4540. return
  4541. }
  4542. for _, feedp := range feedpList {
  4543. // LastftList, err := tx.SQL(` select tname ,id
  4544. // from feedtemplethistory where id = ?
  4545. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4546. // if err != nil {
  4547. // logs.Error(err)
  4548. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4549. // return
  4550. // }
  4551. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4552. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4553. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4554. if err != nil {
  4555. logs.Error(err)
  4556. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4557. return
  4558. }
  4559. var ftname interface{}
  4560. ftnamestatus := 0
  4561. ftname = feedp["ftname"]
  4562. var lastftid int64
  4563. if len(nextfeedpList) > 0 {
  4564. for _, ft := range nextfeedpList {
  4565. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4566. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4567. lastftid = ft["ftid"].(int64)
  4568. ftnamestatus = 1
  4569. break
  4570. }
  4571. }
  4572. }
  4573. for i, fpd := range fpdList {
  4574. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4575. fpd["weightstatus"] = 0
  4576. fpd["tratiostatus"] = 0
  4577. fpd["ftnamestatus"] = ftnamestatus
  4578. for k, fpd2 := range fpdList {
  4579. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4580. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4581. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4582. fpd["weightstatus"] = 1
  4583. }
  4584. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4585. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4586. fpd["tratiostatus"] = 1
  4587. }
  4588. break
  4589. }
  4590. }
  4591. fpd["barid"] = feedp["barid"]
  4592. fpd["barname"] = feedp["barname"]
  4593. fpd["ccount"] = feedp["ccount"]
  4594. fpd["ratio"] = feedp["ratio"]
  4595. fpd["ccountratio"] = feedp["ccountratio"]
  4596. fpd["ftid"] = feedp["ftid"]
  4597. fpd["ftname"] = ftname
  4598. fpd["ccountstatus"] = 0
  4599. fpd["ccountratiostatus"] = 0
  4600. fpd["ratiostatus"] = 0
  4601. fpd["ftnamestatus"] = 0
  4602. fpd["lastftid"] = lastftid
  4603. for _, next := range nextfeedpList {
  4604. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4605. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4606. fpd["ccountstatus"] = 1
  4607. }
  4608. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4609. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4610. fpd["ccountratiostatus"] = 1
  4611. }
  4612. if next["ratio"].(string) != fpd["ratio"].(string) {
  4613. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4614. fpd["ratiostatus"] = 1
  4615. }
  4616. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4617. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4618. // fpd["ftnamestatus"] = 1
  4619. // }
  4620. }
  4621. }
  4622. }
  4623. }
  4624. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4625. }
  4626. // func GetLpplandtl1History(c *gin.Context) {
  4627. // appG := app.Gin{C: c}
  4628. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4629. // fsion := gofasion.NewFasion(string(dataByte))
  4630. // // parammaps := fsion.Get("parammaps")
  4631. // barid := fsion.Get("barid").ValueStr()
  4632. // startDate := fsion.Get("startDate").ValueStr()
  4633. // endDate := fsion.Get("endDate").ValueStr()
  4634. // tx := restful.Engine.NewSession()
  4635. // defer tx.Close()
  4636. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4637. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4638. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4639. // // if err != nil {
  4640. // // logs.Error(err)
  4641. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4642. // // return
  4643. // // }
  4644. // // for _, feedp := range feedpList {
  4645. // // fmt.Println(feedp)
  4646. // // for i, fpd := range fpdList {
  4647. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4648. // // for k, fpd2 := range fpdList {
  4649. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4650. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4651. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4652. // // }
  4653. // // break
  4654. // // }
  4655. // // }
  4656. // // fpd["barid"] = feedp["barid"]
  4657. // // fpd["barname"] = feedp["barname"]
  4658. // // fpd["ccount"] = feedp["ccount"]
  4659. // // fpd["ratio"] = feedp["ratio"]
  4660. // // fpd["ccountratio"] = feedp["ccountratio"]
  4661. // // fpd["ftid"] = feedp["ftid"]
  4662. // // fpd["ftname"] = feedp["ftname"]
  4663. // // }
  4664. // // }
  4665. // // }
  4666. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4667. // }
  4668. func GetRemind(c *gin.Context) {
  4669. appG := app.Gin{C: c}
  4670. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4671. fsion := gofasion.NewFasion(string(dataByte))
  4672. parammaps := fsion.Get("parammaps")
  4673. pastureid := parammaps.Get("pastureid").ValueStr()
  4674. tx := restful.Engine.NewSession()
  4675. defer tx.Close()
  4676. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4677. if err != nil {
  4678. logs.Error(err)
  4679. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4680. return
  4681. }
  4682. // pastureid = "3"
  4683. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  4684. if err != nil {
  4685. logs.Error(err)
  4686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4687. return
  4688. }
  4689. defer resp.Body.Close()
  4690. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4691. buf.ReadFrom(resp.Body)
  4692. fmt.Println(string(buf.Bytes()))
  4693. respMap := make(map[string]interface{}, 0)
  4694. err = json.Unmarshal(buf.Bytes(), &respMap)
  4695. if err != nil {
  4696. logs.Error(err)
  4697. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4698. return
  4699. }
  4700. for _, data := range dataList {
  4701. r := make(map[string]interface{}, 0)
  4702. r["sys_name"] = ""
  4703. r["service_id"] = ""
  4704. r["pasture_id"] = ""
  4705. r["type_name"] = ""
  4706. r["remind_type_id"] = ""
  4707. r["remind_type"] = ""
  4708. r["push_date"] = ""
  4709. r["push_time"] = ""
  4710. r["interval_time"] = ""
  4711. r["push_limit"] = ""
  4712. r["template_id"] = ""
  4713. r["roles_id"] = ""
  4714. r["users_id"] = ""
  4715. r["date_type"] = ""
  4716. r["cycle_type"] = ""
  4717. data["data"] = r
  4718. for _, resp := range respMap["data"].([]interface{}) {
  4719. resp1 := resp.(map[string]interface{})
  4720. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  4721. if resp1["push_time"] == nil {
  4722. resp1["push_time"] = ""
  4723. }
  4724. data["data"] = resp1
  4725. break
  4726. }
  4727. }
  4728. }
  4729. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4730. }
  4731. type NoticeMsgtype struct {
  4732. SysName string `json:"sys_name"`
  4733. PastureId int64 `json:"pasture_id"`
  4734. ServiceId int64 `json:"service_id"`
  4735. TypeName string `json:"type_name"`
  4736. RemindType int64 `json:"remind_type"`
  4737. PushDate int64 `json:"push_date"`
  4738. PushTime string `json:"push_time"`
  4739. IntervalTime int64 `json:"interval_time"`
  4740. PushLimit int64 `json:"push_limit"`
  4741. TemplateId string `json:"template_id"`
  4742. UsersId string `json:"users_id"`
  4743. DateType int64 `json:"date_type"`
  4744. CycleType int64 `json:"cycle_type"`
  4745. DelayTime int64 `json:"delay_time"`
  4746. Status int64 `json:"status"`
  4747. }
  4748. func UpdateRemind(c *gin.Context) {
  4749. appG := app.Gin{C: c}
  4750. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4751. parammaps := gofasion.NewFasion(string(dataByte))
  4752. // parammaps := fsion.Get("parammaps")
  4753. // user := parammaps.Get("user").ValueStr()
  4754. id := parammaps.Get("id").ValueInt64()
  4755. noticeMsgtype := new(NoticeMsgtype)
  4756. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  4757. noticeMsgtype.ServiceId = id
  4758. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  4759. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  4760. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  4761. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  4762. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  4763. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  4764. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  4765. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  4766. noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  4767. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  4768. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  4769. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  4770. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  4771. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  4772. //TODO
  4773. noticeMsgtype.SysName = "tmrWatch_test"
  4774. userList := parammaps.Get("user").Array()
  4775. var userstr []string
  4776. for _, user := range userList {
  4777. userstr = append(userstr, user.ValueStr())
  4778. }
  4779. tx := restful.Engine.NewSession()
  4780. defer tx.Close()
  4781. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  4782. if err != nil {
  4783. logs.Error(err)
  4784. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4785. return
  4786. }
  4787. // var jsonStr = []byte(noticeMsgtype
  4788. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  4789. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  4790. req.Header.Set("Content-Type", "application/json")
  4791. client := &http.Client{}
  4792. resp, err := client.Do(req)
  4793. if err != nil {
  4794. logs.Error(err)
  4795. }
  4796. defer resp.Body.Close()
  4797. body, _ := ioutil.ReadAll(resp.Body)
  4798. fmt.Println("response Body:", string(body))
  4799. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch_test&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  4800. if err != nil {
  4801. logs.Error(err)
  4802. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4803. return
  4804. }
  4805. defer getresp.Body.Close()
  4806. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4807. buf.ReadFrom(getresp.Body)
  4808. fmt.Println(string(buf.Bytes()))
  4809. respMap := make(map[string]interface{}, 0)
  4810. err = json.Unmarshal(buf.Bytes(), &respMap)
  4811. if err != nil {
  4812. logs.Error(err)
  4813. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4814. return
  4815. }
  4816. for _, resp := range respMap["data"].([]interface{}) {
  4817. resp1 := resp.(map[string]interface{})
  4818. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  4819. if err != nil {
  4820. logs.Error(err)
  4821. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4822. return
  4823. }
  4824. }
  4825. appG.Response(http.StatusOK, e.SUCCESS, true)
  4826. }
  4827. func GetSpillageallHistory(c *gin.Context) {
  4828. appG := app.Gin{C: c}
  4829. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4830. parammaps := gofasion.NewFasion(string(dataByte))
  4831. barname := parammaps.Get("barname").ValueStr()
  4832. pastureid := parammaps.Get("pastureid").ValueStr()
  4833. startdate := parammaps.Get("startDate").ValueStr()
  4834. enddate := parammaps.Get("endDate").ValueStr()
  4835. tx := restful.Engine.NewSession()
  4836. defer tx.Close()
  4837. 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
  4838. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  4839. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  4840. if err != nil {
  4841. logs.Error(err)
  4842. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4843. return
  4844. }
  4845. respMap := make([]map[string]interface{}, 0)
  4846. data := make(map[interface{}]interface{})
  4847. for _, history := range historyList {
  4848. data[history["createdate"]] = history["createdate"]
  4849. }
  4850. createList := []string{}
  4851. for _, v := range data {
  4852. createList = append(createList, v.(string))
  4853. }
  4854. // sort.Sort()
  4855. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  4856. sort.Slice(createList, func(i, j int) bool {
  4857. return createList[i] > createList[j]
  4858. })
  4859. for _, v := range createList {
  4860. a := make(map[string]interface{})
  4861. a["createdate"] = data[v]
  4862. // createList = append(createList, v.(string))
  4863. respMap = append(respMap, a)
  4864. }
  4865. number := 0
  4866. dataMap := make([]interface{}, 0)
  4867. for k, resp := range respMap {
  4868. createdate := resp["createdate"].(string)
  4869. var nextcreatedate string
  4870. if len(respMap) > k+1 {
  4871. nextcreatedate = respMap[k+1]["createdate"].(string)
  4872. }
  4873. // dataList := make(map[string][]interface{})
  4874. // list := make(map[string]interface{})
  4875. times := make(map[interface{}]int)
  4876. for _, history := range historyList {
  4877. // List := make(map[interface{}][]interface{})
  4878. i := 0
  4879. if history["createdate"].(string) == createdate {
  4880. times[history["times"]]++
  4881. data := make(map[string]interface{})
  4882. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  4883. // exist := false
  4884. if nextcreatedate != "" {
  4885. for _, history1 := range historyList {
  4886. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  4887. history1["times"].(int64) == history["times"].(int64) {
  4888. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  4889. break
  4890. // exist = true
  4891. }
  4892. }
  4893. }
  4894. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  4895. i++
  4896. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  4897. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  4898. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  4899. // resp["times"] = history["times"]
  4900. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  4901. data1 := make(map[string]interface{})
  4902. data1["times"] = history["times"]
  4903. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  4904. data1["createdate"] = resp["createdate"]
  4905. // fmt.Println(dataList)
  4906. dataMap = append(dataMap, data1)
  4907. }
  4908. if i > number {
  4909. number = i
  4910. }
  4911. // respMap = append(respMap, dataList)
  4912. }
  4913. // for k, data := range dataList {
  4914. // resp[k] = data
  4915. // }
  4916. // resp["data"] = dataList
  4917. }
  4918. // resp := make(map[string]interface{})
  4919. // sort.Strings(createList)
  4920. //
  4921. // for _, create := range createList {
  4922. // for _, r := range respMap {
  4923. // if create == r["createdate"].(string) {
  4924. // resp[create] = r
  4925. // break
  4926. // }
  4927. // }
  4928. // }
  4929. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  4930. var trainsList []interface{}
  4931. for i := 0; i < number; i++ {
  4932. trains := make(map[string]interface{})
  4933. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  4934. trains["prop"] = fmt.Sprintf("a%d", i+1)
  4935. trainsList = append(trainsList, trains)
  4936. }
  4937. respdata := make(map[string]interface{})
  4938. respdata["data"] = dataMap
  4939. respdata["trains"] = trainsList
  4940. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  4941. }
  4942. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  4943. appG := app.Gin{C: c}
  4944. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4945. parammaps := gofasion.NewFasion(string(dataByte))
  4946. ftid := parammaps.Get("ftid").ValueInt64()
  4947. lastftid := parammaps.Get("lastftid").ValueInt64()
  4948. pastureid := parammaps.Get("pastureid").ValueInt64()
  4949. // createdate := parammaps.Get("createdate").ValueStr()
  4950. tx := restful.Engine.NewSession()
  4951. defer tx.Close()
  4952. data := make(map[string]interface{})
  4953. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  4954. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  4955. if err != nil {
  4956. logs.Error(err)
  4957. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4958. return
  4959. }
  4960. feedtemplet := make(map[string]interface{})
  4961. for _, f := range feedtempletList {
  4962. feedtemplet = f
  4963. }
  4964. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  4965. if err != nil {
  4966. logs.Error(err)
  4967. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4968. return
  4969. }
  4970. feedtemplet["fit"] = fitList
  4971. data["current"] = feedtemplet
  4972. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  4973. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  4974. if err != nil {
  4975. logs.Error(err)
  4976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4977. return
  4978. }
  4979. lastfeedtemplet := make(map[string]interface{})
  4980. for _, f := range lastfeedtempletList {
  4981. lastfeedtemplet = f
  4982. }
  4983. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  4984. if err != nil {
  4985. logs.Error(err)
  4986. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4987. return
  4988. }
  4989. lastfeedtemplet["fit"] = lastfitList
  4990. data["last"] = lastfeedtemplet
  4991. appG.Response(http.StatusOK, e.SUCCESS, data)
  4992. }
  4993. func GetFeedtempletHistory(c *gin.Context) {
  4994. appG := app.Gin{C: c}
  4995. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4996. parammaps := gofasion.NewFasion(string(dataByte))
  4997. ftid := parammaps.Get("ftid").ValueStr()
  4998. pastureid := parammaps.Get("pastureid").ValueInt64()
  4999. start := parammaps.Get("startdate").ValueStr()
  5000. end := parammaps.Get("enddate").ValueStr()
  5001. tx := restful.Engine.NewSession()
  5002. defer tx.Close()
  5003. ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1 from feedtemplethistory where createdate between ? and ?
  5004. and id = ? and pastureid = ? order by createdate desc `,
  5005. start, end, ftid, pastureid).Query().List()
  5006. if err != nil {
  5007. logs.Error(err)
  5008. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5009. return
  5010. }
  5011. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5012. ftid, pastureid).Query().List()
  5013. if err != nil {
  5014. logs.Error(err)
  5015. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5016. return
  5017. }
  5018. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5019. for i, ft := range ftList {
  5020. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5021. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5022. 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
  5023. where fit.fitid = ?
  5024. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5025. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5026. if err != nil {
  5027. logs.Error(err)
  5028. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5029. return
  5030. }
  5031. ft["createdate"] = ft["createdate1"]
  5032. // data["tname"] = ft["tname"]
  5033. // data["tcode"] = ft["tcode"]
  5034. // data["tcolor"] = ft["tcolor"]
  5035. // data["fttype"] = ft["fttype"]
  5036. // data["ccname"] = ft["ccname"]
  5037. // data["source"] = ft["source"]
  5038. // data["version"] = ft["version"]
  5039. // data["remark"] = ft["remark"]
  5040. for n, ft2 := range ftList {
  5041. if i < n {
  5042. if ft["tname"].(string) != ft2["tname"].(string) {
  5043. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5044. }
  5045. if _, ok := ft["tcode"]; ok {
  5046. if _, ok := ft2["tcode"]; ok {
  5047. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5048. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5049. }
  5050. }
  5051. }
  5052. if _, ok := ft["tcolor"]; ok {
  5053. if _, ok := ft2["tcolor"]; ok {
  5054. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5055. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5056. }
  5057. }
  5058. }
  5059. if _, ok := ft["fttype"]; ok {
  5060. if _, ok := ft2["fttype"]; ok {
  5061. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5062. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5063. }
  5064. }
  5065. }
  5066. if _, ok := ft["ccname"]; ok {
  5067. if _, ok := ft2["ccname"]; ok {
  5068. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5069. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5070. }
  5071. }
  5072. }
  5073. if _, ok := ft["source"]; ok {
  5074. if _, ok := ft2["source"]; ok {
  5075. if ft["source"].(string) != ft2["source"].(string) {
  5076. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5077. }
  5078. }
  5079. }
  5080. if _, ok := ft["version"]; ok {
  5081. if _, ok := ft2["version"]; ok {
  5082. if ft["version"].(int64) != ft2["version"].(int64) {
  5083. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5084. }
  5085. }
  5086. }
  5087. if _, ok := ft["remark"]; ok {
  5088. if _, ok := ft2["remark"]; ok {
  5089. if ft["remark"].(string) != ft2["remark"].(string) {
  5090. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5091. }
  5092. }
  5093. }
  5094. break
  5095. }
  5096. }
  5097. dataList := make([]map[string]interface{}, 0)
  5098. if len(fithisList) > 0 {
  5099. for _, fit := range fithisList {
  5100. data := make(map[string]interface{})
  5101. data["feedgroup"] = fit["feedgroup"]
  5102. data["fname"] = fit["fname"]
  5103. if fit["Eweight"] != nil {
  5104. if fit["Eweight"].(string) != fit["weight"].(string) {
  5105. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5106. } else {
  5107. data["fweight"] = fit["Eweight"]
  5108. }
  5109. data["fweightstatus"] = 1
  5110. } else {
  5111. data["fweight"] = fit["weight"]
  5112. data["fweightstatus"] = 0
  5113. }
  5114. data["autosecond"] = fit["autosecond"]
  5115. // data["tname"] = ft["tname"]
  5116. // data["tcode"] = ft["tcode"]
  5117. // data["tcolor"] = ft["tcolor"]
  5118. // data["fttype"] = ft["fttype"]
  5119. // data["ccname"] = ft["ccname"]
  5120. // data["source"] = ft["source"]
  5121. // data["version"] = ft["version"]
  5122. // data["remark"] = ft["remark"]
  5123. // data["createdate"] = ft["createdate1"]
  5124. // ft["fit"] = data
  5125. dataList = append(dataList, data)
  5126. }
  5127. } else {
  5128. for _, fit := range ftdetailList {
  5129. data := make(map[string]interface{})
  5130. data["feedgroup"] = fit["feedgroup"]
  5131. data["fname"] = fit["fname"]
  5132. // if fit["Eweight"] != nil {
  5133. // data["weight"] = fit["Eweight"]
  5134. // } else {
  5135. data["fweight"] = fit["fweight"]
  5136. // }
  5137. data["autosecond"] = fit["autosecond"]
  5138. // ft["fit"] = data
  5139. dataList = append(dataList, data)
  5140. }
  5141. }
  5142. ft["fit"] = dataList
  5143. }
  5144. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5145. }
  5146. func UpdateMaterialTMR(c *gin.Context) {
  5147. appG := app.Gin{C: c}
  5148. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5149. parammaps := gofasion.NewFasion(string(dataByte))
  5150. tmrid := parammaps.Get("tmrid").ValueStr()
  5151. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5152. lppid := parammaps.Get("lppid").ValueStr()
  5153. times := parammaps.Get("times").ValueStr()
  5154. pastureid := parammaps.Get("pastureid").ValueStr()
  5155. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5156. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5157. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5158. tx := restful.Engine.NewSession()
  5159. defer tx.Close()
  5160. tx.Begin()
  5161. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5162. if err != nil {
  5163. logs.Error(err)
  5164. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5165. return
  5166. }
  5167. var maxstirfeed float64
  5168. for _, tmr := range tmrList {
  5169. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5170. }
  5171. if status == 0 {
  5172. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5173. if err != nil {
  5174. tx.Rollback()
  5175. logs.Error(err)
  5176. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5177. return
  5178. }
  5179. var lweight float64
  5180. for _, item := range lpplandtl1List {
  5181. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5182. lweight += fl
  5183. }
  5184. if lweight > maxstirfeed {
  5185. lweight = lweight - maxstirfeed
  5186. } else {
  5187. lweight = 0
  5188. }
  5189. if lweight > 0 {
  5190. lweight1 := lweight / float64(len(lpplandtl1List))
  5191. number := 0
  5192. for _, item := range lpplandtl1List {
  5193. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5194. if lweight1 >= fl {
  5195. number++
  5196. }
  5197. }
  5198. lweight := lweight / float64((len(lpplandtl1List) - number))
  5199. for _, item := range lpplandtl1List {
  5200. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5201. if lweight1 >= fl {
  5202. continue
  5203. }
  5204. if tmrtype == "1" {
  5205. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5206. if err != nil {
  5207. tx.Rollback()
  5208. logs.Error(err)
  5209. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5210. return
  5211. }
  5212. } else if tmrtype == "2" {
  5213. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5214. if err != nil {
  5215. tx.Rollback()
  5216. logs.Error(err)
  5217. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5218. return
  5219. }
  5220. }
  5221. if item["fttype"].(int64) == 0 {
  5222. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5223. if err != nil {
  5224. tx.Rollback()
  5225. logs.Error(err)
  5226. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5227. return
  5228. }
  5229. } else {
  5230. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5231. if err != nil {
  5232. tx.Rollback()
  5233. logs.Error(err)
  5234. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5235. return
  5236. }
  5237. }
  5238. }
  5239. } else {
  5240. for _, item := range lpplandtl1List {
  5241. // 自走式
  5242. if tmrtype == "1" {
  5243. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5244. if err != nil {
  5245. logs.Error(err)
  5246. tx.Rollback()
  5247. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5248. return
  5249. }
  5250. } else if tmrtype == "2" {
  5251. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5252. if err != nil {
  5253. logs.Error(err)
  5254. tx.Rollback()
  5255. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5256. return
  5257. }
  5258. }
  5259. }
  5260. }
  5261. } else if status == 1 {
  5262. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5263. if err != nil {
  5264. logs.Error(err)
  5265. tx.Rollback()
  5266. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5267. return
  5268. }
  5269. var lweight float64
  5270. for _, item := range lpplandtl1List {
  5271. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5272. lweight += fl
  5273. }
  5274. if lweight > maxstirfeed {
  5275. lweight = lweight - maxstirfeed
  5276. } else {
  5277. lweight = 0
  5278. }
  5279. for _, item := range lpplandtl1List {
  5280. if lweight > 0 {
  5281. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5282. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5283. if fl >= lweight {
  5284. item["lweight"] = fl - lweight
  5285. lweight = 0
  5286. if tmrtype == "1" {
  5287. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5288. if err != nil {
  5289. logs.Error(err)
  5290. tx.Rollback()
  5291. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5292. return
  5293. }
  5294. } else if tmrtype == "2" {
  5295. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5296. if err != nil {
  5297. logs.Error(err)
  5298. tx.Rollback()
  5299. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5300. return
  5301. }
  5302. }
  5303. if item["fttype"].(int64) == 0 {
  5304. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5305. if err != nil {
  5306. logs.Error(err)
  5307. tx.Rollback()
  5308. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5309. return
  5310. }
  5311. } else {
  5312. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5313. if err != nil {
  5314. logs.Error(err)
  5315. tx.Rollback()
  5316. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5317. return
  5318. }
  5319. }
  5320. } else {
  5321. lweight = lweight - fl
  5322. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5323. if err != nil {
  5324. logs.Error(err)
  5325. tx.Rollback()
  5326. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5327. return
  5328. }
  5329. if item["fttype"].(int64) == 0 {
  5330. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5331. if err != nil {
  5332. logs.Error(err)
  5333. tx.Rollback()
  5334. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5335. return
  5336. }
  5337. } else {
  5338. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5339. if err != nil {
  5340. logs.Error(err)
  5341. tx.Rollback()
  5342. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5343. return
  5344. }
  5345. }
  5346. }
  5347. } else {
  5348. // 自走式
  5349. if tmrtype == "1" {
  5350. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5351. if err != nil {
  5352. logs.Error(err)
  5353. tx.Rollback()
  5354. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5355. return
  5356. }
  5357. } else if tmrtype == "2" {
  5358. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5359. if err != nil {
  5360. logs.Error(err)
  5361. tx.Rollback()
  5362. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5363. return
  5364. }
  5365. }
  5366. }
  5367. }
  5368. } else {
  5369. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5370. if err != nil {
  5371. logs.Error(err)
  5372. tx.Rollback()
  5373. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5374. return
  5375. }
  5376. for _, item := range lpplandtl1List {
  5377. if item["fttype"].(int64) == 0 {
  5378. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5379. if err != nil {
  5380. logs.Error(err)
  5381. tx.Rollback()
  5382. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5383. return
  5384. }
  5385. } else {
  5386. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5387. if err != nil {
  5388. logs.Error(err)
  5389. tx.Rollback()
  5390. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5391. return
  5392. }
  5393. }
  5394. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5395. if err != nil {
  5396. logs.Error(err)
  5397. tx.Rollback()
  5398. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5399. return
  5400. }
  5401. }
  5402. }
  5403. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5404. if err != nil {
  5405. logs.Error(err)
  5406. tx.Rollback()
  5407. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5408. return
  5409. }
  5410. err = tx.Commit()
  5411. if err != nil {
  5412. logs.Error(err)
  5413. tx.Rollback()
  5414. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5415. return
  5416. }
  5417. appG.Response(http.StatusOK, e.SUCCESS, true)
  5418. }
  5419. func UpdateMaterialTMRDate(c *gin.Context) {
  5420. appG := app.Gin{C: c}
  5421. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5422. parammaps := gofasion.NewFasion(string(dataByte))
  5423. tmrid := parammaps.Get("tmrid").ValueStr()
  5424. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5425. lppid := parammaps.Get("lppid").ValueStr()
  5426. times := parammaps.Get("times").ValueStr()
  5427. pastureid := parammaps.Get("pastureid").ValueStr()
  5428. date := parammaps.Get("date").ValueStr()
  5429. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5430. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5431. tx := restful.Engine.NewSession()
  5432. defer tx.Close()
  5433. tx.Begin()
  5434. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5435. if err != nil {
  5436. logs.Error(err)
  5437. tx.Rollback()
  5438. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5439. return
  5440. }
  5441. var maxstirfeed float64
  5442. for _, tmr := range tmrList {
  5443. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5444. }
  5445. if status == 0 {
  5446. 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()
  5447. if err != nil {
  5448. logs.Error(err)
  5449. tx.Rollback()
  5450. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5451. return
  5452. }
  5453. var lweight float64
  5454. for _, item := range lpplandtl1List {
  5455. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5456. lweight += fl
  5457. }
  5458. if lweight > maxstirfeed {
  5459. lweight = lweight - maxstirfeed
  5460. } else {
  5461. lweight = 0
  5462. }
  5463. if lweight > 0 {
  5464. lweight1 := lweight / float64(len(lpplandtl1List))
  5465. number := 0
  5466. for _, item := range lpplandtl1List {
  5467. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5468. if lweight1 >= fl {
  5469. number++
  5470. }
  5471. }
  5472. lweight := lweight / float64((len(lpplandtl1List) - number))
  5473. for _, item := range lpplandtl1List {
  5474. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5475. if lweight1 >= fl {
  5476. continue
  5477. }
  5478. if tmrtype == "1" {
  5479. _, 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()
  5480. if err != nil {
  5481. logs.Error(err)
  5482. tx.Rollback()
  5483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5484. return
  5485. }
  5486. } else if tmrtype == "2" {
  5487. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5488. if err != nil {
  5489. logs.Error(err)
  5490. tx.Rollback()
  5491. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5492. return
  5493. }
  5494. }
  5495. if item["fttype"].(int64) == 0 {
  5496. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5497. if err != nil {
  5498. logs.Error(err)
  5499. tx.Rollback()
  5500. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5501. return
  5502. }
  5503. } else {
  5504. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5505. if err != nil {
  5506. logs.Error(err)
  5507. tx.Rollback()
  5508. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5509. return
  5510. }
  5511. }
  5512. }
  5513. } else {
  5514. for _, item := range lpplandtl1List {
  5515. // 自走式
  5516. if tmrtype == "1" {
  5517. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5518. if err != nil {
  5519. logs.Error(err)
  5520. tx.Rollback()
  5521. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5522. return
  5523. }
  5524. } else if tmrtype == "2" {
  5525. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5526. if err != nil {
  5527. logs.Error(err)
  5528. tx.Rollback()
  5529. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5530. return
  5531. }
  5532. }
  5533. }
  5534. }
  5535. } else if status == 1 {
  5536. 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()
  5537. if err != nil {
  5538. logs.Error(err)
  5539. tx.Rollback()
  5540. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5541. return
  5542. }
  5543. var lweight float64
  5544. for _, item := range lpplandtl1List {
  5545. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5546. lweight += fl
  5547. }
  5548. if lweight > maxstirfeed {
  5549. lweight = lweight - maxstirfeed
  5550. } else {
  5551. lweight = 0
  5552. }
  5553. for _, item := range lpplandtl1List {
  5554. if lweight > 0 {
  5555. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5556. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5557. if fl >= lweight {
  5558. item["lweight"] = fl - lweight
  5559. lweight = 0
  5560. if tmrtype == "1" {
  5561. _, 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()
  5562. if err != nil {
  5563. logs.Error(err)
  5564. tx.Rollback()
  5565. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5566. return
  5567. }
  5568. } else if tmrtype == "2" {
  5569. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5570. if err != nil {
  5571. logs.Error(err)
  5572. tx.Rollback()
  5573. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5574. return
  5575. }
  5576. }
  5577. if item["fttype"].(int64) == 0 {
  5578. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5579. if err != nil {
  5580. logs.Error(err)
  5581. tx.Rollback()
  5582. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5583. return
  5584. }
  5585. } else {
  5586. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5587. if err != nil {
  5588. logs.Error(err)
  5589. tx.Rollback()
  5590. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5591. return
  5592. }
  5593. }
  5594. } else {
  5595. lweight = lweight - fl
  5596. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5597. if err != nil {
  5598. logs.Error(err)
  5599. tx.Rollback()
  5600. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5601. return
  5602. }
  5603. if item["fttype"].(int64) == 0 {
  5604. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5605. if err != nil {
  5606. logs.Error(err)
  5607. tx.Rollback()
  5608. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5609. return
  5610. }
  5611. } else {
  5612. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5613. if err != nil {
  5614. logs.Error(err)
  5615. tx.Rollback()
  5616. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5617. return
  5618. }
  5619. }
  5620. }
  5621. } else {
  5622. // 自走式
  5623. if tmrtype == "1" {
  5624. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5625. if err != nil {
  5626. logs.Error(err)
  5627. tx.Rollback()
  5628. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5629. return
  5630. }
  5631. } else if tmrtype == "2" {
  5632. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5633. if err != nil {
  5634. logs.Error(err)
  5635. tx.Rollback()
  5636. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5637. return
  5638. }
  5639. }
  5640. }
  5641. }
  5642. } else {
  5643. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  5644. if err != nil {
  5645. logs.Error(err)
  5646. tx.Rollback()
  5647. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5648. return
  5649. }
  5650. for _, item := range lpplandtl1List {
  5651. if item["fttype"].(int64) == 0 {
  5652. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5653. if err != nil {
  5654. logs.Error(err)
  5655. tx.Rollback()
  5656. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5657. return
  5658. }
  5659. } else {
  5660. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5661. if err != nil {
  5662. logs.Error(err)
  5663. tx.Rollback()
  5664. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5665. return
  5666. }
  5667. }
  5668. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5669. if err != nil {
  5670. logs.Error(err)
  5671. tx.Rollback()
  5672. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5673. return
  5674. }
  5675. }
  5676. }
  5677. _, 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()
  5678. if err != nil {
  5679. logs.Error(err)
  5680. tx.Rollback()
  5681. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5682. return
  5683. }
  5684. err = tx.Commit()
  5685. if err != nil {
  5686. logs.Error(err)
  5687. tx.Rollback()
  5688. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5689. return
  5690. }
  5691. appG.Response(http.StatusOK, e.SUCCESS, true)
  5692. }