ops.go 232 KB

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