ops.go 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776
  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. fmt.Println(paramvalue["name"])
  1376. if paramvalue["name"].(string) == "updateBigFP" {
  1377. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1378. if err != nil {
  1379. msg := geterrmsg(err.Error())
  1380. appG.Response(http.StatusOK, e.ERROR, msg)
  1381. return
  1382. }
  1383. }
  1384. }
  1385. for _, paramvalue := range tempval {
  1386. if _, ok := paramvalue["resultname"]; !ok {
  1387. paramvalue["resultname"] = paramvalue["name"]
  1388. }
  1389. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1390. if err != nil {
  1391. logging.Error("ExecDataParam error:", err)
  1392. break
  1393. }
  1394. }
  1395. if err == nil {
  1396. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1397. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1398. } else {
  1399. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1400. }
  1401. } else {
  1402. msg := geterrmsg(err.Error())
  1403. appG.Response(http.StatusOK, e.ERROR, msg)
  1404. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1405. }
  1406. }
  1407. }
  1408. if err != nil {
  1409. msg := geterrmsg(err.Error())
  1410. appG.Response(http.StatusOK, e.ERROR, msg)
  1411. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1412. }
  1413. }
  1414. func interfacetostring(val interface{}) string {
  1415. switch val.(type) {
  1416. case string:
  1417. ss := val.(string)
  1418. return ss
  1419. break
  1420. case int:
  1421. ss := val.(int)
  1422. return strconv.Itoa(ss)
  1423. break
  1424. case int64:
  1425. ss := val.(int64)
  1426. return strconv.FormatInt(ss, 10)
  1427. break
  1428. case float64:
  1429. ss := val.(float64)
  1430. return strconv.FormatFloat(ss, 'E', -1, 32)
  1431. break
  1432. }
  1433. return ""
  1434. }
  1435. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1436. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1437. tempstrb := strings.IndexAny(valuestring, "@")
  1438. tempstre := strings.IndexAny(valuestring, ".")
  1439. if tempstrb > -1 && tempstre > -1 {
  1440. for _, ParamMapList := range ParamMap {
  1441. if v, ok := ParamMapList["resultname"]; ok {
  1442. if v == valuestring[tempstrb+1:tempstre] {
  1443. if v1, ok := ParamMapList["resultmaps"]; ok {
  1444. if newA, ok := v1.([]map[string]interface{}); ok {
  1445. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1446. } else if newA, ok := v1.(map[string]interface{}); ok {
  1447. return interfacetostring(newA[valuestring[tempstre+1:]])
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. } else {
  1454. return valuestring
  1455. }
  1456. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1457. return strconv.FormatInt(int64(valuestring), 10)
  1458. }
  1459. return ""
  1460. }
  1461. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1462. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1463. tempstrb := strings.IndexAny(valuestring, "@")
  1464. tempstre := strings.IndexAny(valuestring, ".")
  1465. if tempstrb > -1 && tempstre > -1 {
  1466. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1467. if s, ok := v.(string); ok {
  1468. return s
  1469. } else if s, ok := v.(float64); ok {
  1470. return strconv.FormatFloat(s, 'f', -1, 64)
  1471. // return strconv.FormatInt(int64(s), 10)
  1472. }
  1473. }
  1474. }
  1475. }
  1476. return ""
  1477. }
  1478. 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) {
  1479. sqlname := fasion["name"].(string)
  1480. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1481. if v, ok := fasion["type"]; ok {
  1482. sqltype = v.(string)
  1483. }
  1484. sql := ""
  1485. p := ""
  1486. s_params := make([]interface{}, 0)
  1487. if sqltype != "" {
  1488. sql, p = restful.GetSqlByName(sqlname, tx)
  1489. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1490. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1491. paramslist := strings.Split(p, ",")
  1492. if len(paramslist) > 0 && p != "" {
  1493. for _, value := range paramslist {
  1494. ss := ""
  1495. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1496. ids, err := setting.SnowIds.NextId()
  1497. if err != nil {
  1498. ids = time.Now().UnixNano()
  1499. logging.Info("create SnowIds err", err)
  1500. }
  1501. s_params = append(s_params, ids)
  1502. } else {
  1503. if ss == "" && CommonParamMap != nil {
  1504. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1505. ss = valuestring
  1506. tempstrb := strings.IndexAny(valuestring, "@")
  1507. tempstre := strings.IndexAny(valuestring, ".")
  1508. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1509. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1510. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1511. }
  1512. } else {
  1513. ss = ""
  1514. }
  1515. }
  1516. }
  1517. if ss == "" && ParentParamMap != nil {
  1518. ss = getParamValue_(v, value, ParentParamMap)
  1519. }
  1520. if ss == "" && sameParamMap != nil {
  1521. ss = getParamValue(v, value, sameParamMap)
  1522. }
  1523. if ss == "" && ParamMap != nil {
  1524. ss = getParamValue(v, value, ParamMap)
  1525. }
  1526. s_params = append(s_params, ss)
  1527. }
  1528. }
  1529. }
  1530. }
  1531. }
  1532. if sql == "" {
  1533. sqltype = ""
  1534. }
  1535. if sqltype == "s1" {
  1536. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1537. if v, ok := tempValParam.(map[string]interface{}); ok {
  1538. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1539. }
  1540. if err != nil {
  1541. return nil, err
  1542. }
  1543. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1544. if err != nil {
  1545. return nil, err
  1546. }
  1547. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1548. } else if sqltype == "sm" {
  1549. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1550. if v, ok := tempValParam.(map[string]interface{}); ok {
  1551. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1552. } else {
  1553. }
  1554. if err != nil {
  1555. return nil, err
  1556. }
  1557. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1558. if err != nil {
  1559. return nil, err
  1560. }
  1561. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1562. } else if sqltype == "v" {
  1563. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1564. if v, ok := tempValParam.(map[string]interface{}); ok {
  1565. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1566. } else {
  1567. }
  1568. if err != nil {
  1569. return nil, err
  1570. }
  1571. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1572. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1573. }
  1574. } else if sqltype == "e" {
  1575. tempVal_arrary := make([]map[string]interface{}, 0)
  1576. tempVal_map := make(map[string]interface{})
  1577. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1578. if err == nil {
  1579. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1580. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1581. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1582. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1583. return tempVal_arrary, err
  1584. }
  1585. return nil, err
  1586. } else {
  1587. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1588. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1589. if err != nil {
  1590. return nil, err
  1591. }
  1592. return nil, err
  1593. }
  1594. }
  1595. return nil, nil
  1596. }
  1597. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1598. var err error
  1599. subarray, ok := fasion["children"]
  1600. if ok {
  1601. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1602. tempVal_arrary := make([]map[string]interface{}, 0)
  1603. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1604. tempVal_ := make(map[string]interface{})
  1605. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1606. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1607. } else {
  1608. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1609. }
  1610. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1611. if err != nil {
  1612. return err
  1613. }
  1614. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1615. }
  1616. v.(map[string]interface{})["children"] = tempVal_arrary
  1617. }
  1618. }
  1619. return nil
  1620. }
  1621. // @Summary 删除图片
  1622. // @Tags RemovePicByName
  1623. // @Accept json
  1624. // @Produce json
  1625. // @Param sqlname query string true "sqlname"
  1626. // @Param offset query int true "offset"
  1627. // @Param pagecount query int true "pagecount"
  1628. // @Param returntype query string true "returntype"
  1629. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1630. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1631. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1632. // @Router /data/PostDataByName [POST]
  1633. func RemovePicByName(c *gin.Context) {
  1634. logging.Info("RemovePicByName ", c.Keys)
  1635. appG := app.Gin{C: c}
  1636. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1637. fsion := gofasion.NewFasion(string(dataByte))
  1638. sqlnamestr := fsion.Get("name").ValueStr()
  1639. picname := fsion.Get("picname").ValueStr()
  1640. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1641. params := fsion.Get("params").Array()
  1642. s_params := make([]interface{}, 0)
  1643. for _, v_params := range params {
  1644. s_params = append(s_params, v_params.ValueStr())
  1645. }
  1646. if sql != "" {
  1647. queryData, err := execDataBySql(sql, s_params)
  1648. if picname != "" {
  1649. // Destination
  1650. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, 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. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1662. err = os.Remove(distPath) //删除文件test.txt
  1663. if err != nil {
  1664. //如果删除失败则输出 file remove Error!
  1665. fmt.Println("file remove Error!")
  1666. //输出错误详细信息
  1667. fmt.Printf("%s", err)
  1668. } else {
  1669. //如果删除成功则输出 file remove OK!
  1670. fmt.Print("file remove OK!")
  1671. }
  1672. }
  1673. if err != nil {
  1674. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1675. } else {
  1676. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1677. }
  1678. } else {
  1679. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1680. }
  1681. }
  1682. // @Summary 删除文件
  1683. // @Tags RemoveFileByName
  1684. // @Accept json
  1685. // @Produce json
  1686. // @Param sqlname query string true "sqlname"
  1687. // @Param offset query int true "offset"
  1688. // @Param pagecount query int true "pagecount"
  1689. // @Param returntype query string true "returntype"
  1690. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1691. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1692. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1693. // @Router /data/PostDataByName [POST]
  1694. func RemoveFileByName(c *gin.Context) {
  1695. appG := app.Gin{C: c}
  1696. id := c.Param("id")
  1697. logging.Info("DownloadFile ", c.Keys, id)
  1698. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1699. if eqdoc == nil {
  1700. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1701. return
  1702. }
  1703. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1704. err = os.Remove(distPath) //删除文件test.txt
  1705. if err != nil {
  1706. //如果删除失败则输出 file remove Error!
  1707. fmt.Println("file remove Error!")
  1708. //输出错误详细信息
  1709. fmt.Printf("%s", err)
  1710. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1711. return
  1712. }
  1713. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1714. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1715. }
  1716. // @Summary 根据APISQL表中SQL执行得到数据集
  1717. // @Tags PostDataByName
  1718. // @Accept json
  1719. // @Produce json
  1720. // @Param sqlname query string true "sqlname"
  1721. // @Param offset query int true "offset"
  1722. // @Param pagecount query int true "pagecount"
  1723. // @Param returntype query string true "returntype"
  1724. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1725. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1726. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1727. // @Router /data/PostDataByName [POST]
  1728. func UpdateDataRelation(c *gin.Context) {
  1729. appG := app.Gin{C: c}
  1730. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1731. fsion := gofasion.NewFasion(string(dataByte))
  1732. tablename := fsion.Get("name").ValueStr()
  1733. dataname := fsion.Get("dataname").ValueStr()
  1734. datavalue := fsion.Get("datavalue").ValueStr()
  1735. valuename := fsion.Get("valuename").ValueStr()
  1736. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1737. values := fsion.Get("values").Array()
  1738. tx := restful.Engine.NewSession()
  1739. err := tx.Begin()
  1740. defer func() {
  1741. switch {
  1742. case err != nil:
  1743. if tx != nil {
  1744. tx.Rollback()
  1745. }
  1746. default:
  1747. if tx != nil {
  1748. err = tx.Commit()
  1749. }
  1750. }
  1751. if tx != nil {
  1752. tx.Close()
  1753. }
  1754. }()
  1755. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1756. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1757. d_params := make([]interface{}, 4)
  1758. d_params[0] = datavalue
  1759. s_params := ""
  1760. for _, v_values := range values {
  1761. d_params[1] = v_values.ValueStr()
  1762. if s_params == "" {
  1763. s_params = v_values.ValueStr()
  1764. } else {
  1765. s_params = s_params + "," + v_values.ValueStr()
  1766. }
  1767. d_params[2] = d_params[1]
  1768. d_params[3] = d_params[0]
  1769. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1770. if err != nil {
  1771. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1772. break
  1773. }
  1774. }
  1775. if s_params != "" {
  1776. deleteSqlstr := "delete from " + tablename + " " +
  1777. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1778. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1779. if err != nil {
  1780. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1781. } else if err == nil {
  1782. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1783. }
  1784. } else {
  1785. deleteSqlstr := "delete from " + tablename + " " +
  1786. " where " + dataname + " = " + datavalue
  1787. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1788. if err != nil {
  1789. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1790. } else if err == nil {
  1791. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1792. }
  1793. }
  1794. }
  1795. // @Summary 根据APISQL表中SQL执行得到数据集
  1796. // @Tags PostDatasByName
  1797. // @Accept json
  1798. // @Produce json
  1799. // @Param sqlname query string true "sqlname"
  1800. // @Param offset query int true "offset"
  1801. // @Param pagecount query int true "pagecount"
  1802. // @Param returntype query string true "returntype"
  1803. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1804. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1805. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1806. // @Router /data/PostDatasByName [POST]
  1807. func PostDataByNames(c *gin.Context) {
  1808. appG := app.Gin{C: c}
  1809. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1810. fsion := gofasion.NewFasion(string(dataByte))
  1811. sqlParams := fsion.Get("array").Array()
  1812. queryData := make(map[string]interface{})
  1813. for _, v := range sqlParams {
  1814. fsion2 := gofasion.NewFasion(v.Json())
  1815. ss := fsion2.Get("name")
  1816. aa := fsion2.Get("params")
  1817. fmt.Println(ss, aa)
  1818. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1819. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1820. if sql == "" {
  1821. errorm := make(map[string]interface{})
  1822. errorm["code"] = e.ERROR
  1823. errorm["message"] = "sql没有找到"
  1824. errorm["param"] = ""
  1825. queryData[fsion2.Get("name").ValueStr()] = errorm
  1826. continue
  1827. } else if sql != "" {
  1828. s_params := make([]interface{}, 0)
  1829. if fsion2.HasKey("parammaps") {
  1830. parammaps := fsion2.Get("parammaps")
  1831. paramslist := strings.Split(p, ",")
  1832. if len(paramslist) > 0 && p != "" {
  1833. for _, value := range paramslist {
  1834. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1835. if tempv, exists := c.Get("jwt_username"); exists {
  1836. s_params = append(s_params, tempv.(string))
  1837. } else {
  1838. s_params = append(s_params, "")
  1839. }
  1840. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1841. ids, err := setting.SnowIds.NextId()
  1842. if err != nil {
  1843. ids = time.Now().UnixNano()
  1844. logging.Info("create SnowIds err", err)
  1845. }
  1846. s_params = append(s_params, ids)
  1847. } else {
  1848. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1849. }
  1850. }
  1851. }
  1852. } else if fsion2.HasKey("params") {
  1853. params := fsion2.Get("params").Array()
  1854. //ids,err := setting.SnowIds.NextId()
  1855. //if err !=nil{
  1856. // ids = time.Now().UnixNano()
  1857. // logging.Info("create SnowIds err",err)
  1858. //}
  1859. //s_params = append(s_params, ids)
  1860. for _, v_params := range params {
  1861. s_params = append(s_params, v_params.ValueStr())
  1862. }
  1863. }
  1864. _, err := execDataBySql(sql, s_params)
  1865. if err != nil {
  1866. logging.Error("PostDataByName err: ", err)
  1867. errorm := make(map[string]interface{})
  1868. errorm["code"] = e.ERROR
  1869. errorm["message"] = err.Error()
  1870. errorm["param"] = s_params
  1871. queryData[fsion2.Get("name").ValueStr()] = errorm
  1872. continue
  1873. } else {
  1874. errorm := make(map[string]interface{})
  1875. errorm["code"] = e.SUCCESS
  1876. errorm["message"] = "success"
  1877. queryData[fsion2.Get("name").ValueStr()] = errorm
  1878. continue
  1879. }
  1880. } else {
  1881. errorm := make(map[string]interface{})
  1882. errorm["code"] = e.ERROR
  1883. errorm["message"] = "NO SQL"
  1884. errorm["param"] = ""
  1885. queryData[fsion2.Get("name").ValueStr()] = errorm
  1886. }
  1887. }
  1888. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1889. }
  1890. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1891. if offset > 0 {
  1892. offset = offset - 1
  1893. }
  1894. //if pagecount == 0 {
  1895. // pagecount = setting.AppSetting.PageSize
  1896. //}else if pagecount>setting.AppSetting.PageSize{
  1897. // pagecount = setting.AppSetting.PageSize
  1898. //}
  1899. if returntype == "list" {
  1900. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1901. return queryData, err
  1902. } else if returntype == "listlist" {
  1903. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1904. return queryData, err
  1905. } else {
  1906. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1907. return queryData, err
  1908. }
  1909. }
  1910. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1911. if offset > 0 {
  1912. offset = offset - 1
  1913. }
  1914. //if pagecount == 0 {
  1915. // pagecount = setting.AppSetting.PageSize
  1916. //}else if pagecount>setting.AppSetting.PageSize{
  1917. // pagecount = setting.AppSetting.PageSize
  1918. //}
  1919. if returntype == "list" {
  1920. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1921. return queryData, err
  1922. } else if returntype == "listlist" {
  1923. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1924. return queryData, err
  1925. } else {
  1926. fmt.Println(params)
  1927. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1928. return queryData, err
  1929. }
  1930. }
  1931. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1932. paramslist := strings.Split(Params, ",")
  1933. s_params := make([]interface{}, 0)
  1934. if isList {
  1935. for _, v_params := range thisParams["params"].([]interface{}) {
  1936. s_params = append(s_params, v_params)
  1937. }
  1938. } else {
  1939. paramslist := strings.Split(Params, ",")
  1940. if len(paramslist) > 0 && Params != "" {
  1941. for _, value := range paramslist {
  1942. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1943. }
  1944. }
  1945. }
  1946. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1947. for _, queryData_ := range queryData {
  1948. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1949. if isList {
  1950. if queryData_[idname] != nil {
  1951. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1952. }
  1953. } else {
  1954. if queryData_[idname] != nil {
  1955. thisParams[idname] = queryData_[idname].(interface{})
  1956. }
  1957. if len(paramslist) > 0 && Params != "" {
  1958. s_params = make([]interface{}, 0)
  1959. for _, value := range paramslist {
  1960. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1961. }
  1962. }
  1963. }
  1964. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1965. } else {
  1966. }
  1967. }
  1968. return queryData, err
  1969. }
  1970. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1971. queryData, err := restful.ExecQuery(sqlstr, params)
  1972. return queryData, err
  1973. }
  1974. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1975. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1976. return queryData, err
  1977. }
  1978. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1979. queryData, err := restful.ExecQuery(sqlstr, params)
  1980. return queryData, err
  1981. }
  1982. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1983. // @Tags ImportExcel
  1984. // @Accept json
  1985. // @Produce json
  1986. // @Param file query string true "文件名"
  1987. // @Param name header string true "执行sql的名字"
  1988. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1989. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1990. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1991. // @Router /data/ImportExcel [POST]
  1992. func ImportExcel(c *gin.Context) {
  1993. appG := app.Gin{C: c}
  1994. inputdata := ""
  1995. c.Request.ParseForm()
  1996. params := c.Request.Form
  1997. file, _, err := c.Request.FormFile("file")
  1998. if err != nil {
  1999. appG.Response(http.StatusOK, e.ERROR, err)
  2000. return
  2001. }
  2002. sqlnamestrs := params.Get("name")
  2003. sheetname := params.Get("sheetname")
  2004. pastureid := params.Get("pastureid")
  2005. //importParams := params.Get("importParams")
  2006. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2007. // 必输项参数 (字符串格式 "field1,field2,field3")
  2008. requiredParams := params.Get("requiredParams")
  2009. // 日期参数
  2010. dateParams := params.Get("dateParams")
  2011. // 数字参数
  2012. numParams := params.Get("numParams")
  2013. //将字符串分割开
  2014. dateParamslist := strings.Split(dateParams, ",")
  2015. requiredParamslist := strings.Split(requiredParams, ",")
  2016. numParamslist := strings.Split(numParams, ",")
  2017. queryData := make([]interface{}, 0)
  2018. sqlslist := strings.Split(sqlnamestrs, ",")
  2019. xlsx1, err := excelize.OpenReader(file)
  2020. if err != nil {
  2021. fmt.Println(err)
  2022. return
  2023. }
  2024. ok := 0
  2025. error := 0
  2026. isdone := true
  2027. rows := xlsx1.GetRows(sheetname)
  2028. // 限制10000条,多余的截取掉
  2029. if len(rows) > 10000 {
  2030. rows = rows[:10000]
  2031. }
  2032. for i, row := range rows {
  2033. if i > 0 {
  2034. entry := make(map[string]interface{})
  2035. outentry := make(map[string]interface{})
  2036. for j, colCell := range rows[0] {
  2037. for k, colCell1 := range row {
  2038. if j == k {
  2039. outentry[colCell] = colCell1
  2040. entry[colCell] = colCell1
  2041. }
  2042. }
  2043. }
  2044. inputdata = ""
  2045. a := ""
  2046. fmt.Println(outentry, entry)
  2047. //校验日期格式
  2048. for _, v := range dateParamslist {
  2049. if v == "" {
  2050. continue
  2051. }
  2052. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2053. dtime, err := TransfTime(d.(string))
  2054. if err != nil {
  2055. a = strings.Trim(v, " ")
  2056. break
  2057. }
  2058. outentry[strings.Trim(v, " ")] = dtime
  2059. }
  2060. }
  2061. if a != "" {
  2062. outentry["error_msg"] = a + " 格式错误"
  2063. error++
  2064. queryData = append(queryData, outentry)
  2065. continue
  2066. }
  2067. a = ""
  2068. //校验必填格式
  2069. for _, v := range requiredParamslist {
  2070. if v == "" {
  2071. continue
  2072. }
  2073. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2074. a = strings.Trim(v, " ")
  2075. break
  2076. }
  2077. }
  2078. if a != "" {
  2079. outentry["error_msg"] = a + " 未填或格式错误"
  2080. error++
  2081. queryData = append(queryData, outentry)
  2082. continue
  2083. }
  2084. a = ""
  2085. //校验数字格式
  2086. for _, v := range numParamslist {
  2087. if v == "" {
  2088. continue
  2089. }
  2090. d, ok := outentry[strings.Trim(v, " ")]
  2091. if !ok || d == "" {
  2092. outentry[strings.Trim(v, " ")] = 0
  2093. } else {
  2094. var fl float64
  2095. switch d.(type) {
  2096. case string:
  2097. fl, err = strconv.ParseFloat(d.(string), 64)
  2098. }
  2099. if err != nil || fl < 0 {
  2100. a = strings.Trim(v, " ")
  2101. break
  2102. }
  2103. }
  2104. }
  2105. if a != "" {
  2106. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2107. error++
  2108. queryData = append(queryData, outentry)
  2109. continue
  2110. }
  2111. tx := restful.Engine.NewSession()
  2112. err := tx.Begin()
  2113. for _, sqlnamestr := range sqlslist {
  2114. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2115. paramslist := strings.Split(paramslists, ",")
  2116. if len(paramslist) > 0 {
  2117. s_params := make([]interface{}, 0)
  2118. for _, value := range paramslist {
  2119. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2120. if tempv, exists := c.Get("jwt_username"); exists {
  2121. s_params = append(s_params, tempv.(string))
  2122. } else {
  2123. s_params = append(s_params, "")
  2124. }
  2125. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2126. s_params = append(s_params, pastureid)
  2127. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2128. ids, err := setting.SnowIds.NextId()
  2129. if err != nil {
  2130. ids = time.Now().UnixNano()
  2131. logging.Info("create SnowIds err", err)
  2132. }
  2133. s_params = append(s_params, ids)
  2134. } else {
  2135. if outentry[strings.Trim(value, " ")] == nil {
  2136. s_params = append(s_params, "")
  2137. } else {
  2138. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2139. }
  2140. }
  2141. }
  2142. outentry["input"] = inputdata
  2143. fmt.Println(sql, s_params)
  2144. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2145. if err != nil {
  2146. if tx != nil {
  2147. tx.Rollback()
  2148. }
  2149. if tx != nil {
  2150. tx.Close()
  2151. }
  2152. msg := geterrmsg(err.Error())
  2153. outentry["error_msg"] = msg
  2154. error++
  2155. queryData = append(queryData, outentry)
  2156. isdone = true
  2157. break
  2158. } else {
  2159. if len(returnmsgmap1) > 0 {
  2160. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2161. if tx != nil {
  2162. tx.Rollback()
  2163. }
  2164. if tx != nil {
  2165. tx.Close()
  2166. }
  2167. msg := geterrmsg(va.(string))
  2168. outentry["error_msg"] = msg
  2169. error++
  2170. queryData = append(queryData, outentry)
  2171. isdone = true
  2172. break
  2173. }
  2174. }
  2175. isdone = false
  2176. }
  2177. }
  2178. }
  2179. switch {
  2180. case err != nil:
  2181. if tx != nil {
  2182. tx.Rollback()
  2183. }
  2184. default:
  2185. if tx != nil {
  2186. err = tx.Commit()
  2187. }
  2188. }
  2189. if tx != nil {
  2190. tx.Close()
  2191. }
  2192. }
  2193. if !isdone {
  2194. ok++
  2195. isdone = true
  2196. }
  2197. }
  2198. data := make(map[string]interface{})
  2199. data["result"] = queryData
  2200. data["success"] = ok
  2201. data["err_count"] = error
  2202. appG.Response(http.StatusOK, e.SUCCESS, data)
  2203. }
  2204. func TransfTime(timestr string) (string, error) {
  2205. if timestr == "" {
  2206. return time.Now().Format("2006-01-02"), nil
  2207. }
  2208. days, err := strconv.Atoi(timestr)
  2209. if err != nil {
  2210. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2211. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2212. }
  2213. _, err := time.Parse("2006-01-02", timestr)
  2214. if err != nil {
  2215. t, err := time.Parse("2006/01/02", timestr)
  2216. if err != nil {
  2217. t, err := time.Parse("2006.01.02", timestr)
  2218. if err != nil {
  2219. return "", err
  2220. } else {
  2221. return t.Format("2006-01-02"), nil
  2222. }
  2223. } else {
  2224. return t.Format("2006-01-02"), nil
  2225. }
  2226. } else {
  2227. return timestr, nil
  2228. }
  2229. }
  2230. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2231. times = times.AddDate(0, 0, days)
  2232. return times.Format("2006-01-02"), nil
  2233. }
  2234. func Createchart(c *gin.Context) {
  2235. appG := app.Gin{C: c}
  2236. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2237. fsion := gofasion.NewFasion(string(dataByte))
  2238. chart_name := fsion.Get("chart_name").ValueStr()
  2239. desc := fsion.Get("desc").ValueStr()
  2240. pastureid := fsion.Get("pastureid").ValueStr()
  2241. source_id := fsion.Get("source_id").ValueStr()
  2242. emp := fsion.Get("emp").ValueStr()
  2243. content := fsion.Get("content").Json()
  2244. var mapResult map[string]interface{}
  2245. err1 := json.Unmarshal([]byte(content), &mapResult)
  2246. if err1 != nil {
  2247. fmt.Println("JsonToMapDemo err: ", err1)
  2248. }
  2249. tx := restful.Engine.NewSession()
  2250. err := tx.Begin()
  2251. defer func() {
  2252. switch {
  2253. case err != nil:
  2254. logging.Error("tx.Begin 事务启动失败__error:", err)
  2255. if tx != nil {
  2256. tx.Rollback()
  2257. }
  2258. default:
  2259. if tx != nil {
  2260. err = tx.Commit()
  2261. }
  2262. }
  2263. if tx != nil {
  2264. tx.Close()
  2265. }
  2266. }()
  2267. ids, err := setting.SnowIds.NextId()
  2268. if err != nil {
  2269. ids = time.Now().UnixNano()
  2270. logging.Info("create SnowIds err", err)
  2271. }
  2272. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2273. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2274. if err != nil {
  2275. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2276. } else {
  2277. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2278. }
  2279. }
  2280. func Updatedashboard(c *gin.Context) {
  2281. appG := app.Gin{C: c}
  2282. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2283. fsion := gofasion.NewFasion(string(dataByte))
  2284. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2285. pastureid := fsion.Get("pastureid").ValueStr()
  2286. content := fsion.Get("content").Json()
  2287. var mapResult map[string]interface{}
  2288. err1 := json.Unmarshal([]byte(content), &mapResult)
  2289. if err1 != nil {
  2290. fmt.Println("JsonToMapDemo err: ", err1)
  2291. }
  2292. layout := mapResult["layout"]
  2293. tx := restful.Engine.NewSession()
  2294. err := tx.Begin()
  2295. defer func() {
  2296. switch {
  2297. case err != nil:
  2298. logging.Error("tx.Begin 事务启动失败__error:", err)
  2299. if tx != nil {
  2300. tx.Rollback()
  2301. }
  2302. default:
  2303. if tx != nil {
  2304. err = tx.Commit()
  2305. }
  2306. }
  2307. if tx != nil {
  2308. tx.Close()
  2309. }
  2310. }()
  2311. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2312. if err != nil {
  2313. println("2", err.Error())
  2314. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2315. } else {
  2316. if exec != nil {
  2317. if exec[0]["content"] == nil {
  2318. mapR := make(map[string]interface{})
  2319. mapR["layout"] = layout
  2320. mjson, _ := json.Marshal(mapR)
  2321. mString := string(mjson)
  2322. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2323. if err3 != nil {
  2324. println("3", err3.Error())
  2325. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2326. } else {
  2327. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2328. }
  2329. } else {
  2330. var mapR map[string]interface{}
  2331. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2332. if err1 != nil {
  2333. fmt.Println("JsonToMapDemo err: ", err2)
  2334. }
  2335. mapR["layout"] = layout
  2336. mjson, _ := json.Marshal(mapR)
  2337. mString := string(mjson)
  2338. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2339. if err3 != nil {
  2340. println("3", err3.Error())
  2341. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2342. } else {
  2343. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2344. }
  2345. }
  2346. } else {
  2347. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2348. }
  2349. }
  2350. }
  2351. func ExecSQL(c *gin.Context) {
  2352. appG := app.Gin{C: c}
  2353. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2354. fsion := gofasion.NewFasion(string(dataByte))
  2355. content := fsion.Get("content").Json()
  2356. pastureid := fsion.Get("pastureid").ValueStr()
  2357. var mapResult map[string]interface{}
  2358. err1 := json.Unmarshal([]byte(content), &mapResult)
  2359. if err1 != nil {
  2360. fmt.Println("JsonToMapDemo err: ", err1)
  2361. }
  2362. sqlstr := "select "
  2363. groupstr := " GROUP BY "
  2364. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2365. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2366. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2367. }
  2368. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2369. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2370. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2371. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2372. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2373. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2374. sqlstr = sqlstr + tem + ","
  2375. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2376. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2377. sqlstr = sqlstr + tem + ","
  2378. } else {
  2379. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2380. sqlstr = sqlstr + tem + ","
  2381. }
  2382. }
  2383. if _, ok := mapResult["selectedCalcul2"]; ok {
  2384. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2385. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2386. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2387. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2388. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2389. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2390. sqlstr = sqlstr + tem + ","
  2391. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2392. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2393. sqlstr = sqlstr + tem + ","
  2394. } else {
  2395. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2396. sqlstr = sqlstr + tem + ","
  2397. }
  2398. }
  2399. }
  2400. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2401. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2402. sqlstr = sqlstr + " where pastureid=" + pastureid
  2403. if len(mapResult["filters"].([]interface{})) > 0 {
  2404. sqlstr = sqlstr + " and "
  2405. }
  2406. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2407. for _, value := range mapResult["filters"].([]interface{}) {
  2408. switch value.(map[string]interface{})["filterOperator"].(string) {
  2409. case ">", "=", "<", ">=", "<=", "!=", "like":
  2410. 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 "
  2411. case "IN":
  2412. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2413. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2414. sqlstr = sqlstr + value1.(string) + ","
  2415. }
  2416. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2417. sqlstr = sqlstr + ")" + " AND "
  2418. case "BETWEEN":
  2419. 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 "
  2420. }
  2421. }
  2422. if len(mapResult["filters"].([]interface{})) > 0 {
  2423. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2424. }
  2425. //
  2426. groupstr = groupstr[0 : len(groupstr)-1]
  2427. sqlstr = sqlstr + groupstr + " "
  2428. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2429. sqlstr = sqlstr + " order by "
  2430. }
  2431. //
  2432. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2433. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2434. sqlstr = sqlstr + value.(string) + " "
  2435. } else {
  2436. sqlstr = sqlstr + value.(string) + ","
  2437. }
  2438. }
  2439. //
  2440. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2441. tx := restful.Engine.NewSession()
  2442. err := tx.Begin()
  2443. defer func() {
  2444. switch {
  2445. case err != nil:
  2446. logging.Error("tx.Begin 事务启动失败__error:", err)
  2447. if tx != nil {
  2448. tx.Rollback()
  2449. }
  2450. default:
  2451. if tx != nil {
  2452. err = tx.Commit()
  2453. }
  2454. }
  2455. if tx != nil {
  2456. tx.Close()
  2457. }
  2458. }()
  2459. exec, err := tx.SQL(sqlstr).Query().List()
  2460. if err != nil {
  2461. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2462. } else {
  2463. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2464. }
  2465. }
  2466. func Dashboards(c *gin.Context) {
  2467. appG := app.Gin{C: c}
  2468. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2469. fsion := gofasion.NewFasion(string(dataByte))
  2470. sqlnamestr := fsion.Get("name").ValueStr()
  2471. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2472. offset := fsion.Get("offset").ValueDefaultInt(0)
  2473. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2474. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2475. month := fsion.Get("month").ValueDefaultStr("map")
  2476. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2477. tx := restful.Engine.NewSession()
  2478. err := tx.Begin()
  2479. defer func() {
  2480. switch {
  2481. case err != nil:
  2482. if tx != nil {
  2483. tx.Rollback()
  2484. }
  2485. default:
  2486. if tx != nil {
  2487. err = tx.Commit()
  2488. }
  2489. }
  2490. if tx != nil {
  2491. tx.Close()
  2492. }
  2493. }()
  2494. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2495. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2496. if sql != "" {
  2497. s_params := make([]interface{}, 0)
  2498. if fsion.HasKey("parammaps") {
  2499. parammaps := fsion.Get("parammaps")
  2500. paramslist := strings.Split(p, ",")
  2501. if len(paramslist) > 0 && p != "" {
  2502. for _, value := range paramslist {
  2503. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2504. if tempv, exists := c.Get("jwt_username"); exists {
  2505. s_params = append(s_params, tempv.(string))
  2506. } else {
  2507. s_params = append(s_params, "")
  2508. }
  2509. } else {
  2510. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2511. }
  2512. }
  2513. }
  2514. }
  2515. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2516. if err != nil {
  2517. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2518. } else {
  2519. //paramslist1 := strings.Split(p1, ",")
  2520. dids := make([]interface{}, 0)
  2521. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2522. var mapResult map[string]interface{}
  2523. dids = append(dids, value["dashboard_id"])
  2524. if value["content"] != nil {
  2525. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2526. if err1 != nil {
  2527. println("JsonToMapDemo1 err: ", err1)
  2528. }
  2529. temap := make(map[string]interface{})
  2530. tem := mapResult["layout"].([]interface{})
  2531. if v, ok := value["chartids"]; ok {
  2532. chartids := strings.Split(v.(string), ",")
  2533. for _, va := range chartids {
  2534. a := false
  2535. for _, v2 := range tem {
  2536. if v2.(map[string]interface{})["id"].(string) == va {
  2537. a = true
  2538. //println("va1======",va)
  2539. }
  2540. }
  2541. if !a {
  2542. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2543. va + "\",\"id\":\"" + va +
  2544. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2545. var mapTem map[string]interface{}
  2546. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2547. if err1 != nil {
  2548. println("JsonToMapDemo err: ", err1)
  2549. }
  2550. tem = append(tem, mapTem)
  2551. }
  2552. }
  2553. temap["layout"] = tem
  2554. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2555. }
  2556. } else {
  2557. temap := make(map[string]interface{})
  2558. tem := make([]interface{}, 0)
  2559. if v, ok := value["chartids"]; ok {
  2560. chartids := strings.Split(v.(string), ",")
  2561. for _, va := range chartids {
  2562. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2563. va + "\",\"id\":\"" + va +
  2564. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2565. var mapTem map[string]interface{}
  2566. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2567. if err1 != nil {
  2568. println("JsonToMapDemo err: ", err1)
  2569. }
  2570. tem = append(tem, mapTem)
  2571. }
  2572. temap["layout"] = tem
  2573. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2574. }
  2575. }
  2576. }
  2577. queryData.(map[string]interface{})["order"] = dids
  2578. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2579. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2580. }
  2581. } else {
  2582. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2583. }
  2584. }
  2585. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2586. fsion := gofasion.NewFasion(parammaps)
  2587. sqlnamestr := fsion.Get("name").ValueStr()
  2588. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2589. offset := fsion.Get("offset").ValueDefaultInt(0)
  2590. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2591. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2592. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2593. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2594. body := []byte("")
  2595. if sql != "" {
  2596. s_params := make([]interface{}, 0)
  2597. if fsion.HasKey("parammaps") {
  2598. parammaps := fsion.Get("parammaps")
  2599. paramslist := strings.Split(p, ",")
  2600. if len(paramslist) > 0 && p != "" {
  2601. for _, value := range paramslist {
  2602. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2603. }
  2604. }
  2605. }
  2606. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2607. if err != nil {
  2608. } else {
  2609. paramslist1 := strings.Split(p1, ",")
  2610. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2611. s_params1 := make([]interface{}, 0)
  2612. if len(paramslist1) > 0 && p1 != "" {
  2613. for _, v := range paramslist1 {
  2614. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2615. }
  2616. }
  2617. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2618. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2619. body, _ = json.Marshal(queryData)
  2620. }
  2621. }
  2622. }
  2623. bs := bytes.NewBuffer(body)
  2624. client := &http.Client{}
  2625. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2626. req, err := http.NewRequest(RequestMethod,
  2627. url,
  2628. bs,
  2629. )
  2630. if err != nil {
  2631. }
  2632. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2633. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2634. if err != nil {
  2635. // handle error
  2636. }
  2637. resp, err := client.Do(req)
  2638. if err != nil {
  2639. return ""
  2640. }
  2641. defer resp.Body.Close()
  2642. result_body, err := ioutil.ReadAll(resp.Body)
  2643. if err != nil {
  2644. return ""
  2645. }
  2646. fmt.Println(string(result_body))
  2647. return ""
  2648. }
  2649. func GetSummary(c *gin.Context) {
  2650. appG := app.Gin{C: c}
  2651. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2652. fsion := gofasion.NewFasion(string(dataByte))
  2653. offset := fsion.Get("offset").ValueDefaultInt(0)
  2654. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2655. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2656. parammaps := fsion.Get("parammaps")
  2657. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2658. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2659. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2660. tx := restful.Engine.NewSession()
  2661. defer tx.Close()
  2662. sqlnamestr := ""
  2663. if genre == "0" {
  2664. if status == "0" {
  2665. sqlnamestr = "getAccuracyJSY"
  2666. } else if status == "1" {
  2667. sqlnamestr = "getAccuracyHFT"
  2668. } else if status == "2" {
  2669. sqlnamestr = "getAccuracyHNS"
  2670. } else if status == "3" {
  2671. sqlnamestr = "getAccuracyHSC"
  2672. } else if status == "4" {
  2673. sqlnamestr = "getAccuracyHCC"
  2674. } else if status == "5" {
  2675. sqlnamestr = "getAccuracyMC"
  2676. } else if status == "6" {
  2677. sqlnamestr = "getAccuracyFeedHL"
  2678. } else if status == "7" {
  2679. sqlnamestr = "getAccuracyRT"
  2680. }
  2681. } else {
  2682. if status == "0" {
  2683. sqlnamestr = "getAccuracySCCJSY"
  2684. } else if status == "1" {
  2685. sqlnamestr = "getAccuracySFT"
  2686. } else if status == "2" {
  2687. sqlnamestr = "getAccuracySNS"
  2688. } else if status == "3" {
  2689. sqlnamestr = "getAccuracySSC"
  2690. } else if status == "4" {
  2691. sqlnamestr = "getAccuracySCC"
  2692. } else if status == "5" {
  2693. sqlnamestr = "getAccuracySLCL"
  2694. } else if status == "7" {
  2695. sqlnamestr = "getAccuracySCCRT"
  2696. }
  2697. }
  2698. if isDate == "1" {
  2699. sqlnamestr += "Date"
  2700. }
  2701. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2702. // fmt.Println(sqlnamestr, sql)
  2703. if sql != "" {
  2704. s_params := make([]interface{}, 0)
  2705. // if fsion.HasKey("parammaps") {
  2706. fmt.Println(s_params, "222", p)
  2707. paramslist := strings.Split(p, ",")
  2708. if len(paramslist) > 0 && p != "" {
  2709. for _, value := range paramslist {
  2710. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2711. if tempv, exists := c.Get("jwt_username"); exists {
  2712. s_params = append(s_params, tempv.(string))
  2713. } else {
  2714. s_params = append(s_params, "")
  2715. }
  2716. } else {
  2717. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2718. }
  2719. }
  2720. }
  2721. if returntype == "xlsx" {
  2722. var xlsxfile *xlsx.File
  2723. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2724. //c.File("c:/dd.xlsx")
  2725. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2726. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2727. c.Header("Content-Transfer-Encoding", "binary")
  2728. _ = xlsxfile.Write(c.Writer)
  2729. } else {
  2730. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2731. if err != nil {
  2732. logging.Error("GetDataByName err: ", err)
  2733. msg := geterrmsg(err.Error())
  2734. appG.Response(http.StatusOK, e.ERROR, msg)
  2735. } else {
  2736. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2737. }
  2738. }
  2739. } else {
  2740. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2741. }
  2742. }
  2743. // type lpplanStruct struct {
  2744. // Id int64 `xorm:"id"`
  2745. // Tmrname string `xorm:"tmrname"`
  2746. // Tmrid int64 `xorm:"tmrid"`
  2747. // Sort int64 `xorm:"sort"`
  2748. // Sel int64 `xorm:"sel"`
  2749. // Times int64 `xorm:"times"`
  2750. // Ftname string `xorm:"ftname"`
  2751. // Ftid int64 `xorm:"ftid"`
  2752. // Maxweight float64 `xorm:"maxweight"`
  2753. // Sumweight float64 `xorm:"sumweight"`
  2754. // Sumcowcount int64 `xorm:"sumcowcount"`
  2755. // Pastureid string `xorm:"pastureid"`
  2756. // Display string `xorm:"display"`
  2757. // Issplit int64 `xorm:"issplit"`
  2758. // BeginTime string `xorm:"begintime"`
  2759. // }
  2760. func UpdateFTdetail(c *gin.Context) {
  2761. appG := app.Gin{C: c}
  2762. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2763. tempval_ := make(map[string]interface{})
  2764. tempCommon := make(map[string]interface{})
  2765. tempval := make([]map[string]interface{}, 0)
  2766. fTChange := make(map[string]interface{}, 0)
  2767. fpdOldDataList := make([]map[string]interface{}, 0)
  2768. fpdDataList := make([]map[string]interface{}, 0)
  2769. fsion := gofasion.NewFasion(string(dataByte))
  2770. // parammaps := fsion.Get("parammaps")
  2771. createdate := time.Now().Format("2006-01-02 15:04:05")
  2772. err := json.Unmarshal(dataByte, &tempval_)
  2773. if err != nil {
  2774. appG.Response(http.StatusOK, e.ERROR, false)
  2775. return
  2776. }
  2777. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2778. tx := restful.Engine.NewSession()
  2779. if v, ok := tempval_["data"].([]interface{}); ok {
  2780. for _, Tvalue := range v {
  2781. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2782. if v1["name"] == "updateFPbyFTChange" {
  2783. fTChange = v1
  2784. continue
  2785. }
  2786. tempval = append(tempval, v1)
  2787. }
  2788. }
  2789. }
  2790. parammaps := fTChange["parammaps"].(map[string]interface{})
  2791. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2792. // if err != nil {
  2793. // logs.Error(err)
  2794. // appG.Response(http.StatusOK, e.ERROR, false)
  2795. // return
  2796. // }
  2797. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2798. // if err != nil {
  2799. // logs.Error(err)
  2800. // appG.Response(http.StatusOK, e.ERROR, false)
  2801. // return
  2802. // }
  2803. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2804. // if err != nil {
  2805. // logs.Error(err)
  2806. // appG.Response(http.StatusOK, e.ERROR, false)
  2807. // return
  2808. // }
  2809. err = tx.Begin()
  2810. if err != nil {
  2811. logging.Error("tx.Begin 事务启动失败__error:", err)
  2812. }
  2813. defer func() {
  2814. if err != nil {
  2815. if tx != nil {
  2816. tx.Rollback()
  2817. }
  2818. }
  2819. if tx != nil {
  2820. tx.Close()
  2821. }
  2822. }()
  2823. if err != nil {
  2824. } else {
  2825. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2826. tempCommon = v
  2827. }
  2828. 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 ,
  2829. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2830. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2831. UNION
  2832. 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 ,
  2833. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2834. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2835. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2836. if err == nil {
  2837. if tempv, exists := c.Get("jwt_username"); exists {
  2838. tempCommon["jwt_username"] = tempv.(string)
  2839. }
  2840. for _, paramvalue := range tempval {
  2841. if _, ok := paramvalue["resultname"]; !ok {
  2842. paramvalue["resultname"] = paramvalue["name"]
  2843. }
  2844. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2845. if err != nil {
  2846. logging.Error("ExecDataParam error:", err)
  2847. break
  2848. }
  2849. }
  2850. if err != nil {
  2851. msg := geterrmsg(err.Error())
  2852. appG.Response(http.StatusOK, e.ERROR, msg)
  2853. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2854. }
  2855. }
  2856. }
  2857. tx.Commit()
  2858. // go func() {
  2859. if fTChange != nil {
  2860. parammaps := fTChange["parammaps"].(map[string]interface{})
  2861. if parammaps["type"].(float64) == 1 {
  2862. _, err = tx.SQL(`UPDATE feedp fp
  2863. set
  2864. fp.ftweight= IFNULL(IF(
  2865. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2866. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2867. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2868. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2869. ),0),fp.feedweight = IFNULL(IF(
  2870. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2871. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2872. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2873. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2874. ),0) +ifnull(fp.supplyweight,0)
  2875. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2876. _, err = tx.SQL(`UPDATE fpdetail fpd
  2877. INNER JOIN feedp fp
  2878. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2879. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2880. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2881. } else {
  2882. _, err = tx.SQL(`UPDATE feedp fp
  2883. SET
  2884. fp.supplyweight= IFNULL(IF(
  2885. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2886. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2887. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2888. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2889. ),0),fp.feedweight = IFNULL(IF(
  2890. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2891. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2892. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2893. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2894. ),0) +ifnull(fp.supplyweight,0)
  2895. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2896. _, err = tx.SQL(`UPDATE fpdetail fpd
  2897. INNER JOIN feedp fp
  2898. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2899. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2900. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2901. }
  2902. 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 ,
  2903. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2904. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2905. UNION
  2906. 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 ,
  2907. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2908. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2909. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2910. lpplanList := make([]*lpplanStruct, 0)
  2911. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2912. if err != nil {
  2913. logs.Error(err, 1)
  2914. return
  2915. }
  2916. lppidlist := []string{}
  2917. for _, lpp := range lpplanList {
  2918. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2919. }
  2920. if len(lppidlist) <= 0 {
  2921. appG.Response(http.StatusOK, e.SUCCESS, true)
  2922. return
  2923. }
  2924. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2925. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2926. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2927. if err != nil {
  2928. // tx.Rollback()
  2929. logs.Error(err, 2, parammaps["pastureid"])
  2930. return
  2931. }
  2932. var wg sync.WaitGroup
  2933. for _, old := range fpdOldDataList {
  2934. for _, fpd := range fpdDataList {
  2935. wg.Add(1)
  2936. go func(old, fpd map[string]interface{}) {
  2937. updateLppandList := make([]*lpplandtl1, 0)
  2938. defer wg.Done()
  2939. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2940. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2941. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2942. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2943. // if weight > oldweight {
  2944. // return
  2945. // }
  2946. var w float64
  2947. var status int
  2948. if weight < oldweight {
  2949. if weight >= 0 {
  2950. return
  2951. }
  2952. w = weight
  2953. status = 0
  2954. } else {
  2955. if oldweight > 0 {
  2956. return
  2957. }
  2958. w = weight
  2959. status = 1
  2960. }
  2961. // fweight = w
  2962. for _, lpp := range lpplanList {
  2963. var fweight float64
  2964. var lweight float64
  2965. lpplandtl1List := make([]*lpplandtl1, 0)
  2966. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2967. for _, lppland := range lpplandtl1AllList {
  2968. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2969. lpplandtl1List = append(lpplandtl1List, lppland)
  2970. }
  2971. }
  2972. if len(lpplandtl1List) == 0 {
  2973. continue
  2974. }
  2975. for _, lppland := range lpplandtl1List {
  2976. lweight += lppland.Lweight
  2977. }
  2978. if status == 0 {
  2979. if lweight <= 0 {
  2980. continue
  2981. }
  2982. } else {
  2983. if lpp.Maxweight <= lweight {
  2984. continue
  2985. }
  2986. }
  2987. for _, lppland := range lpplandtl1List {
  2988. if fpdid == lppland.Fpdid {
  2989. if status == 1 {
  2990. // if w <= lppland.Lweight {
  2991. if lpp.Maxweight <= lweight {
  2992. continue
  2993. }
  2994. if w+lweight <= lpp.Maxweight {
  2995. lppland.Lweight += w
  2996. lweight += w
  2997. fweight += w
  2998. w = 0
  2999. } else {
  3000. w = w - (lpp.Maxweight - lweight)
  3001. n := (lpp.Maxweight - lweight)
  3002. lppland.Lweight = lppland.Lweight + n
  3003. lweight += n
  3004. fweight += n
  3005. }
  3006. } else {
  3007. if lppland.Lweight == 0 {
  3008. continue
  3009. }
  3010. if w+lppland.Lweight >= 0 {
  3011. lppland.Lweight = lppland.Lweight + w
  3012. lweight = lweight + w
  3013. fweight = fweight + w
  3014. w = 0
  3015. } else {
  3016. w = w + lppland.Lweight
  3017. lweight = lweight - lppland.Lweight
  3018. fweight = fweight - lppland.Lweight
  3019. lppland.Lweight = 0
  3020. }
  3021. }
  3022. updateLppandList = append(updateLppandList, lppland)
  3023. break
  3024. }
  3025. }
  3026. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3027. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3028. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3029. if err != nil {
  3030. // tx.Rollback()
  3031. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3032. return
  3033. }
  3034. for _, lppland := range updateLppandList {
  3035. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3036. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3037. if err != nil {
  3038. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3039. // tx.Rollback()
  3040. logs.Error(err, 3)
  3041. return
  3042. }
  3043. // defer wg.Done()
  3044. }
  3045. updateLppandList = []*lpplandtl1{}
  3046. if w == 0 {
  3047. break
  3048. }
  3049. }
  3050. }
  3051. }(old, fpd)
  3052. }
  3053. }
  3054. wg.Wait()
  3055. }
  3056. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3057. if err != nil {
  3058. logs.Error(err)
  3059. appG.Response(http.StatusOK, e.ERROR, false)
  3060. return
  3061. }
  3062. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3063. if err != nil {
  3064. logs.Error(err)
  3065. appG.Response(http.StatusOK, e.ERROR, false)
  3066. return
  3067. }
  3068. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3069. if err != nil {
  3070. logs.Error(err)
  3071. appG.Response(http.StatusOK, e.ERROR, false)
  3072. return
  3073. }
  3074. now := createdate
  3075. // for _, oldFpd := range oldFpdDataList {
  3076. for _, newFpd := range newFpdDataList {
  3077. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3078. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3079. // go func() {
  3080. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3081. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3082. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3083. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3084. if err != nil {
  3085. logs.Error(err)
  3086. appG.Response(http.StatusOK, e.ERROR, false)
  3087. return
  3088. }
  3089. // }()
  3090. }
  3091. // break
  3092. // }
  3093. // }
  3094. // }
  3095. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3096. for _, newLpplandtl1 := range newLpplandtl1List {
  3097. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3098. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3099. // go func() {
  3100. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3101. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3102. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3103. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3104. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3105. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3106. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3107. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3108. if err != nil {
  3109. logs.Error(err)
  3110. appG.Response(http.StatusOK, e.ERROR, false)
  3111. return
  3112. }
  3113. // }()
  3114. // }
  3115. // break
  3116. // }
  3117. // }
  3118. }
  3119. // for _, oldFeedp := range oldFeedpList {
  3120. for _, newFeedp := range newFeedpList {
  3121. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3122. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3123. // go func() {
  3124. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3125. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3126. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3127. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3128. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3129. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3130. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3131. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3132. if err != nil {
  3133. logs.Error(err)
  3134. appG.Response(http.StatusOK, e.ERROR, false)
  3135. return
  3136. }
  3137. // }()
  3138. // }
  3139. // }
  3140. }
  3141. appG.Response(http.StatusOK, e.SUCCESS, true)
  3142. }
  3143. type lpplandtlInfo struct {
  3144. Id int64 `xorm:"id"`
  3145. Pastureid int64 `xorm:"pastureid"`
  3146. Lppid int64 `xorm:"lppid"`
  3147. Barid int64 `xorm:"barid"`
  3148. Barname string `xorm:"barname"`
  3149. Fpdid int64 `xorm:"fpdid"`
  3150. Fttype int64 `xorm:"fttype"`
  3151. Lweight float64 `xorm:"lweight"`
  3152. Sort int64 `xorm:"sort"`
  3153. Tmrid int64 `xorm:"tmrid"`
  3154. Tmrname string `xorm:"tmrname"`
  3155. Cowcount int64 `xorm:"cowcount"`
  3156. Ccountradio float64 `xorm:"ccountradio"`
  3157. Background string `xorm:"background"`
  3158. Lweighthis float64 `xorm:"lweighthis"`
  3159. Maxweight float64 `xorm:"maxweight"`
  3160. }
  3161. func UpdateFpdetailBar(c *gin.Context) {
  3162. appG := app.Gin{C: c}
  3163. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3164. fsion := gofasion.NewFasion(string(dataByte))
  3165. pastureid := fsion.Get("pastureid").ValueStr()
  3166. id := fsion.Get("id").ValueStr()
  3167. tx := restful.Engine.NewSession()
  3168. tx.Begin()
  3169. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse from fpdetail where pastureid = ? and barid = (select barid from feedp where id = ? ) order by times `,
  3170. pastureid, id).Query().List()
  3171. if err != nil {
  3172. logs.Error(err)
  3173. }
  3174. for _, fpd := range fpdList {
  3175. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3176. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3177. pastureid, fpd["id"]).Query().List()
  3178. if err != nil {
  3179. tx.Rollback()
  3180. logs.Error(err)
  3181. appG.Response(http.StatusOK, e.ERROR, false)
  3182. return
  3183. }
  3184. var lweight float64
  3185. for _, lppland := range lpplandList {
  3186. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3187. lweight += lweight1
  3188. }
  3189. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3190. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3191. if fpdweight >= ptuse && lweight == ptuse {
  3192. continue
  3193. } else {
  3194. if lweight <= fpdweight {
  3195. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3196. if err != nil {
  3197. tx.Rollback()
  3198. logs.Error(err)
  3199. appG.Response(http.StatusOK, e.ERROR, false)
  3200. return
  3201. }
  3202. } else {
  3203. weight := fpdweight - lweight
  3204. for _, lppland := range lpplandList {
  3205. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3206. if weight >= lpplandlweight {
  3207. weight = weight - lpplandlweight
  3208. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3209. if err != nil {
  3210. tx.Rollback()
  3211. logs.Error(err)
  3212. appG.Response(http.StatusOK, e.ERROR, false)
  3213. return
  3214. }
  3215. } else {
  3216. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3217. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3218. // if err != nil {
  3219. // tx.Rollback()
  3220. // logs.Error(err)
  3221. // appG.Response(http.StatusOK, e.ERROR, false)
  3222. // return
  3223. // }
  3224. weight = 0
  3225. break
  3226. }
  3227. }
  3228. }
  3229. }
  3230. }
  3231. for _, list := range fsion.Get("data").Array() {
  3232. ftmap := make(map[string]interface{})
  3233. ftmap["old"] = list.Get("old").ValueFloat64()
  3234. ftmap["new"] = list.Get("new").ValueFloat64()
  3235. ftmap["times"] = list.Get("times").ValueInt64()
  3236. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3237. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3238. // fmt.Println(ftmap)
  3239. 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(-1 ) ptsid ,
  3240. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3241. WHERE fpdetail.pastureid = ? and barid =(select barid from feedp where id = ? ) and times = ?
  3242. UNION
  3243. 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 ,
  3244. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3245. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? ) t
  3246. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3247. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3248. if err != nil {
  3249. tx.Rollback()
  3250. logs.Error(err)
  3251. }
  3252. for _, fpd := range fpdDataList {
  3253. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3254. fttype := -1
  3255. if ftmap["ptid"].(string) != "-1" {
  3256. fttype = 1
  3257. }
  3258. var fweight float64
  3259. var lweight float64
  3260. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3261. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3262. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3263. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3264. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3265. if err != nil {
  3266. tx.Rollback()
  3267. logs.Error(err)
  3268. }
  3269. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3270. var w float64
  3271. var status int
  3272. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3273. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3274. if weight >= 0 {
  3275. continue
  3276. }
  3277. w = weight
  3278. status = 0
  3279. } else {
  3280. // continue
  3281. if weight <= 0 {
  3282. continue
  3283. }
  3284. w = weight
  3285. status = 1
  3286. }
  3287. for _, lppland := range lpplandtl1List {
  3288. lweight += lppland.Lweight
  3289. }
  3290. for _, lppland := range lpplandtl1List {
  3291. if status == 1 {
  3292. // if w <= lppland.Lweight {
  3293. if lppland.Maxweight <= lweight {
  3294. continue
  3295. }
  3296. if w+lweight <= lppland.Maxweight {
  3297. lppland.Lweight += w
  3298. lweight += w
  3299. fweight += w
  3300. w = 0
  3301. } else {
  3302. w = w - (lppland.Maxweight - lweight)
  3303. n := (lppland.Maxweight - lweight)
  3304. lppland.Lweight = lppland.Lweight + n
  3305. lweight += n
  3306. fweight += n
  3307. }
  3308. } else {
  3309. if lppland.Lweight == 0 {
  3310. continue
  3311. }
  3312. if w+lppland.Lweight >= 0 {
  3313. lppland.Lweight = lppland.Lweight + w
  3314. lweight = lweight + w
  3315. fweight = fweight + w
  3316. w = 0
  3317. } else {
  3318. w = w + lppland.Lweight
  3319. lweight = lweight - lppland.Lweight
  3320. fweight = fweight - lppland.Lweight
  3321. lppland.Lweight = 0
  3322. }
  3323. }
  3324. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3325. if err != nil {
  3326. tx.Rollback()
  3327. logs.Error(err)
  3328. return
  3329. }
  3330. break
  3331. }
  3332. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3333. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3334. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3335. if err != nil {
  3336. tx.Rollback()
  3337. logs.Error(err)
  3338. }
  3339. if w == 0 {
  3340. break
  3341. }
  3342. }
  3343. }
  3344. }
  3345. tx.Commit()
  3346. now := time.Now()
  3347. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3348. if err != nil {
  3349. logs.Error(err)
  3350. appG.Response(http.StatusOK, e.ERROR, false)
  3351. return
  3352. }
  3353. // newFpdDataList, err := tx.SQL(` select * from fpdetail where barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3354. // if err != nil {
  3355. // logs.Error(err)
  3356. // appG.Response(http.StatusOK, e.ERROR, false)
  3357. // return
  3358. // }
  3359. // newFeedpList, err := tx.SQL(` select * from feedp where barid = ? and pastureid = ?`, id, pastureid).Query().List()
  3360. // if err != nil {
  3361. // logs.Error(err)
  3362. // appG.Response(http.StatusOK, e.ERROR, false)
  3363. // return
  3364. // }
  3365. for _, newLpplandtl1 := range newLpplandtl1List {
  3366. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3367. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3368. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3369. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3370. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3371. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3372. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3373. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3374. if err != nil {
  3375. logs.Error(err)
  3376. appG.Response(http.StatusOK, e.ERROR, false)
  3377. return
  3378. }
  3379. }
  3380. appG.Response(http.StatusOK, e.SUCCESS, true)
  3381. }
  3382. func GetProcessAnalysis(c *gin.Context) {
  3383. appG := app.Gin{C: c}
  3384. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3385. fsion := gofasion.NewFasion(string(dataByte))
  3386. sqlnamestr := fsion.Get("name").ValueStr()
  3387. offset := fsion.Get("offset").ValueDefaultInt(0)
  3388. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3389. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3390. parammaps := fsion.Get("parammaps")
  3391. tx := restful.Engine.NewSession()
  3392. err := tx.Begin()
  3393. defer func() {
  3394. switch {
  3395. case err != nil:
  3396. logging.Error("tx.Begin 事务启动失败__error:", err)
  3397. if tx != nil {
  3398. tx.Rollback()
  3399. }
  3400. default:
  3401. if tx != nil {
  3402. err = tx.Commit()
  3403. }
  3404. }
  3405. if tx != nil {
  3406. tx.Close()
  3407. }
  3408. }()
  3409. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3410. s_params := make([]interface{}, 0)
  3411. paramslist := strings.Split(p, ",")
  3412. if len(paramslist) > 0 && p != "" {
  3413. for _, value := range paramslist {
  3414. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3415. if tempv, exists := c.Get("jwt_username"); exists {
  3416. s_params = append(s_params, tempv.(string))
  3417. } else {
  3418. s_params = append(s_params, "")
  3419. }
  3420. } else {
  3421. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3422. }
  3423. }
  3424. }
  3425. tmrtnameStr := ""
  3426. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3427. if len(tmrtnameStr) == 0 {
  3428. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3429. } else {
  3430. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3431. }
  3432. }
  3433. if len(tmrtnameStr) > 0 {
  3434. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3435. }
  3436. sql += " ORDER BY d.intime"
  3437. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3438. if err != nil {
  3439. logging.Error("GetDataByName err: ", err)
  3440. msg := geterrmsg(err.Error())
  3441. appG.Response(http.StatusOK, e.ERROR, msg)
  3442. } else {
  3443. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3444. }
  3445. }
  3446. func UpdateFeedtempletStatus(c *gin.Context) {
  3447. appG := app.Gin{C: c}
  3448. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3449. fsion := gofasion.NewFasion(string(dataByte))
  3450. parammaps := fsion.Get("parammaps")
  3451. tx := restful.Engine.NewSession()
  3452. tx.Begin()
  3453. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3454. if err != nil {
  3455. tx.Rollback()
  3456. logs.Error(err)
  3457. appG.Response(http.StatusOK, e.ERROR, err)
  3458. return
  3459. }
  3460. tx.Commit()
  3461. appG.Response(http.StatusOK, e.SUCCESS, true)
  3462. }
  3463. func AddFtdry(c *gin.Context) {
  3464. appG := app.Gin{C: c}
  3465. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3466. fsion := gofasion.NewFasion(string(dataByte))
  3467. sqlnamestr := fsion.Get("name").ValueStr()
  3468. s_params := make([]interface{}, 0)
  3469. tx := restful.Engine.NewSession()
  3470. err := tx.Begin()
  3471. defer func() {
  3472. switch {
  3473. case err != nil:
  3474. if tx != nil {
  3475. tx.Rollback()
  3476. }
  3477. default:
  3478. if tx != nil {
  3479. err = tx.Commit()
  3480. }
  3481. }
  3482. if tx != nil {
  3483. tx.Close()
  3484. }
  3485. }()
  3486. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3487. if sql != "" {
  3488. parammaps := fsion.Get("parammaps")
  3489. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3490. paramslist := strings.Split(p, ",")
  3491. if len(paramslist) > 0 && p != "" {
  3492. for _, value := range paramslist {
  3493. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3494. if tempv, exists := c.Get("jwt_username"); exists {
  3495. s_params = append(s_params, tempv.(string))
  3496. } else {
  3497. s_params = append(s_params, "")
  3498. }
  3499. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3500. ids, err := setting.SnowIds.NextId()
  3501. if err != nil {
  3502. ids = time.Now().UnixNano()
  3503. logging.Info("create SnowIds err", err)
  3504. }
  3505. s_params = append(s_params, ids)
  3506. } else {
  3507. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3508. }
  3509. }
  3510. }
  3511. var actweight float64
  3512. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3513. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3514. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3515. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3516. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3517. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3518. 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()
  3519. if err != nil {
  3520. logging.Error("AddFtdry err: ", err)
  3521. msg := geterrmsg(err.Error())
  3522. appG.Response(http.StatusOK, e.ERROR, msg)
  3523. }
  3524. if len(actweightList) > 0 {
  3525. for _, item := range actweightList {
  3526. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3527. if err != nil {
  3528. logging.Error("AddFtdry err: ", err)
  3529. msg := geterrmsg(err.Error())
  3530. appG.Response(http.StatusOK, e.ERROR, msg)
  3531. }
  3532. actweight = fl
  3533. }
  3534. } else {
  3535. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3536. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3537. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3538. if err != nil {
  3539. logging.Error("AddFtdry err: ", err)
  3540. msg := geterrmsg(err.Error())
  3541. appG.Response(http.StatusOK, e.ERROR, msg)
  3542. }
  3543. for _, item := range dryList {
  3544. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3545. if err != nil {
  3546. logging.Error("AddFtdry err: ", err)
  3547. msg := geterrmsg(err.Error())
  3548. appG.Response(http.StatusOK, e.ERROR, msg)
  3549. }
  3550. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3551. }
  3552. }
  3553. if sqlnamestr == "insertFtdry" {
  3554. s_params = append(s_params, actweight)
  3555. } else if sqlnamestr == "updateFtdry" {
  3556. sql = fmt.Sprintf(sql, actweight)
  3557. }
  3558. queryData, err := execDataBySqlT(sql, s_params, tx)
  3559. if err != nil {
  3560. logging.Error("AddFtdry err: ", err)
  3561. msg := geterrmsg(err.Error())
  3562. appG.Response(http.StatusOK, e.ERROR, msg)
  3563. } else {
  3564. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3565. }
  3566. } else {
  3567. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3568. }
  3569. }
  3570. func CheckDates(c *gin.Context) {
  3571. tx := restful.Engine.NewSession()
  3572. defer tx.Close()
  3573. appG := app.Gin{C: c}
  3574. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3575. tempval_ := make(map[string]interface{})
  3576. tempCommon := make(map[string]interface{})
  3577. tempval := make([]map[string]interface{}, 0)
  3578. err := json.Unmarshal(dataByte, &tempval_)
  3579. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3580. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3581. if err != nil {
  3582. } else {
  3583. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3584. tempCommon = v
  3585. }
  3586. if v, ok := tempval_["data"].([]interface{}); ok {
  3587. for _, Tvalue := range v {
  3588. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3589. tempval = append(tempval, v1)
  3590. }
  3591. }
  3592. }
  3593. if err == nil {
  3594. if tempv, exists := c.Get("jwt_username"); exists {
  3595. tempCommon["jwt_username"] = tempv.(string)
  3596. }
  3597. for _, paramvalue := range tempval {
  3598. if _, ok := paramvalue["resultname"]; !ok {
  3599. paramvalue["resultname"] = paramvalue["name"]
  3600. }
  3601. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3602. if err != nil {
  3603. logging.Error("ExecDataParam error:", err)
  3604. }
  3605. }
  3606. if err == nil {
  3607. vmsg := ""
  3608. for _, item := range tempval {
  3609. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3610. for _, childrenList := range list.([]interface{}) {
  3611. for k, children := range childrenList.(map[string]interface{}) {
  3612. if k != "children" {
  3613. continue
  3614. }
  3615. for _, v := range children.([]map[string]interface{}) {
  3616. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3617. if k1 == "list" {
  3618. for _, v2 := range v1.([]map[string]interface{}) {
  3619. if v2["vmsg"].(string) != "1" {
  3620. if len(vmsg) == 0 {
  3621. vmsg = v2["vmsg"].(string)
  3622. } else {
  3623. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3624. }
  3625. }
  3626. }
  3627. }
  3628. }
  3629. }
  3630. }
  3631. }
  3632. }
  3633. }
  3634. if len(vmsg) > 0 {
  3635. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3636. } else {
  3637. appG.Response(http.StatusOK, e.SUCCESS, true)
  3638. }
  3639. } else {
  3640. msg := geterrmsg(err.Error())
  3641. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3642. }
  3643. }
  3644. }
  3645. if err != nil {
  3646. msg := geterrmsg(err.Error())
  3647. appG.Response(http.StatusOK, e.ERROR, msg)
  3648. }
  3649. }
  3650. 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) {
  3651. sqlname := fasion["name"].(string)
  3652. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3653. if v, ok := fasion["type"]; ok {
  3654. sqltype = v.(string)
  3655. }
  3656. sql := ""
  3657. p := ""
  3658. s_params := make([]interface{}, 0)
  3659. if sqltype != "" {
  3660. sql, p = restful.GetSqlByName(sqlname, tx)
  3661. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3662. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3663. paramslist := strings.Split(p, ",")
  3664. if len(paramslist) > 0 && p != "" {
  3665. for _, value := range paramslist {
  3666. ss := ""
  3667. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3668. ids, err := setting.SnowIds.NextId()
  3669. if err != nil {
  3670. ids = time.Now().UnixNano()
  3671. logging.Info("create SnowIds err", err)
  3672. }
  3673. s_params = append(s_params, ids)
  3674. } else {
  3675. if ss == "" && CommonParamMap != nil {
  3676. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3677. ss = valuestring
  3678. tempstrb := strings.IndexAny(valuestring, "@")
  3679. tempstre := strings.IndexAny(valuestring, ".")
  3680. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3681. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3682. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3683. }
  3684. } else {
  3685. ss = ""
  3686. }
  3687. }
  3688. }
  3689. if ss == "" && ParentParamMap != nil {
  3690. ss = getParamValue_(v, value, ParentParamMap)
  3691. }
  3692. if ss == "" && sameParamMap != nil {
  3693. ss = getParamValue(v, value, sameParamMap)
  3694. }
  3695. if ss == "" && ParamMap != nil {
  3696. ss = getParamValue(v, value, ParamMap)
  3697. }
  3698. s_params = append(s_params, ss)
  3699. }
  3700. }
  3701. }
  3702. }
  3703. }
  3704. if sql == "" {
  3705. sqltype = ""
  3706. }
  3707. if sql != "" {
  3708. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3709. if err != nil {
  3710. return nil, err
  3711. }
  3712. // fmt.Println(tempValParam)
  3713. return tempValParam.(map[string]interface{}), nil
  3714. } else {
  3715. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3716. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3717. if err != nil {
  3718. return nil, err
  3719. }
  3720. return nil, err
  3721. }
  3722. }
  3723. return nil, nil
  3724. }
  3725. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3726. var err error
  3727. subarray, ok := fasion["children"]
  3728. if ok {
  3729. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3730. tempVal_arrary := make([]map[string]interface{}, 0)
  3731. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3732. tempVal_ := make(map[string]interface{})
  3733. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3734. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3735. } else {
  3736. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3737. }
  3738. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3739. if err != nil {
  3740. return err
  3741. }
  3742. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3743. }
  3744. v.(map[string]interface{})["children"] = tempVal_arrary
  3745. }
  3746. }
  3747. return nil
  3748. }
  3749. func FpdImportExcel(c *gin.Context) {
  3750. appG := app.Gin{C: c}
  3751. inputdata := ""
  3752. c.Request.ParseForm()
  3753. params := c.Request.Form
  3754. file, _, err := c.Request.FormFile("file")
  3755. if err != nil {
  3756. appG.Response(http.StatusOK, e.ERROR, err)
  3757. return
  3758. }
  3759. sqlnamestrs := params.Get("name")
  3760. sheetname := params.Get("sheetname")
  3761. pastureid := params.Get("pastureid")
  3762. // importParams := params.Get("importParams")
  3763. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3764. // 必输项参数 (字符串格式 "field1,field2,field3")
  3765. requiredParams := params.Get("requiredParams")
  3766. // 日期参数
  3767. dateParams := params.Get("dateParams")
  3768. // 数字参数
  3769. numParams := params.Get("numParams")
  3770. //将字符串分割开
  3771. dateParamslist := strings.Split(dateParams, ",")
  3772. requiredParamslist := strings.Split(requiredParams, ",")
  3773. numParamslist := strings.Split(numParams, ",")
  3774. queryData := make([]interface{}, 0)
  3775. sqlslist := strings.Split(sqlnamestrs, ",")
  3776. xlsx1, err := excelize.OpenReader(file)
  3777. if err != nil {
  3778. fmt.Println(err)
  3779. return
  3780. }
  3781. ok := 0
  3782. error := 0
  3783. isdone := true
  3784. tx := restful.Engine.NewSession()
  3785. defer tx.Close()
  3786. 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
  3787. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3788. if err != nil {
  3789. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3790. return
  3791. }
  3792. rows := xlsx1.GetRows(sheetname)
  3793. // 限制10000条,多余的截取掉
  3794. if len(rows) > 10000 {
  3795. rows = rows[:10000]
  3796. }
  3797. for i, row := range rows {
  3798. if i > 0 {
  3799. entry := make(map[string]interface{})
  3800. outentry := make(map[string]interface{})
  3801. for j, colCell := range rows[0] {
  3802. for k, colCell1 := range row {
  3803. if j == k {
  3804. outentry[colCell] = colCell1
  3805. entry[colCell] = colCell1
  3806. }
  3807. }
  3808. }
  3809. inputdata = ""
  3810. a := ""
  3811. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3812. //校验日期格式
  3813. for _, v := range dateParamslist {
  3814. if v == "" {
  3815. continue
  3816. }
  3817. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3818. dtime, err := TransfTime(d.(string))
  3819. if err != nil {
  3820. a = strings.Trim(v, " ")
  3821. break
  3822. }
  3823. outentry[strings.Trim(v, " ")] = dtime
  3824. }
  3825. }
  3826. if a != "" {
  3827. outentry["error_msg"] = a + " 格式错误"
  3828. error++
  3829. queryData = append(queryData, outentry)
  3830. continue
  3831. }
  3832. a = ""
  3833. //校验必填格式
  3834. for _, v := range requiredParamslist {
  3835. if v == "" {
  3836. continue
  3837. }
  3838. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3839. a = strings.Trim(v, " ")
  3840. break
  3841. }
  3842. }
  3843. if a != "" {
  3844. outentry["error_msg"] = a + " 未填或格式错误"
  3845. error++
  3846. queryData = append(queryData, outentry)
  3847. continue
  3848. }
  3849. a = ""
  3850. //校验数字格式
  3851. for _, v := range numParamslist {
  3852. if v == "" {
  3853. continue
  3854. }
  3855. d, ok := outentry[strings.Trim(v, " ")]
  3856. if !ok || d == "" {
  3857. outentry[strings.Trim(v, " ")] = 0
  3858. } else {
  3859. var fl float64
  3860. switch d.(type) {
  3861. case string:
  3862. fl, err = strconv.ParseFloat(d.(string), 64)
  3863. }
  3864. if err != nil || fl < 0 {
  3865. a = strings.Trim(v, " ")
  3866. break
  3867. }
  3868. }
  3869. }
  3870. if a != "" {
  3871. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3872. error++
  3873. queryData = append(queryData, outentry)
  3874. continue
  3875. }
  3876. errExist := false
  3877. for _, sqlnamestr := range sqlslist {
  3878. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3879. paramslist := strings.Split(paramslists, ",")
  3880. if len(paramslist) > 0 {
  3881. s_params := make([]interface{}, 0)
  3882. for _, value := range paramslist {
  3883. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3884. if tempv, exists := c.Get("jwt_username"); exists {
  3885. s_params = append(s_params, tempv.(string))
  3886. } else {
  3887. s_params = append(s_params, "")
  3888. }
  3889. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3890. s_params = append(s_params, pastureid)
  3891. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3892. ids, err := setting.SnowIds.NextId()
  3893. if err != nil {
  3894. ids = time.Now().UnixNano()
  3895. logging.Info("create SnowIds err", err)
  3896. }
  3897. s_params = append(s_params, ids)
  3898. } else {
  3899. if outentry[strings.Trim(value, " ")] == nil {
  3900. s_params = append(s_params, "")
  3901. } else {
  3902. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3903. }
  3904. }
  3905. }
  3906. outentry["input"] = inputdata
  3907. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3908. if err != nil {
  3909. errExist = true
  3910. // if tx != nil {
  3911. // tx.Rollback()
  3912. // }
  3913. // if tx != nil {
  3914. // tx.Close()
  3915. // }
  3916. msg := geterrmsg(err.Error())
  3917. outentry["error_msg"] = msg
  3918. error++
  3919. queryData = append(queryData, outentry)
  3920. isdone = true
  3921. break
  3922. } else {
  3923. if len(returnmsgmap1) > 0 {
  3924. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3925. // if tx != nil {
  3926. // tx.Rollback()
  3927. // }
  3928. // if tx != nil {
  3929. // tx.Close()
  3930. // }
  3931. msg := geterrmsg(va.(string))
  3932. outentry["error_msg"] = msg
  3933. error++
  3934. queryData = append(queryData, outentry)
  3935. isdone = true
  3936. break
  3937. }
  3938. }
  3939. isdone = false
  3940. }
  3941. }
  3942. }
  3943. if !errExist {
  3944. dataexcel := make(map[string]interface{}, 0)
  3945. if _, ok := outentry["栏舍名称"]; ok {
  3946. dataexcel["barname"] = outentry["栏舍名称"]
  3947. }
  3948. if _, ok := outentry["实际牛头数"]; ok {
  3949. dataexcel["ccount"] = outentry["实际牛头数"]
  3950. }
  3951. if _, ok := outentry["系数(%)"]; ok {
  3952. dataexcel["ratio"] = outentry["系数(%)"]
  3953. }
  3954. if _, ok := outentry["配方模板"]; ok {
  3955. dataexcel["ftname"] = outentry["配方模板"]
  3956. }
  3957. if _, ok := outentry["补料配方"]; ok {
  3958. dataexcel["ptsfname"] = outentry["补料配方"]
  3959. }
  3960. if _, ok := outentry["第一班比例(%)"]; ok {
  3961. dataexcel["1"] = outentry["第一班比例(%)"]
  3962. }
  3963. if _, ok := outentry["第二班比例(%)"]; ok {
  3964. dataexcel["2"] = outentry["第二班比例(%)"]
  3965. }
  3966. if _, ok := outentry["第三班比例(%)"]; ok {
  3967. dataexcel["3"] = outentry["第三班比例(%)"]
  3968. }
  3969. if _, ok := outentry["第四班比例(%)"]; ok {
  3970. dataexcel["4"] = outentry["第四班比例(%)"]
  3971. }
  3972. if _, ok := outentry["第五班比例(%)"]; ok {
  3973. dataexcel["5"] = outentry["第四班比例(%)"]
  3974. }
  3975. if _, ok := outentry["第六班比例(%)"]; ok {
  3976. dataexcel["6"] = outentry["第六班比例(%)"]
  3977. }
  3978. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3979. if err != nil {
  3980. logs.Error(err)
  3981. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3982. return
  3983. }
  3984. if !existbar {
  3985. continue
  3986. }
  3987. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  3988. if err != nil {
  3989. logs.Error(err)
  3990. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3991. return
  3992. }
  3993. if !ftexist {
  3994. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  3995. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3996. if err != nil {
  3997. logs.Error(err)
  3998. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3999. return
  4000. }
  4001. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4002. if err != nil {
  4003. logs.Error(err)
  4004. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4005. return
  4006. }
  4007. }
  4008. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4009. if err != nil {
  4010. logs.Error(err)
  4011. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4012. return
  4013. }
  4014. if !exist {
  4015. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4016. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4017. if err != nil {
  4018. logs.Error(err)
  4019. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4020. return
  4021. }
  4022. }
  4023. var feedpargs []interface{}
  4024. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4025. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4026. if _, ok := dataexcel["ftname"]; ok {
  4027. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4028. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4029. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4030. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4031. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4032. } else {
  4033. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4034. }
  4035. if _, ok := dataexcel["ptsfname"]; ok {
  4036. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4037. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4038. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4039. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4040. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4041. } else {
  4042. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4043. }
  4044. upFeedpSql += " where barname = ? and pastureid = ? "
  4045. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4046. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4047. if err != nil {
  4048. logs.Error(err)
  4049. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4050. return
  4051. }
  4052. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4053. if err != nil {
  4054. logs.Error(err)
  4055. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4056. return
  4057. }
  4058. if !exist1 {
  4059. _, 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) `,
  4060. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4061. if err != nil {
  4062. logs.Error(err)
  4063. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4064. return
  4065. }
  4066. }
  4067. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4068. if err != nil {
  4069. logs.Error(err)
  4070. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4071. return
  4072. }
  4073. if !exist2 {
  4074. _, 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) `,
  4075. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4076. if err != nil {
  4077. logs.Error(err)
  4078. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4079. return
  4080. }
  4081. }
  4082. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4083. if err != nil {
  4084. logs.Error(err)
  4085. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4086. return
  4087. }
  4088. if !exist3 {
  4089. _, 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) `,
  4090. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4091. if err != nil {
  4092. logs.Error(err)
  4093. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4094. return
  4095. }
  4096. }
  4097. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4098. if err != nil {
  4099. logs.Error(err)
  4100. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4101. return
  4102. }
  4103. if !exist4 {
  4104. _, 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) `,
  4105. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4106. if err != nil {
  4107. logs.Error(err)
  4108. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4109. return
  4110. }
  4111. }
  4112. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4113. if err != nil {
  4114. logs.Error(err)
  4115. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4116. return
  4117. }
  4118. if !exist5 {
  4119. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  4120. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4121. if err != nil {
  4122. logs.Error(err)
  4123. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4124. return
  4125. }
  4126. }
  4127. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4128. if err != nil {
  4129. logs.Error(err)
  4130. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4131. return
  4132. }
  4133. if !exist6 {
  4134. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  4135. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4136. if err != nil {
  4137. logs.Error(err)
  4138. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4139. return
  4140. }
  4141. }
  4142. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4143. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4144. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4145. and pastureid = ? and times = ?`
  4146. var fpdargs1 []interface{}
  4147. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4148. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4149. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4150. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4151. if err != nil {
  4152. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4153. return
  4154. }
  4155. var fpdargs2 []interface{}
  4156. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4157. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4158. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4159. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4160. if err != nil {
  4161. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4162. return
  4163. }
  4164. var fpdargs3 []interface{}
  4165. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4166. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4167. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4168. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4169. if err != nil {
  4170. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4171. return
  4172. }
  4173. var fpdargs4 []interface{}
  4174. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4175. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4176. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4177. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4178. if err != nil {
  4179. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4180. return
  4181. }
  4182. var fpdargs5 []interface{}
  4183. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4184. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4185. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4186. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4187. if err != nil {
  4188. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4189. return
  4190. }
  4191. var fpdargs6 []interface{}
  4192. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4193. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4194. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4195. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4196. if err != nil {
  4197. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4198. return
  4199. }
  4200. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4201. 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()
  4202. if err != nil {
  4203. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4204. return
  4205. }
  4206. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4207. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4208. upFpdetailList := make([]*upFpdetail, 0)
  4209. for _, newfpd := range newList {
  4210. for _, oldfpd := range oldFpdList {
  4211. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4212. var oldweight, newweight float64
  4213. if oldfpd["weight"] != nil {
  4214. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4215. }
  4216. if newfpd["weight"] != nil {
  4217. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4218. }
  4219. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4220. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4221. Old: oldweight,
  4222. New: newweight,
  4223. Times: newfpd["times"].(int64),
  4224. Ptid: newfpd["ptid"].(int64),
  4225. Fweight: fweight,
  4226. Id: oldfpd["id"].(int64),
  4227. })
  4228. break
  4229. }
  4230. }
  4231. }
  4232. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4233. }
  4234. }
  4235. if !isdone {
  4236. ok++
  4237. isdone = true
  4238. }
  4239. }
  4240. data := make(map[string]interface{})
  4241. data["result"] = queryData
  4242. data["success"] = ok
  4243. data["err_count"] = error
  4244. appG.Response(http.StatusOK, e.SUCCESS, data)
  4245. }
  4246. type upFpdetail struct {
  4247. Old float64
  4248. New float64
  4249. Times int64
  4250. Ptid int64
  4251. Fweight float64
  4252. Id int64
  4253. // Ptsid string
  4254. }
  4255. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4256. tx := restful.Engine.NewSession()
  4257. defer tx.Close()
  4258. tx.Begin()
  4259. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ifnull(ptsrate,0))*weight,2),"") weight,ptuse,times from fpdetail where pastureid = ? and barname = ? order by times `,
  4260. pastureid, barname).Query().List()
  4261. if err != nil {
  4262. logs.Error(err)
  4263. }
  4264. for _, fpd := range fpdList {
  4265. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4266. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4267. pastureid, fpd["id"], fpd["times"]).Query().List()
  4268. if err != nil {
  4269. tx.Rollback()
  4270. logs.Error(err)
  4271. return err
  4272. }
  4273. var lweight float64
  4274. for _, lppland := range lpplandList {
  4275. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4276. lweight += lweight1
  4277. }
  4278. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4279. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4280. if fpdweight >= ptuse && lweight == ptuse {
  4281. continue
  4282. } else {
  4283. if lweight <= fpdweight {
  4284. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4285. if err != nil {
  4286. tx.Rollback()
  4287. logs.Error(err)
  4288. return err
  4289. }
  4290. } else {
  4291. weight := lweight - fpdweight
  4292. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4293. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4294. if err != nil {
  4295. tx.Rollback()
  4296. logs.Error(err)
  4297. return err
  4298. }
  4299. for _, lppland := range lpplandList {
  4300. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4301. if weight >= lpplandlweight {
  4302. weight = weight - lpplandlweight
  4303. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4304. if err != nil {
  4305. tx.Rollback()
  4306. logs.Error(err)
  4307. return err
  4308. }
  4309. } else {
  4310. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4311. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4312. if err != nil {
  4313. tx.Rollback()
  4314. logs.Error(err)
  4315. return err
  4316. }
  4317. weight = 0
  4318. break
  4319. }
  4320. }
  4321. }
  4322. }
  4323. }
  4324. for _, list := range dataList {
  4325. ftmap := make(map[string]interface{})
  4326. ftmap["old"] = list.Old
  4327. ftmap["new"] = list.New
  4328. ftmap["times"] = list.Times
  4329. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4330. ftmap["ptsid"] = ""
  4331. // fmt.Println(ftmap)
  4332. 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 ,
  4333. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4334. WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4335. UNION
  4336. 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 ,
  4337. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4338. WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  4339. order by t.barname,t.times`, pastureid, barname, ftmap["times"], pastureid, barname, ftmap["times"]).Query().List()
  4340. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4341. if err != nil {
  4342. tx.Rollback()
  4343. logs.Error(err)
  4344. }
  4345. for _, fpd := range fpdDataList {
  4346. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4347. fttype := -1
  4348. if ftmap["ptid"].(string) != "-1" {
  4349. fttype = 1
  4350. }
  4351. var fweight float64
  4352. var lweight float64
  4353. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4354. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4355. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4356. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4357. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4358. if err != nil {
  4359. tx.Rollback()
  4360. logs.Error(err)
  4361. }
  4362. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4363. // ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4364. var w float64
  4365. var status int
  4366. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  4367. if weight >= 0 {
  4368. continue
  4369. }
  4370. w = weight
  4371. status = 0
  4372. } else {
  4373. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4374. continue
  4375. }
  4376. w = weight
  4377. status = 1
  4378. }
  4379. for _, lppland := range lpplandtl1List {
  4380. lweight += lppland.Lweight
  4381. }
  4382. for _, lppland := range lpplandtl1List {
  4383. if status == 1 {
  4384. // if w <= lppland.Lweight {
  4385. if lppland.Maxweight <= lweight {
  4386. continue
  4387. }
  4388. if w+lweight <= lppland.Maxweight {
  4389. lppland.Lweight += w
  4390. lweight += w
  4391. fweight += w
  4392. w = 0
  4393. } else {
  4394. w = w - (lppland.Maxweight - lweight)
  4395. n := (lppland.Maxweight - lweight)
  4396. lppland.Lweight = lppland.Lweight + n
  4397. lweight += n
  4398. fweight += n
  4399. }
  4400. } else {
  4401. if lppland.Lweight == 0 {
  4402. continue
  4403. }
  4404. if w+lppland.Lweight >= 0 {
  4405. lppland.Lweight = lppland.Lweight + w
  4406. lweight = lweight + w
  4407. fweight = fweight + w
  4408. w = 0
  4409. } else {
  4410. w = w + lppland.Lweight
  4411. lweight = lweight - lppland.Lweight
  4412. fweight = fweight - lppland.Lweight
  4413. lppland.Lweight = 0
  4414. }
  4415. }
  4416. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4417. if err != nil {
  4418. tx.Rollback()
  4419. logs.Error(err)
  4420. return err
  4421. }
  4422. break
  4423. }
  4424. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4425. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4426. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4427. if err != nil {
  4428. tx.Rollback()
  4429. logs.Error(err)
  4430. }
  4431. if w == 0 {
  4432. break
  4433. }
  4434. }
  4435. }
  4436. }
  4437. // for _, data := range dataList {
  4438. // fttype := -1
  4439. // if data.Ptid != -1 {
  4440. // fttype = 1
  4441. // }
  4442. // var fweight float64
  4443. // var lweight float64
  4444. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4445. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4446. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4447. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4448. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4449. // if err != nil {
  4450. // tx.Rollback()
  4451. // logs.Error(err)
  4452. // return err
  4453. // }
  4454. // weight := data.Fweight
  4455. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4456. // var w float64
  4457. // var status int
  4458. // if data.New < data.Old {
  4459. // if weight >= 0 {
  4460. // continue
  4461. // }
  4462. // w = weight
  4463. // status = 0
  4464. // } else {
  4465. // // if weight-(data.New-data.Old) > 0 {
  4466. // // continue
  4467. // // }
  4468. // w = data.New - data.Old
  4469. // status = 1
  4470. // }
  4471. // for _, lppland := range lpplandtl1List {
  4472. // var lppdata lpplandtlInfo
  4473. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4474. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4475. // if err != nil {
  4476. // tx.Rollback()
  4477. // logs.Error(err)
  4478. // return err
  4479. // }
  4480. // lweight = lppdata.Lweight
  4481. // if status == 1 {
  4482. // // if w <= lppland.Lweight {
  4483. // if lppland.Maxweight <= lweight {
  4484. // continue
  4485. // }
  4486. // if w+lweight <= lppland.Maxweight {
  4487. // lppland.Lweight += w
  4488. // lweight += w
  4489. // fweight += w
  4490. // w = 0
  4491. // } else {
  4492. // w = w - (lppland.Maxweight - lweight)
  4493. // n := (lppland.Maxweight - lweight)
  4494. // lppland.Lweight = lppland.Lweight + n
  4495. // lweight += n
  4496. // fweight += n
  4497. // }
  4498. // } else {
  4499. // if lppland.Lweight == 0 {
  4500. // continue
  4501. // }
  4502. // if w+lppland.Lweight >= 0 {
  4503. // lppland.Lweight = lppland.Lweight + w
  4504. // lweight = lweight + w
  4505. // fweight = fweight + w
  4506. // w = 0
  4507. // } else {
  4508. // w = w + lppland.Lweight
  4509. // lweight = lweight - lppland.Lweight
  4510. // fweight = fweight - lppland.Lweight
  4511. // lppland.Lweight = 0
  4512. // }
  4513. // }
  4514. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4515. // if err != nil {
  4516. // tx.Rollback()
  4517. // logs.Error(err)
  4518. // return err
  4519. // }
  4520. // break
  4521. // }
  4522. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4523. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4524. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4525. // if err != nil {
  4526. // tx.Rollback()
  4527. // logs.Error(err)
  4528. // return err
  4529. // }
  4530. // // if w == 0 {
  4531. // // break
  4532. // // }
  4533. // // }
  4534. // }
  4535. err = tx.Commit()
  4536. if err != nil {
  4537. logs.Error(err)
  4538. tx.Rollback()
  4539. return err
  4540. }
  4541. now := time.Now()
  4542. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4543. if err != nil {
  4544. logs.Error(err)
  4545. return nil
  4546. }
  4547. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4548. if err != nil {
  4549. logs.Error(err)
  4550. return nil
  4551. }
  4552. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4553. if err != nil {
  4554. logs.Error(err)
  4555. return nil
  4556. }
  4557. for _, newLpplandtl1 := range newLpplandtl1List {
  4558. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4559. background,cowcount,ccountradio,lweighthis,createdate)
  4560. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4561. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4562. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4563. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4564. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4565. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4566. if err != nil {
  4567. logs.Error(err)
  4568. // appG.Response(http.StatusOK, e.ERROR, false)
  4569. return nil
  4570. }
  4571. }
  4572. for _, newFpd := range newFpdDataList {
  4573. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4574. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4575. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4576. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4577. if err != nil {
  4578. logs.Error(err)
  4579. // appG.Response(http.StatusOK, e.ERROR, false)
  4580. return nil
  4581. }
  4582. }
  4583. for _, newFeedp := range newFeedpList {
  4584. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4585. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4586. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4587. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4588. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4589. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4590. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4591. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4592. if err != nil {
  4593. logs.Error(err)
  4594. // appG.Response(http.StatusOK, e.ERROR, false)
  4595. return nil
  4596. }
  4597. }
  4598. return nil
  4599. }
  4600. func DeleteFTdetail(c *gin.Context) {
  4601. appG := app.Gin{C: c}
  4602. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4603. fsion := gofasion.NewFasion(string(dataByte))
  4604. parammaps := fsion.Get("parammaps")
  4605. pastureid := parammaps.Get("pastureid").ValueStr()
  4606. ftid := parammaps.Get("ftid").ValueStr()
  4607. tx := restful.Engine.NewSession()
  4608. defer tx.Close()
  4609. tx.Begin()
  4610. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4611. if err != nil {
  4612. tx.Rollback()
  4613. logs.Error(err)
  4614. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4615. return
  4616. }
  4617. if parammaps.Get("type").ValueStr() == "1" {
  4618. _, err := tx.SQL(`UPDATE feedp fp
  4619. set
  4620. fp.ftweight= IFNULL(IF(
  4621. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4622. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4623. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4624. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4625. ),0),fp.feedweight = IFNULL(IF(
  4626. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4627. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4629. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4630. ),0) +ifnull(fp.supplyweight,0)
  4631. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4632. if err != nil {
  4633. tx.Rollback()
  4634. logs.Error(err)
  4635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4636. return
  4637. }
  4638. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4639. _, err = tx.SQL(`
  4640. UPDATE fpdetail fpd
  4641. INNER JOIN feedp fp
  4642. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4643. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4644. ptuse= 0
  4645. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4646. if err != nil {
  4647. tx.Rollback()
  4648. logs.Error(err)
  4649. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4650. return
  4651. }
  4652. } else {
  4653. _, err := tx.SQL(`UPDATE feedp fp
  4654. SET
  4655. fp.supplyweight= IFNULL(IF(
  4656. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4657. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4658. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4659. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4660. ),0),fp.feedweight = IFNULL(IF(
  4661. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4662. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4663. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4664. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4665. ),0) + ifnull(fp.supplyweight,0)
  4666. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4667. if err != nil {
  4668. tx.Rollback()
  4669. logs.Error(err)
  4670. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4671. return
  4672. }
  4673. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4674. _, err = tx.SQL(`
  4675. UPDATE fpdetail fpd
  4676. INNER JOIN feedp fp
  4677. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4678. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4679. ptsrate = 0
  4680. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4681. if err != nil {
  4682. tx.Rollback()
  4683. logs.Error(err)
  4684. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4685. return
  4686. }
  4687. }
  4688. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4689. if err != nil {
  4690. tx.Rollback()
  4691. logs.Error(err)
  4692. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4693. return
  4694. }
  4695. err = tx.Commit()
  4696. if err != nil {
  4697. tx.Rollback()
  4698. logs.Error(err)
  4699. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4700. return
  4701. }
  4702. appG.Response(http.StatusOK, e.SUCCESS, true)
  4703. }
  4704. func DeleteSpillageAll(c *gin.Context) {
  4705. appG := app.Gin{C: c}
  4706. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4707. fsion := gofasion.NewFasion(string(dataByte))
  4708. parammaps := fsion.Get("parammaps")
  4709. pastureid := parammaps.Get("pastureid").ValueStr()
  4710. times := parammaps.Get("times").ValueStr()
  4711. barid := parammaps.Get("barid").ValueStr()
  4712. tx := restful.Engine.NewSession()
  4713. defer tx.Close()
  4714. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4715. if err != nil {
  4716. logs.Error(err)
  4717. appG.Response(http.StatusOK, e.ERROR, false)
  4718. return
  4719. }
  4720. now := time.Now()
  4721. for _, item := range lpplandtl1List {
  4722. go func(item map[string]interface{}) {
  4723. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4724. background,cowcount,ccountradio,lweighthis,createdate)
  4725. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4726. item["pastureid"], item["lppid"], item["barid"],
  4727. item["barname"], item["fpdid"], item["fttype"],
  4728. item["lweight"], item["sort"], item["tmrid"],
  4729. item["tmrname"], item["background"], item["cowcount"],
  4730. item["ccountradio"], item["lweighthis"], now).Execute()
  4731. if err != nil {
  4732. logs.Error(err)
  4733. appG.Response(http.StatusOK, e.ERROR, false)
  4734. return
  4735. }
  4736. }(item)
  4737. }
  4738. tx.Begin()
  4739. _, 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()
  4740. if err != nil {
  4741. tx.Rollback()
  4742. logs.Error(err)
  4743. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4744. return
  4745. }
  4746. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4747. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4748. if err != nil {
  4749. tx.Rollback()
  4750. logs.Error(err)
  4751. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4752. return
  4753. }
  4754. err = tx.Commit()
  4755. if err != nil {
  4756. tx.Rollback()
  4757. logs.Error(err)
  4758. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4759. return
  4760. }
  4761. appG.Response(http.StatusOK, e.SUCCESS, true)
  4762. }
  4763. func GetTMRListEnableTypeAll(c *gin.Context) {
  4764. appG := app.Gin{C: c}
  4765. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4766. fsion := gofasion.NewFasion(string(dataByte))
  4767. parammaps := fsion.Get("parammaps")
  4768. pastureid := parammaps.Get("pastureid").ValueStr()
  4769. tx := restful.Engine.NewSession()
  4770. defer tx.Close()
  4771. dataList, err := tx.SQL(`SELECT
  4772. eqcode,
  4773. tname,
  4774. datacaptureno,
  4775. trim(tclassid) tclassid,
  4776. concat(tname,' / ',eqcode) tmrmix,
  4777. d.label tclassname,
  4778. maxstirfeed,
  4779. remark,
  4780. tmr.enable,
  4781. TRIM(tmr.id) id,
  4782. TRIM(tmr.pastureid)pastureid
  4783. FROM
  4784. tmr
  4785. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4786. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4787. ORDER BY id DESC`, pastureid).Query().List()
  4788. if err != nil {
  4789. logs.Error(err)
  4790. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4791. return
  4792. }
  4793. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4794. if err != nil {
  4795. logs.Error(err)
  4796. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4797. return
  4798. }
  4799. var carNum int64
  4800. for _, sysopt := range sysoptData {
  4801. if sysopt["inforvalue"] == nil {
  4802. carNum = 1
  4803. } else {
  4804. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4805. }
  4806. }
  4807. id := 200
  4808. n := 0
  4809. for i := carNum; i > 0; i-- {
  4810. id++
  4811. n++
  4812. data := make(map[string]interface{}, 0)
  4813. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4814. data["tname"] = fmt.Sprintf("任意车%d", n)
  4815. data["datacaptureno"] = -2
  4816. data["tclassid"] = -2
  4817. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4818. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4819. data["maxstirfeed"] = 100000
  4820. data["remark"] = fmt.Sprintf("任意车%d", n)
  4821. data["enable"] = 1
  4822. data["id"] = fmt.Sprintf("%d", id)
  4823. data["pastureid"] = pastureid
  4824. dataList = append(dataList, data)
  4825. }
  4826. // UNION ALL
  4827. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4828. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4829. }
  4830. func GetFeedpHistory(c *gin.Context) {
  4831. appG := app.Gin{C: c}
  4832. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4833. fsion := gofasion.NewFasion(string(dataByte))
  4834. // parammaps := fsion.Get("parammaps")
  4835. bar := fsion.Get("barname").ValueStr()
  4836. startDate := fsion.Get("startDate").ValueStr()
  4837. endDate := fsion.Get("endDate").ValueStr()
  4838. tx := restful.Engine.NewSession()
  4839. defer tx.Close()
  4840. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4841. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  4842. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4843. if err != nil {
  4844. logs.Error(err)
  4845. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4846. return
  4847. }
  4848. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  4849. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  4850. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4851. if err != nil {
  4852. logs.Error(err)
  4853. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4854. return
  4855. }
  4856. for _, feedp := range feedpList {
  4857. // LastftList, err := tx.SQL(` select tname ,id
  4858. // from feedtemplethistory where id = ?
  4859. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4860. // if err != nil {
  4861. // logs.Error(err)
  4862. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4863. // return
  4864. // }
  4865. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4866. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4867. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4868. if err != nil {
  4869. logs.Error(err)
  4870. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4871. return
  4872. }
  4873. var ftname interface{}
  4874. ftnamestatus := 0
  4875. ftname = feedp["ftname"]
  4876. var lastftid int64
  4877. if len(nextfeedpList) > 0 {
  4878. for _, ft := range nextfeedpList {
  4879. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4880. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4881. lastftid = ft["ftid"].(int64)
  4882. ftnamestatus = 1
  4883. break
  4884. }
  4885. }
  4886. }
  4887. for i, fpd := range fpdList {
  4888. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4889. fpd["weightstatus"] = 0
  4890. fpd["tratiostatus"] = 0
  4891. fpd["ftnamestatus"] = ftnamestatus
  4892. for k, fpd2 := range fpdList {
  4893. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4894. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4895. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4896. fpd["weightstatus"] = 1
  4897. }
  4898. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4899. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4900. fpd["tratiostatus"] = 1
  4901. }
  4902. break
  4903. }
  4904. }
  4905. fpd["barid"] = feedp["barid"]
  4906. fpd["barname"] = feedp["barname"]
  4907. fpd["ccount"] = feedp["ccount"]
  4908. fpd["ratio"] = feedp["ratio"]
  4909. fpd["ccountratio"] = feedp["ccountratio"]
  4910. fpd["ftid"] = feedp["ftid"]
  4911. fpd["ftname"] = ftname
  4912. fpd["ccountstatus"] = 0
  4913. fpd["ccountratiostatus"] = 0
  4914. fpd["ratiostatus"] = 0
  4915. fpd["ftnamestatus"] = 0
  4916. fpd["lastftid"] = lastftid
  4917. for _, next := range nextfeedpList {
  4918. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4919. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4920. fpd["ccountstatus"] = 1
  4921. }
  4922. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4923. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4924. fpd["ccountratiostatus"] = 1
  4925. }
  4926. if next["ratio"].(string) != fpd["ratio"].(string) {
  4927. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4928. fpd["ratiostatus"] = 1
  4929. }
  4930. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4931. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4932. // fpd["ftnamestatus"] = 1
  4933. // }
  4934. }
  4935. }
  4936. }
  4937. }
  4938. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4939. }
  4940. // func GetLpplandtl1History(c *gin.Context) {
  4941. // appG := app.Gin{C: c}
  4942. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4943. // fsion := gofasion.NewFasion(string(dataByte))
  4944. // // parammaps := fsion.Get("parammaps")
  4945. // barid := fsion.Get("barid").ValueStr()
  4946. // startDate := fsion.Get("startDate").ValueStr()
  4947. // endDate := fsion.Get("endDate").ValueStr()
  4948. // tx := restful.Engine.NewSession()
  4949. // defer tx.Close()
  4950. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4951. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4952. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4953. // // if err != nil {
  4954. // // logs.Error(err)
  4955. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4956. // // return
  4957. // // }
  4958. // // for _, feedp := range feedpList {
  4959. // // fmt.Println(feedp)
  4960. // // for i, fpd := range fpdList {
  4961. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4962. // // for k, fpd2 := range fpdList {
  4963. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4964. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4965. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4966. // // }
  4967. // // break
  4968. // // }
  4969. // // }
  4970. // // fpd["barid"] = feedp["barid"]
  4971. // // fpd["barname"] = feedp["barname"]
  4972. // // fpd["ccount"] = feedp["ccount"]
  4973. // // fpd["ratio"] = feedp["ratio"]
  4974. // // fpd["ccountratio"] = feedp["ccountratio"]
  4975. // // fpd["ftid"] = feedp["ftid"]
  4976. // // fpd["ftname"] = feedp["ftname"]
  4977. // // }
  4978. // // }
  4979. // // }
  4980. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4981. // }
  4982. func GetRemind(c *gin.Context) {
  4983. appG := app.Gin{C: c}
  4984. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4985. fsion := gofasion.NewFasion(string(dataByte))
  4986. parammaps := fsion.Get("parammaps")
  4987. pastureid := parammaps.Get("pastureid").ValueStr()
  4988. tx := restful.Engine.NewSession()
  4989. defer tx.Close()
  4990. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4991. if err != nil {
  4992. logs.Error(err)
  4993. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4994. return
  4995. }
  4996. // pastureid = "3"
  4997. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  4998. if err != nil {
  4999. logs.Error(err)
  5000. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5001. return
  5002. }
  5003. defer resp.Body.Close()
  5004. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5005. buf.ReadFrom(resp.Body)
  5006. fmt.Println(string(buf.Bytes()))
  5007. respMap := make(map[string]interface{}, 0)
  5008. err = json.Unmarshal(buf.Bytes(), &respMap)
  5009. if err != nil {
  5010. logs.Error(err)
  5011. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5012. return
  5013. }
  5014. for _, data := range dataList {
  5015. r := make(map[string]interface{}, 0)
  5016. r["sys_name"] = ""
  5017. r["service_id"] = ""
  5018. r["pasture_id"] = ""
  5019. r["type_name"] = ""
  5020. r["remind_type_id"] = ""
  5021. r["remind_type"] = ""
  5022. r["push_date"] = ""
  5023. r["push_time"] = ""
  5024. r["interval_time"] = ""
  5025. r["push_limit"] = ""
  5026. r["template_id"] = ""
  5027. r["roles_id"] = ""
  5028. r["users_id"] = ""
  5029. r["date_type"] = ""
  5030. r["cycle_type"] = ""
  5031. data["data"] = r
  5032. for _, resp := range respMap["data"].([]interface{}) {
  5033. resp1 := resp.(map[string]interface{})
  5034. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5035. if resp1["push_time"] == nil {
  5036. resp1["push_time"] = ""
  5037. }
  5038. data["data"] = resp1
  5039. break
  5040. }
  5041. }
  5042. }
  5043. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5044. }
  5045. type NoticeMsgtype struct {
  5046. SysName string `json:"sys_name"`
  5047. PastureId int64 `json:"pasture_id"`
  5048. ServiceId int64 `json:"service_id"`
  5049. TypeName string `json:"type_name"`
  5050. RemindType int64 `json:"remind_type"`
  5051. PushDate int64 `json:"push_date"`
  5052. PushTime string `json:"push_time"`
  5053. IntervalTime int64 `json:"interval_time"`
  5054. PushLimit int64 `json:"push_limit"`
  5055. TemplateId string `json:"template_id"`
  5056. UsersId string `json:"users_id"`
  5057. DateType int64 `json:"date_type"`
  5058. CycleType int64 `json:"cycle_type"`
  5059. DelayTime int64 `json:"delay_time"`
  5060. Status int64 `json:"status"`
  5061. }
  5062. func UpdateRemind(c *gin.Context) {
  5063. appG := app.Gin{C: c}
  5064. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5065. parammaps := gofasion.NewFasion(string(dataByte))
  5066. // parammaps := fsion.Get("parammaps")
  5067. // user := parammaps.Get("user").ValueStr()
  5068. id := parammaps.Get("id").ValueInt64()
  5069. noticeMsgtype := new(NoticeMsgtype)
  5070. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5071. noticeMsgtype.ServiceId = id
  5072. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5073. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5074. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5075. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5076. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5077. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5078. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5079. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5080. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5081. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5082. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5083. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5084. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5085. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5086. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5087. //TODO
  5088. noticeMsgtype.SysName = "tmrWatch"
  5089. userList := parammaps.Get("user").Array()
  5090. var userstr []string
  5091. for _, user := range userList {
  5092. userstr = append(userstr, user.ValueStr())
  5093. }
  5094. tx := restful.Engine.NewSession()
  5095. defer tx.Close()
  5096. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5097. if err != nil {
  5098. logs.Error(err)
  5099. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5100. return
  5101. }
  5102. // var jsonStr = []byte(noticeMsgtype
  5103. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5104. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5105. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5106. req.Header.Set("Content-Type", "application/json")
  5107. client := &http.Client{}
  5108. resp, err := client.Do(req)
  5109. if err != nil {
  5110. logs.Error(err)
  5111. }
  5112. defer resp.Body.Close()
  5113. body, _ := ioutil.ReadAll(resp.Body)
  5114. fmt.Println("response Body:", string(body))
  5115. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5116. if err != nil {
  5117. logs.Error(err)
  5118. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5119. return
  5120. }
  5121. defer getresp.Body.Close()
  5122. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5123. buf.ReadFrom(getresp.Body)
  5124. // fmt.Println(string(buf.Bytes()))
  5125. respMap := make(map[string]interface{}, 0)
  5126. err = json.Unmarshal(buf.Bytes(), &respMap)
  5127. if err != nil {
  5128. logs.Error(err)
  5129. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5130. return
  5131. }
  5132. for _, resp := range respMap["data"].([]interface{}) {
  5133. resp1 := resp.(map[string]interface{})
  5134. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5135. if err != nil {
  5136. logs.Error(err)
  5137. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5138. return
  5139. }
  5140. }
  5141. appG.Response(http.StatusOK, e.SUCCESS, true)
  5142. }
  5143. func GetSpillageallHistory(c *gin.Context) {
  5144. appG := app.Gin{C: c}
  5145. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5146. parammaps := gofasion.NewFasion(string(dataByte))
  5147. barname := parammaps.Get("barname").ValueStr()
  5148. pastureid := parammaps.Get("pastureid").ValueStr()
  5149. startdate := parammaps.Get("startDate").ValueStr()
  5150. enddate := parammaps.Get("endDate").ValueStr()
  5151. tx := restful.Engine.NewSession()
  5152. defer tx.Close()
  5153. 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
  5154. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5155. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5156. if err != nil {
  5157. logs.Error(err)
  5158. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5159. return
  5160. }
  5161. respMap := make([]map[string]interface{}, 0)
  5162. data := make(map[interface{}]interface{})
  5163. for _, history := range historyList {
  5164. data[history["createdate"]] = history["createdate"]
  5165. }
  5166. createList := []string{}
  5167. for _, v := range data {
  5168. createList = append(createList, v.(string))
  5169. }
  5170. // sort.Sort()
  5171. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5172. sort.Slice(createList, func(i, j int) bool {
  5173. return createList[i] > createList[j]
  5174. })
  5175. for _, v := range createList {
  5176. a := make(map[string]interface{})
  5177. a["createdate"] = data[v]
  5178. // createList = append(createList, v.(string))
  5179. respMap = append(respMap, a)
  5180. }
  5181. number := 0
  5182. dataMap := make([]interface{}, 0)
  5183. for k, resp := range respMap {
  5184. createdate := resp["createdate"].(string)
  5185. var nextcreatedate string
  5186. if len(respMap) > k+1 {
  5187. nextcreatedate = respMap[k+1]["createdate"].(string)
  5188. }
  5189. // dataList := make(map[string][]interface{})
  5190. // list := make(map[string]interface{})
  5191. times := make(map[interface{}]int)
  5192. for _, history := range historyList {
  5193. // List := make(map[interface{}][]interface{})
  5194. i := 0
  5195. if history["createdate"].(string) == createdate {
  5196. times[history["times"]]++
  5197. data := make(map[string]interface{})
  5198. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5199. // exist := false
  5200. if nextcreatedate != "" {
  5201. for _, history1 := range historyList {
  5202. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5203. history1["times"].(int64) == history["times"].(int64) {
  5204. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  5205. break
  5206. // exist = true
  5207. }
  5208. }
  5209. }
  5210. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5211. i++
  5212. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5213. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5214. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5215. // resp["times"] = history["times"]
  5216. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5217. data1 := make(map[string]interface{})
  5218. data1["times"] = history["times"]
  5219. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5220. data1["createdate"] = resp["createdate"]
  5221. // fmt.Println(dataList)
  5222. dataMap = append(dataMap, data1)
  5223. }
  5224. if i > number {
  5225. number = i
  5226. }
  5227. // respMap = append(respMap, dataList)
  5228. }
  5229. // for k, data := range dataList {
  5230. // resp[k] = data
  5231. // }
  5232. // resp["data"] = dataList
  5233. }
  5234. // resp := make(map[string]interface{})
  5235. // sort.Strings(createList)
  5236. //
  5237. // for _, create := range createList {
  5238. // for _, r := range respMap {
  5239. // if create == r["createdate"].(string) {
  5240. // resp[create] = r
  5241. // break
  5242. // }
  5243. // }
  5244. // }
  5245. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5246. var trainsList []interface{}
  5247. for i := 0; i < number; i++ {
  5248. trains := make(map[string]interface{})
  5249. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5250. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5251. trainsList = append(trainsList, trains)
  5252. }
  5253. respdata := make(map[string]interface{})
  5254. respdata["data"] = dataMap
  5255. respdata["trains"] = trainsList
  5256. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5257. }
  5258. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5259. appG := app.Gin{C: c}
  5260. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5261. parammaps := gofasion.NewFasion(string(dataByte))
  5262. ftid := parammaps.Get("ftid").ValueInt64()
  5263. lastftid := parammaps.Get("lastftid").ValueInt64()
  5264. pastureid := parammaps.Get("pastureid").ValueInt64()
  5265. // createdate := parammaps.Get("createdate").ValueStr()
  5266. tx := restful.Engine.NewSession()
  5267. defer tx.Close()
  5268. data := make(map[string]interface{})
  5269. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5270. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5271. if err != nil {
  5272. logs.Error(err)
  5273. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5274. return
  5275. }
  5276. feedtemplet := make(map[string]interface{})
  5277. for _, f := range feedtempletList {
  5278. feedtemplet = f
  5279. }
  5280. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5281. if err != nil {
  5282. logs.Error(err)
  5283. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5284. return
  5285. }
  5286. feedtemplet["fit"] = fitList
  5287. data["current"] = feedtemplet
  5288. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5289. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5290. if err != nil {
  5291. logs.Error(err)
  5292. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5293. return
  5294. }
  5295. lastfeedtemplet := make(map[string]interface{})
  5296. for _, f := range lastfeedtempletList {
  5297. lastfeedtemplet = f
  5298. }
  5299. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5300. if err != nil {
  5301. logs.Error(err)
  5302. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5303. return
  5304. }
  5305. lastfeedtemplet["fit"] = lastfitList
  5306. data["last"] = lastfeedtemplet
  5307. appG.Response(http.StatusOK, e.SUCCESS, data)
  5308. }
  5309. func GetFeedtempletHistory(c *gin.Context) {
  5310. appG := app.Gin{C: c}
  5311. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5312. parammaps := gofasion.NewFasion(string(dataByte))
  5313. ftid := parammaps.Get("ftid").ValueStr()
  5314. pastureid := parammaps.Get("pastureid").ValueInt64()
  5315. start := parammaps.Get("startdate").ValueStr()
  5316. end := parammaps.Get("enddate").ValueStr()
  5317. tx := restful.Engine.NewSession()
  5318. defer tx.Close()
  5319. ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1,(select empname from user where id = feedtemplethistory.userId) empname from feedtemplethistory where createdate between ? and ?
  5320. and id = ? and pastureid = ? order by createdate desc `,
  5321. start, end, ftid, pastureid).Query().List()
  5322. if err != nil {
  5323. logs.Error(err)
  5324. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5325. return
  5326. }
  5327. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5328. ftid, pastureid).Query().List()
  5329. if err != nil {
  5330. logs.Error(err)
  5331. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5332. return
  5333. }
  5334. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5335. for i, ft := range ftList {
  5336. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5337. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5338. (select empname from user where id = fit.userId) empname,
  5339. 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
  5340. where fit.fitid = ?
  5341. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5342. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5343. if err != nil {
  5344. logs.Error(err)
  5345. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5346. return
  5347. }
  5348. ft["createdate"] = ft["createdate1"]
  5349. // data["tname"] = ft["tname"]
  5350. // data["tcode"] = ft["tcode"]
  5351. // data["tcolor"] = ft["tcolor"]
  5352. // data["fttype"] = ft["fttype"]
  5353. // data["ccname"] = ft["ccname"]
  5354. // data["source"] = ft["source"]
  5355. // data["version"] = ft["version"]
  5356. // data["remark"] = ft["remark"]
  5357. for n, ft2 := range ftList {
  5358. if i < n {
  5359. if ft["tname"].(string) != ft2["tname"].(string) {
  5360. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5361. }
  5362. if _, ok := ft["tcode"]; ok {
  5363. if _, ok := ft2["tcode"]; ok {
  5364. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5365. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5366. }
  5367. }
  5368. }
  5369. if _, ok := ft["tcolor"]; ok {
  5370. if _, ok := ft2["tcolor"]; ok {
  5371. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5372. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5373. }
  5374. }
  5375. }
  5376. if _, ok := ft["fttype"]; ok {
  5377. if _, ok := ft2["fttype"]; ok {
  5378. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5379. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5380. }
  5381. }
  5382. }
  5383. if _, ok := ft["ccname"]; ok {
  5384. if _, ok := ft2["ccname"]; ok {
  5385. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5386. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5387. }
  5388. }
  5389. }
  5390. if _, ok := ft["source"]; ok {
  5391. if _, ok := ft2["source"]; ok {
  5392. if ft["source"].(string) != ft2["source"].(string) {
  5393. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5394. }
  5395. }
  5396. }
  5397. if _, ok := ft["version"]; ok {
  5398. if _, ok := ft2["version"]; ok {
  5399. if ft["version"].(int64) != ft2["version"].(int64) {
  5400. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5401. }
  5402. }
  5403. }
  5404. if _, ok := ft["remark"]; ok {
  5405. if _, ok := ft2["remark"]; ok {
  5406. if ft["remark"].(string) != ft2["remark"].(string) {
  5407. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5408. }
  5409. }
  5410. }
  5411. break
  5412. }
  5413. }
  5414. dataList := make([]map[string]interface{}, 0)
  5415. if len(fithisList) > 0 {
  5416. for _, fit := range fithisList {
  5417. data := make(map[string]interface{})
  5418. data["feedgroup"] = fit["feedgroup"]
  5419. data["fname"] = fit["fname"]
  5420. data["empname"] = fit["empname"]
  5421. if fit["Eweight"] != nil {
  5422. if fit["Eweight"].(string) != fit["weight"].(string) {
  5423. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5424. } else {
  5425. data["fweight"] = fit["Eweight"]
  5426. }
  5427. data["fweightstatus"] = 1
  5428. } else {
  5429. data["fweight"] = fit["weight"]
  5430. data["fweightstatus"] = 0
  5431. }
  5432. data["autosecond"] = fit["autosecond"]
  5433. // data["tname"] = ft["tname"]
  5434. // data["tcode"] = ft["tcode"]
  5435. // data["tcolor"] = ft["tcolor"]
  5436. // data["fttype"] = ft["fttype"]
  5437. // data["ccname"] = ft["ccname"]
  5438. // data["source"] = ft["source"]
  5439. // data["version"] = ft["version"]
  5440. // data["remark"] = ft["remark"]
  5441. // data["createdate"] = ft["createdate1"]
  5442. // ft["fit"] = data
  5443. dataList = append(dataList, data)
  5444. }
  5445. } else {
  5446. for _, fit := range ftdetailList {
  5447. data := make(map[string]interface{})
  5448. data["feedgroup"] = fit["feedgroup"]
  5449. data["fname"] = fit["fname"]
  5450. // if fit["Eweight"] != nil {
  5451. // data["weight"] = fit["Eweight"]
  5452. // } else {
  5453. data["fweight"] = fit["fweight"]
  5454. // }
  5455. data["autosecond"] = fit["autosecond"]
  5456. // ft["fit"] = data
  5457. dataList = append(dataList, data)
  5458. }
  5459. }
  5460. ft["fit"] = dataList
  5461. }
  5462. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5463. }
  5464. func UpdateMaterialTMR(c *gin.Context) {
  5465. appG := app.Gin{C: c}
  5466. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5467. parammaps := gofasion.NewFasion(string(dataByte))
  5468. tmrid := parammaps.Get("tmrid").ValueStr()
  5469. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5470. lppid := parammaps.Get("lppid").ValueStr()
  5471. times := parammaps.Get("times").ValueStr()
  5472. pastureid := parammaps.Get("pastureid").ValueStr()
  5473. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5474. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5475. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5476. tx := restful.Engine.NewSession()
  5477. defer tx.Close()
  5478. tx.Begin()
  5479. if tmrid != "1000" {
  5480. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5481. if err != nil {
  5482. logs.Error(err)
  5483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5484. return
  5485. }
  5486. var maxstirfeed float64
  5487. for _, tmr := range tmrList {
  5488. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5489. }
  5490. if status == 0 {
  5491. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5492. if err != nil {
  5493. tx.Rollback()
  5494. logs.Error(err)
  5495. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5496. return
  5497. }
  5498. var lweight float64
  5499. for _, item := range lpplandtl1List {
  5500. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5501. lweight += fl
  5502. }
  5503. if lweight > maxstirfeed {
  5504. lweight = lweight - maxstirfeed
  5505. } else {
  5506. lweight = 0
  5507. }
  5508. if lweight > 0 {
  5509. lweight1 := lweight / float64(len(lpplandtl1List))
  5510. number := 0
  5511. for _, item := range lpplandtl1List {
  5512. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5513. if lweight1 >= fl {
  5514. number++
  5515. }
  5516. }
  5517. lweight := lweight / float64((len(lpplandtl1List) - number))
  5518. for _, item := range lpplandtl1List {
  5519. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5520. if lweight1 >= fl {
  5521. continue
  5522. }
  5523. if tmrtype == "1" {
  5524. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5525. if err != nil {
  5526. tx.Rollback()
  5527. logs.Error(err)
  5528. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5529. return
  5530. }
  5531. } else if tmrtype == "2" {
  5532. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5533. if err != nil {
  5534. tx.Rollback()
  5535. logs.Error(err)
  5536. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5537. return
  5538. }
  5539. }
  5540. if item["fttype"].(int64) == 0 {
  5541. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5542. if err != nil {
  5543. tx.Rollback()
  5544. logs.Error(err)
  5545. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5546. return
  5547. }
  5548. } else {
  5549. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5550. if err != nil {
  5551. tx.Rollback()
  5552. logs.Error(err)
  5553. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5554. return
  5555. }
  5556. }
  5557. }
  5558. } else {
  5559. for _, item := range lpplandtl1List {
  5560. // 自走式
  5561. if tmrtype == "1" {
  5562. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5563. if err != nil {
  5564. logs.Error(err)
  5565. tx.Rollback()
  5566. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5567. return
  5568. }
  5569. } else if tmrtype == "2" {
  5570. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5571. if err != nil {
  5572. logs.Error(err)
  5573. tx.Rollback()
  5574. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5575. return
  5576. }
  5577. }
  5578. }
  5579. }
  5580. } else if status == 1 {
  5581. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5582. if err != nil {
  5583. logs.Error(err)
  5584. tx.Rollback()
  5585. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5586. return
  5587. }
  5588. var lweight float64
  5589. for _, item := range lpplandtl1List {
  5590. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5591. lweight += fl
  5592. }
  5593. if lweight > maxstirfeed {
  5594. lweight = lweight - maxstirfeed
  5595. } else {
  5596. lweight = 0
  5597. }
  5598. for _, item := range lpplandtl1List {
  5599. if lweight > 0 {
  5600. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5601. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5602. if fl >= lweight {
  5603. item["lweight"] = fl - lweight
  5604. lweight = 0
  5605. if tmrtype == "1" {
  5606. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5607. if err != nil {
  5608. logs.Error(err)
  5609. tx.Rollback()
  5610. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5611. return
  5612. }
  5613. } else if tmrtype == "2" {
  5614. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5615. if err != nil {
  5616. logs.Error(err)
  5617. tx.Rollback()
  5618. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5619. return
  5620. }
  5621. }
  5622. if item["fttype"].(int64) == 0 {
  5623. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5624. if err != nil {
  5625. logs.Error(err)
  5626. tx.Rollback()
  5627. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5628. return
  5629. }
  5630. } else {
  5631. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5632. if err != nil {
  5633. logs.Error(err)
  5634. tx.Rollback()
  5635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5636. return
  5637. }
  5638. }
  5639. } else {
  5640. lweight = lweight - fl
  5641. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5642. if err != nil {
  5643. logs.Error(err)
  5644. tx.Rollback()
  5645. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5646. return
  5647. }
  5648. if item["fttype"].(int64) == 0 {
  5649. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5650. if err != nil {
  5651. logs.Error(err)
  5652. tx.Rollback()
  5653. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5654. return
  5655. }
  5656. } else {
  5657. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5658. if err != nil {
  5659. logs.Error(err)
  5660. tx.Rollback()
  5661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5662. return
  5663. }
  5664. }
  5665. }
  5666. } else {
  5667. // 自走式
  5668. if tmrtype == "1" {
  5669. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5670. if err != nil {
  5671. logs.Error(err)
  5672. tx.Rollback()
  5673. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5674. return
  5675. }
  5676. } else if tmrtype == "2" {
  5677. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5678. if err != nil {
  5679. logs.Error(err)
  5680. tx.Rollback()
  5681. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5682. return
  5683. }
  5684. }
  5685. }
  5686. }
  5687. } else {
  5688. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5689. if err != nil {
  5690. logs.Error(err)
  5691. tx.Rollback()
  5692. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5693. return
  5694. }
  5695. for _, item := range lpplandtl1List {
  5696. if item["fttype"].(int64) == 0 {
  5697. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5698. if err != nil {
  5699. logs.Error(err)
  5700. tx.Rollback()
  5701. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5702. return
  5703. }
  5704. } else {
  5705. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5706. if err != nil {
  5707. logs.Error(err)
  5708. tx.Rollback()
  5709. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5710. return
  5711. }
  5712. }
  5713. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5714. if err != nil {
  5715. logs.Error(err)
  5716. tx.Rollback()
  5717. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5718. return
  5719. }
  5720. }
  5721. }
  5722. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5723. if err != nil {
  5724. logs.Error(err)
  5725. tx.Rollback()
  5726. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5727. return
  5728. }
  5729. } else {
  5730. if status == 2 {
  5731. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5732. if err != nil {
  5733. logs.Error(err)
  5734. tx.Rollback()
  5735. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5736. return
  5737. }
  5738. for _, item := range lpplandtl1List {
  5739. if item["fttype"].(int64) == 0 {
  5740. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5741. if err != nil {
  5742. logs.Error(err)
  5743. tx.Rollback()
  5744. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5745. return
  5746. }
  5747. } else {
  5748. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5749. if err != nil {
  5750. logs.Error(err)
  5751. tx.Rollback()
  5752. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5753. return
  5754. }
  5755. }
  5756. }
  5757. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  5758. if err != nil {
  5759. logs.Error(err)
  5760. tx.Rollback()
  5761. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5762. return
  5763. }
  5764. } else {
  5765. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  5766. if err != nil {
  5767. logs.Error(err)
  5768. tx.Rollback()
  5769. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5770. return
  5771. }
  5772. }
  5773. }
  5774. err := tx.Commit()
  5775. if err != nil {
  5776. logs.Error(err)
  5777. tx.Rollback()
  5778. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5779. return
  5780. }
  5781. appG.Response(http.StatusOK, e.SUCCESS, true)
  5782. }
  5783. func UpdateMaterialTMRDate(c *gin.Context) {
  5784. appG := app.Gin{C: c}
  5785. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5786. parammaps := gofasion.NewFasion(string(dataByte))
  5787. tmrid := parammaps.Get("tmrid").ValueStr()
  5788. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5789. lppid := parammaps.Get("lppid").ValueStr()
  5790. times := parammaps.Get("times").ValueStr()
  5791. pastureid := parammaps.Get("pastureid").ValueStr()
  5792. date := parammaps.Get("date").ValueStr()
  5793. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5794. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5795. tx := restful.Engine.NewSession()
  5796. defer tx.Close()
  5797. tx.Begin()
  5798. if tmrid != "1000" {
  5799. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5800. if err != nil {
  5801. logs.Error(err)
  5802. tx.Rollback()
  5803. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5804. return
  5805. }
  5806. var maxstirfeed float64
  5807. for _, tmr := range tmrList {
  5808. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5809. }
  5810. if status == 0 {
  5811. 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()
  5812. if err != nil {
  5813. logs.Error(err)
  5814. tx.Rollback()
  5815. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5816. return
  5817. }
  5818. var lweight float64
  5819. for _, item := range lpplandtl1List {
  5820. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5821. lweight += fl
  5822. }
  5823. if lweight > maxstirfeed {
  5824. lweight = lweight - maxstirfeed
  5825. } else {
  5826. lweight = 0
  5827. }
  5828. if lweight > 0 {
  5829. lweight1 := lweight / float64(len(lpplandtl1List))
  5830. number := 0
  5831. for _, item := range lpplandtl1List {
  5832. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5833. if lweight1 >= fl {
  5834. number++
  5835. }
  5836. }
  5837. lweight := lweight / float64((len(lpplandtl1List) - number))
  5838. for _, item := range lpplandtl1List {
  5839. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5840. if lweight1 >= fl {
  5841. continue
  5842. }
  5843. if tmrtype == "1" {
  5844. _, 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()
  5845. if err != nil {
  5846. logs.Error(err)
  5847. tx.Rollback()
  5848. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5849. return
  5850. }
  5851. } else if tmrtype == "2" {
  5852. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5853. if err != nil {
  5854. logs.Error(err)
  5855. tx.Rollback()
  5856. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5857. return
  5858. }
  5859. }
  5860. if item["fttype"].(int64) == 0 {
  5861. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5862. if err != nil {
  5863. logs.Error(err)
  5864. tx.Rollback()
  5865. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5866. return
  5867. }
  5868. } else {
  5869. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5870. if err != nil {
  5871. logs.Error(err)
  5872. tx.Rollback()
  5873. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5874. return
  5875. }
  5876. }
  5877. }
  5878. } else {
  5879. for _, item := range lpplandtl1List {
  5880. // 自走式
  5881. if tmrtype == "1" {
  5882. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5883. if err != nil {
  5884. logs.Error(err)
  5885. tx.Rollback()
  5886. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5887. return
  5888. }
  5889. } else if tmrtype == "2" {
  5890. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5891. if err != nil {
  5892. logs.Error(err)
  5893. tx.Rollback()
  5894. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5895. return
  5896. }
  5897. }
  5898. }
  5899. }
  5900. } else if status == 1 {
  5901. 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()
  5902. if err != nil {
  5903. logs.Error(err)
  5904. tx.Rollback()
  5905. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5906. return
  5907. }
  5908. var lweight float64
  5909. for _, item := range lpplandtl1List {
  5910. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5911. lweight += fl
  5912. }
  5913. if lweight > maxstirfeed {
  5914. lweight = lweight - maxstirfeed
  5915. } else {
  5916. lweight = 0
  5917. }
  5918. for _, item := range lpplandtl1List {
  5919. if lweight > 0 {
  5920. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5921. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5922. if fl >= lweight {
  5923. item["lweight"] = fl - lweight
  5924. lweight = 0
  5925. if tmrtype == "1" {
  5926. _, 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()
  5927. if err != nil {
  5928. logs.Error(err)
  5929. tx.Rollback()
  5930. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5931. return
  5932. }
  5933. } else if tmrtype == "2" {
  5934. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5935. if err != nil {
  5936. logs.Error(err)
  5937. tx.Rollback()
  5938. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5939. return
  5940. }
  5941. }
  5942. if item["fttype"].(int64) == 0 {
  5943. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5944. if err != nil {
  5945. logs.Error(err)
  5946. tx.Rollback()
  5947. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5948. return
  5949. }
  5950. } else {
  5951. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5952. if err != nil {
  5953. logs.Error(err)
  5954. tx.Rollback()
  5955. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5956. return
  5957. }
  5958. }
  5959. } else {
  5960. lweight = lweight - fl
  5961. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5962. if err != nil {
  5963. logs.Error(err)
  5964. tx.Rollback()
  5965. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5966. return
  5967. }
  5968. if item["fttype"].(int64) == 0 {
  5969. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5970. if err != nil {
  5971. logs.Error(err)
  5972. tx.Rollback()
  5973. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5974. return
  5975. }
  5976. } else {
  5977. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5978. if err != nil {
  5979. logs.Error(err)
  5980. tx.Rollback()
  5981. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5982. return
  5983. }
  5984. }
  5985. }
  5986. } else {
  5987. // 自走式
  5988. if tmrtype == "1" {
  5989. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5990. if err != nil {
  5991. logs.Error(err)
  5992. tx.Rollback()
  5993. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5994. return
  5995. }
  5996. } else if tmrtype == "2" {
  5997. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5998. if err != nil {
  5999. logs.Error(err)
  6000. tx.Rollback()
  6001. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6002. return
  6003. }
  6004. }
  6005. }
  6006. }
  6007. } else {
  6008. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6009. if err != nil {
  6010. logs.Error(err)
  6011. tx.Rollback()
  6012. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6013. return
  6014. }
  6015. for _, item := range lpplandtl1List {
  6016. if item["fttype"].(int64) == 0 {
  6017. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6018. if err != nil {
  6019. logs.Error(err)
  6020. tx.Rollback()
  6021. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6022. return
  6023. }
  6024. } else {
  6025. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6026. if err != nil {
  6027. logs.Error(err)
  6028. tx.Rollback()
  6029. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6030. return
  6031. }
  6032. }
  6033. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6034. if err != nil {
  6035. logs.Error(err)
  6036. tx.Rollback()
  6037. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6038. return
  6039. }
  6040. }
  6041. }
  6042. _, 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()
  6043. if err != nil {
  6044. logs.Error(err)
  6045. tx.Rollback()
  6046. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6047. return
  6048. }
  6049. } else {
  6050. if status == 2 {
  6051. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6052. if err != nil {
  6053. logs.Error(err)
  6054. tx.Rollback()
  6055. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6056. return
  6057. }
  6058. for _, item := range lpplandtl1List {
  6059. if item["fttype"].(int64) == 0 {
  6060. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6061. if err != nil {
  6062. logs.Error(err)
  6063. tx.Rollback()
  6064. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6065. return
  6066. }
  6067. } else {
  6068. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6069. if err != nil {
  6070. logs.Error(err)
  6071. tx.Rollback()
  6072. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6073. return
  6074. }
  6075. }
  6076. }
  6077. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6078. if err != nil {
  6079. logs.Error(err)
  6080. tx.Rollback()
  6081. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6082. return
  6083. }
  6084. } else {
  6085. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6086. if err != nil {
  6087. logs.Error(err)
  6088. tx.Rollback()
  6089. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6090. return
  6091. }
  6092. }
  6093. }
  6094. err := tx.Commit()
  6095. if err != nil {
  6096. logs.Error(err)
  6097. tx.Rollback()
  6098. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6099. return
  6100. }
  6101. appG.Response(http.StatusOK, e.SUCCESS, true)
  6102. }
  6103. func Decimal(value float64) float64 {
  6104. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6105. return value
  6106. }
  6107. func UpdateDailyData(c *gin.Context) {
  6108. appG := app.Gin{C: c}
  6109. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6110. parammaps := gofasion.NewFasion(string(dataByte))
  6111. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6112. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6113. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6114. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6115. date := parammaps.Get("date").ValueStr()
  6116. tx := restful.Engine.NewSession()
  6117. defer tx.Close()
  6118. tx.Begin()
  6119. if location == 0 {
  6120. fid := parammaps.Get("fid").ValueStr()
  6121. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6122. if err != nil {
  6123. logs.Error("UpdateDailyData-error-1:", err)
  6124. tx.Rollback()
  6125. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6126. return
  6127. }
  6128. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6129. if err != nil {
  6130. logs.Error("UpdateDailyData-error-1:", err)
  6131. tx.Rollback()
  6132. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6133. return
  6134. }
  6135. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6136. if err != nil {
  6137. fmt.Println("Error:", err)
  6138. return
  6139. }
  6140. actualWeight := weight - num
  6141. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6142. if err != nil {
  6143. logs.Error("UpdateDailyData-error-2:", err)
  6144. tx.Rollback()
  6145. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6146. return
  6147. }
  6148. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6149. if err != nil {
  6150. logs.Error("UpdateDailyData-error-3:", err)
  6151. tx.Rollback()
  6152. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6153. return
  6154. }
  6155. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6156. if err != nil {
  6157. logs.Error("UpdateDailyData-error-4:", err)
  6158. tx.Rollback()
  6159. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6160. return
  6161. }
  6162. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6163. if err != nil {
  6164. logs.Error("UpdateDailyData-error-5:", err)
  6165. tx.Rollback()
  6166. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6167. return
  6168. }
  6169. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6170. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6171. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6172. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6173. if err != nil {
  6174. fmt.Println("Error:", err)
  6175. return
  6176. }
  6177. // actual := actualWeight / float64(len(downloadedplanList))
  6178. for _, item := range downloadedplanList {
  6179. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6180. if err != nil {
  6181. fmt.Println("Error:", err)
  6182. return
  6183. }
  6184. actual := itemLweight / lweight * actualWeight
  6185. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6186. if err != nil {
  6187. logs.Error("UpdateDailyData-error-6:", err)
  6188. tx.Rollback()
  6189. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6190. return
  6191. }
  6192. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6193. if err != nil {
  6194. logs.Error("UpdateDailyData-error-7:", err)
  6195. tx.Rollback()
  6196. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6197. return
  6198. }
  6199. _, 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()
  6200. if err != nil {
  6201. logs.Error("UpdateDailyData-error-8:", err)
  6202. tx.Rollback()
  6203. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6204. return
  6205. }
  6206. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6207. if err != nil {
  6208. logs.Error("UpdateDailyData-error-9:", err)
  6209. tx.Rollback()
  6210. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6211. return
  6212. }
  6213. }
  6214. } else {
  6215. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6216. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6217. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6218. // if err != nil {
  6219. // fmt.Println("Error:", err)
  6220. // return
  6221. // }
  6222. for _, item := range downloadedplanList {
  6223. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6224. if err != nil {
  6225. logs.Error("UpdateDailyData-error-6:", err)
  6226. tx.Rollback()
  6227. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6228. return
  6229. }
  6230. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6231. item["lweight"], actualWeight, item["id"]).Execute()
  6232. if err != nil {
  6233. logs.Error("UpdateDailyData-error-7:", err)
  6234. tx.Rollback()
  6235. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6236. return
  6237. }
  6238. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6239. where pid = ?`, item["id"]).Execute()
  6240. if err != nil {
  6241. logs.Error("UpdateDailyData-error-8:", err)
  6242. tx.Rollback()
  6243. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6244. return
  6245. }
  6246. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6247. if err != nil {
  6248. logs.Error("UpdateDailyData-error-9:", err)
  6249. tx.Rollback()
  6250. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6251. return
  6252. }
  6253. }
  6254. }
  6255. } else {
  6256. fbarid := parammaps.Get("fbarid").ValueStr()
  6257. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6258. if err != nil {
  6259. logs.Error("UpdateDailyData-error-10:", err)
  6260. tx.Rollback()
  6261. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6262. return
  6263. }
  6264. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6265. if err != nil {
  6266. logs.Error("UpdateDailyData-error-1:", err)
  6267. tx.Rollback()
  6268. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6269. return
  6270. }
  6271. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6272. if err != nil {
  6273. fmt.Println("Error:", err)
  6274. return
  6275. }
  6276. actualWeight := weight - num
  6277. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6278. if err != nil {
  6279. logs.Error("UpdateDailyData-error-11:", err)
  6280. tx.Rollback()
  6281. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6282. return
  6283. }
  6284. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6285. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6286. if err != nil {
  6287. logs.Error("UpdateDailyData-error-12:", err)
  6288. tx.Rollback()
  6289. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6290. return
  6291. }
  6292. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6293. where pid = ? `, pid).Execute()
  6294. if err != nil {
  6295. logs.Error("UpdateDailyData-error-13:", err)
  6296. tx.Rollback()
  6297. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6298. return
  6299. }
  6300. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6301. if err != nil {
  6302. logs.Error("UpdateDailyData-error-14:", err)
  6303. tx.Rollback()
  6304. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6305. return
  6306. }
  6307. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6308. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6309. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6310. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6311. if err != nil {
  6312. fmt.Println("Error:", err)
  6313. return
  6314. }
  6315. for _, item := range downloadedplanList {
  6316. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6317. if err != nil {
  6318. fmt.Println("Error:", err)
  6319. return
  6320. }
  6321. actual := itemLweight / lweight * actualWeight
  6322. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6323. if err != nil {
  6324. logs.Error("UpdateDailyData-error-6:", err)
  6325. tx.Rollback()
  6326. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6327. return
  6328. }
  6329. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6330. if err != nil {
  6331. logs.Error("UpdateDailyData-error-7:", err)
  6332. tx.Rollback()
  6333. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6334. return
  6335. }
  6336. _, 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()
  6337. if err != nil {
  6338. logs.Error("UpdateDailyData-error-8:", err)
  6339. tx.Rollback()
  6340. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6341. return
  6342. }
  6343. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6344. if err != nil {
  6345. logs.Error("UpdateDailyData-error-9:", err)
  6346. tx.Rollback()
  6347. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6348. return
  6349. }
  6350. }
  6351. } else {
  6352. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6353. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6354. for _, item := range downloadedplanList {
  6355. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6356. // if err != nil {
  6357. // fmt.Println("Error:", err)
  6358. // return
  6359. // }
  6360. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6361. if err != nil {
  6362. logs.Error("UpdateDailyData-error-6:", err)
  6363. tx.Rollback()
  6364. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6365. return
  6366. }
  6367. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6368. item["lweight"], actualWeight, item["id"]).Execute()
  6369. if err != nil {
  6370. logs.Error("UpdateDailyData-error-7:", err)
  6371. tx.Rollback()
  6372. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6373. return
  6374. }
  6375. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6376. where pid = ?`, item["id"]).Execute()
  6377. if err != nil {
  6378. logs.Error("UpdateDailyData-error-8:", err)
  6379. tx.Rollback()
  6380. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6381. return
  6382. }
  6383. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6384. if err != nil {
  6385. logs.Error("UpdateDailyData-error-9:", err)
  6386. tx.Rollback()
  6387. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6388. return
  6389. }
  6390. }
  6391. }
  6392. }
  6393. err := tx.Commit()
  6394. if err != nil {
  6395. logs.Error("UpdateDailyData-error-20:", err)
  6396. tx.Rollback()
  6397. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6398. return
  6399. }
  6400. appG.Response(http.StatusOK, e.SUCCESS, true)
  6401. }
  6402. func GetFormulaStatistics(c *gin.Context) {
  6403. appG := app.Gin{C: c}
  6404. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6405. parammaps := gofasion.NewFasion(string(dataByte))
  6406. startTime := parammaps.Get("startTime").ValueStr()
  6407. endTime := parammaps.Get("endTime").ValueStr()
  6408. pastureId := parammaps.Get("pastureId").ValueStr()
  6409. tx := restful.Engine.NewSession()
  6410. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6411. if err != nil {
  6412. logs.Error("GetFormulaStatistics-error-1:", err)
  6413. tx.Rollback()
  6414. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6415. return
  6416. }
  6417. var feedtemplet, dateList []string
  6418. for _, f := range feedtempletList {
  6419. feedtemplet = append(feedtemplet, f["tname"].(string))
  6420. }
  6421. layout := "2006-01-02"
  6422. // s := "2023-05-01"
  6423. // e := "2023-05-23"
  6424. start, err := time.Parse(layout, startTime)
  6425. if err != nil {
  6426. fmt.Println(err)
  6427. return
  6428. }
  6429. end, err := time.Parse(layout, endTime)
  6430. if err != nil {
  6431. fmt.Println(err)
  6432. return
  6433. }
  6434. end = end.AddDate(0, 0, 1)
  6435. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6436. dateList = append(dateList, d.Format("2006-01-02"))
  6437. }
  6438. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6439. 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= ?
  6440. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6441. if err != nil {
  6442. logs.Error("GetFormulaStatistics-error-2:", err)
  6443. tx.Rollback()
  6444. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6445. return
  6446. }
  6447. var data2 [][]interface{}
  6448. for _, f := range feedtemplet {
  6449. var data1 []interface{}
  6450. for _, date := range dateList {
  6451. exist := false
  6452. for _, item := range downloadedplanList {
  6453. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6454. data1 = append(data1, item["total"])
  6455. exist = true
  6456. break
  6457. }
  6458. }
  6459. if !exist {
  6460. data1 = append(data1, 0)
  6461. }
  6462. }
  6463. data2 = append(data2, data1)
  6464. }
  6465. //前端让加的
  6466. feedtemplet = append(feedtemplet, "")
  6467. {
  6468. var data1 []interface{}
  6469. for _, f := range dateList {
  6470. // f = f + "\n"
  6471. fmt.Println(f)
  6472. data1 = append(data1, 0)
  6473. }
  6474. data2 = append(data2, data1)
  6475. }
  6476. resp := make(map[string]interface{}, 0)
  6477. resp["xdata"] = dateList
  6478. resp["data1"] = feedtemplet
  6479. resp["data2"] = data2
  6480. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6481. }
  6482. func GetPlanData(c *gin.Context) {
  6483. appG := app.Gin{C: c}
  6484. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6485. fsion := gofasion.NewFasion(string(dataByte))
  6486. sqlnamestr := fsion.Get("name").ValueStr()
  6487. sqlnamestr1 := fsion.Get("name1").ValueStr()
  6488. offset := fsion.Get("offset").ValueDefaultInt(0)
  6489. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  6490. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6491. month := fsion.Get("month").ValueDefaultStr("map")
  6492. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  6493. tx := restful.Engine.NewSession()
  6494. err := tx.Begin()
  6495. defer func() {
  6496. switch {
  6497. case err != nil:
  6498. if tx != nil {
  6499. tx.Rollback()
  6500. }
  6501. default:
  6502. if tx != nil {
  6503. err = tx.Commit()
  6504. }
  6505. }
  6506. if tx != nil {
  6507. tx.Close()
  6508. }
  6509. }()
  6510. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6511. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  6512. if sql != "" {
  6513. s_params := make([]interface{}, 0)
  6514. if fsion.HasKey("parammaps") {
  6515. parammaps := fsion.Get("parammaps")
  6516. paramslist := strings.Split(p, ",")
  6517. if len(paramslist) > 0 && p != "" {
  6518. for _, value := range paramslist {
  6519. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6520. if tempv, exists := c.Get("jwt_username"); exists {
  6521. s_params = append(s_params, tempv.(string))
  6522. } else {
  6523. s_params = append(s_params, "")
  6524. }
  6525. } else {
  6526. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6527. }
  6528. }
  6529. }
  6530. }
  6531. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6532. if err != nil {
  6533. appG.Response(http.StatusOK, e.ERROR, err.Error())
  6534. } else {
  6535. paramslist1 := strings.Split(p1, ",")
  6536. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6537. s_params1 := make([]interface{}, 0)
  6538. if len(paramslist1) > 0 && p1 != "" {
  6539. for _, v := range paramslist1 {
  6540. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  6541. }
  6542. }
  6543. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  6544. for _, item := range arr {
  6545. trgaddressList := []string{}
  6546. if _, ok := item["trgaddress"]; ok {
  6547. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6548. for _, str := range trgaddressList1 {
  6549. if str != "" {
  6550. trgaddressList = append(trgaddressList, str)
  6551. }
  6552. }
  6553. }
  6554. item["trgaddressList"] = trgaddressList
  6555. }
  6556. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  6557. }
  6558. // var wg sync.WaitGroup
  6559. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6560. // wg.Add(1)
  6561. // go func(value map[string]interface{}) {
  6562. // defer wg.Done()
  6563. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  6564. // }(value)
  6565. // }
  6566. // wg.Wait()
  6567. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6568. }
  6569. } else {
  6570. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6571. }
  6572. }
  6573. func PostPlanData(c *gin.Context) {
  6574. appG := app.Gin{C: c}
  6575. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6576. fsion := gofasion.NewFasion(string(dataByte))
  6577. logging.Info("PostRJSBData err: ", string(dataByte))
  6578. s_params := make([]interface{}, 0)
  6579. tx := restful.Engine.NewSession()
  6580. err := tx.Begin()
  6581. defer func() {
  6582. switch {
  6583. case err != nil:
  6584. if tx != nil {
  6585. tx.Rollback()
  6586. }
  6587. default:
  6588. if tx != nil {
  6589. err = tx.Commit()
  6590. }
  6591. }
  6592. if tx != nil {
  6593. tx.Close()
  6594. }
  6595. }()
  6596. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  6597. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  6598. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  6599. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  6600. if !fsion.HasKey("parammaps") {
  6601. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  6602. return
  6603. }
  6604. parammaps := fsion.Get("parammaps")
  6605. paramslist := strings.Split(p, ",")
  6606. if len(paramslist) > 0 && p != "" {
  6607. for _, value := range paramslist {
  6608. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6609. }
  6610. }
  6611. _, err = tx.SQL(sql, s_params...).Execute()
  6612. if err != nil {
  6613. logging.Error("PostRJSBData err: ", err)
  6614. msg := geterrmsg(err.Error())
  6615. appG.Response(http.StatusOK, e.ERROR, msg)
  6616. return
  6617. }
  6618. s_params = make([]interface{}, 0)
  6619. paramslist = strings.Split(p1, ",")
  6620. if len(paramslist) > 0 && p1 != "" {
  6621. for _, value := range paramslist {
  6622. // if value == "ID" {
  6623. // id := parammaps.Get("ID").ValueStr()
  6624. // pastureid := parammaps.Get("pastureid").ValueStr()
  6625. // 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
  6626. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6627. // if err != nil {
  6628. // logging.Error("PostRJSBData err: ", err)
  6629. // msg := geterrmsg(err.Error())
  6630. // appG.Response(http.StatusOK, e.ERROR, msg)
  6631. // return
  6632. // }
  6633. // for _, item := range datalist {
  6634. // id = item["id"]
  6635. // }
  6636. // s_params = append(s_params, id)
  6637. // } else {
  6638. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6639. // }
  6640. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6641. }
  6642. }
  6643. _, err = tx.SQL(sql1, s_params...).Execute()
  6644. if err != nil {
  6645. logging.Error("PostRJSBData1 err: ", err)
  6646. msg := geterrmsg(err.Error())
  6647. appG.Response(http.StatusOK, e.ERROR, msg)
  6648. return
  6649. }
  6650. s_params = make([]interface{}, 0)
  6651. paramslist = strings.Split(p2, ",")
  6652. if len(paramslist) > 0 && p2 != "" {
  6653. for _, value := range paramslist {
  6654. if value == "ID" {
  6655. id := parammaps.Get("ID").ValueStr()
  6656. pastureid := parammaps.Get("pastureid").ValueStr()
  6657. 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
  6658. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6659. if err != nil {
  6660. logging.Error("PostRJSBData err: ", err)
  6661. msg := geterrmsg(err.Error())
  6662. appG.Response(http.StatusOK, e.ERROR, msg)
  6663. return
  6664. }
  6665. for _, item := range datalist {
  6666. id = item["id"]
  6667. }
  6668. s_params = append(s_params, id)
  6669. } else {
  6670. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6671. }
  6672. }
  6673. }
  6674. _, err = tx.SQL(sql2, s_params...).Execute()
  6675. if err != nil {
  6676. logging.Error("PostRJSBData2 err: ", err)
  6677. msg := geterrmsg(err.Error())
  6678. appG.Response(http.StatusOK, e.ERROR, msg)
  6679. return
  6680. }
  6681. s_params = make([]interface{}, 0)
  6682. paramslist = strings.Split(p3, ",")
  6683. if len(paramslist) > 0 && p3 != "" {
  6684. for _, value := range paramslist {
  6685. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6686. }
  6687. }
  6688. _, err = tx.SQL(sql3, s_params...).Execute()
  6689. if err != nil {
  6690. logging.Error("PostRJSBData3 err: ", err)
  6691. msg := geterrmsg(err.Error())
  6692. appG.Response(http.StatusOK, e.ERROR, msg)
  6693. return
  6694. }
  6695. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6696. }
  6697. func CheckFeedTrgaddress(c *gin.Context) {
  6698. appG := app.Gin{C: c}
  6699. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6700. fsion := gofasion.NewFasion(string(dataByte))
  6701. fclassid := fsion.Get("fclassid").ValueStr()
  6702. feedId := fsion.Get("feedId").ValueStr()
  6703. backup1 := fsion.Get("backup1").ValueStr()
  6704. backup1List := strings.Split(backup1, ",")
  6705. tx := restful.Engine.NewSession()
  6706. defer tx.Close()
  6707. // if backup1 != "" {
  6708. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  6709. for _, feed := range feedList {
  6710. if feed["backup1"] == "" {
  6711. continue
  6712. }
  6713. feedbackupList := strings.Split(feed["backup1"], ",")
  6714. for _, feedbackup := range feedbackupList {
  6715. for _, backup := range backup1List {
  6716. if feedbackup == backup {
  6717. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  6718. return
  6719. }
  6720. }
  6721. }
  6722. }
  6723. // }
  6724. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6725. }
  6726. func ThiGetDataByName(c *gin.Context) {
  6727. appG := app.Gin{C: c}
  6728. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6729. fsion := gofasion.NewFasion(string(dataByte))
  6730. sqlnamestr := fsion.Get("name").ValueStr()
  6731. offset := fsion.Get("offset").ValueDefaultInt(0)
  6732. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  6733. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6734. tx := restful.Engine.NewSession()
  6735. err := tx.Begin()
  6736. defer func() {
  6737. switch {
  6738. case err != nil:
  6739. logging.Error("tx.Begin 事务启动失败__error:", err)
  6740. if tx != nil {
  6741. tx.Rollback()
  6742. }
  6743. default:
  6744. if tx != nil {
  6745. err = tx.Commit()
  6746. }
  6747. }
  6748. if tx != nil {
  6749. tx.Close()
  6750. }
  6751. }()
  6752. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6753. if sql != "" {
  6754. s_params := make([]interface{}, 0)
  6755. if fsion.HasKey("parammaps") {
  6756. parammaps := fsion.Get("parammaps")
  6757. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  6758. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  6759. }
  6760. paramslist := strings.Split(p, ",")
  6761. if len(paramslist) > 0 && p != "" {
  6762. for _, value := range paramslist {
  6763. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6764. if tempv, exists := c.Get("jwt_username"); exists {
  6765. s_params = append(s_params, tempv.(string))
  6766. } else {
  6767. s_params = append(s_params, "")
  6768. }
  6769. } else {
  6770. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6771. }
  6772. }
  6773. }
  6774. } else if fsion.HasKey("params") {
  6775. params := fsion.Get("params").Array()
  6776. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  6777. for _, v_params := range params {
  6778. s_params = append(s_params, v_params.ValueStr())
  6779. }
  6780. }
  6781. if returntype == "xlsx" {
  6782. var xlsxfile *xlsx.File
  6783. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  6784. //c.File("c:/dd.xlsx")
  6785. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  6786. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  6787. c.Header("Content-Transfer-Encoding", "binary")
  6788. _ = xlsxfile.Write(c.Writer)
  6789. } else {
  6790. if sqlnamestr == "getHomepageStr" {
  6791. parammaps := fsion.Get("parammaps")
  6792. pastureid := parammaps.Get("pastureid").ValueStr()
  6793. var montimeList []float64
  6794. var montime float64
  6795. var wg sync.WaitGroup
  6796. now := time.Now()
  6797. for i := 0; i < 30; i++ {
  6798. wg.Add(1)
  6799. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  6800. go func(nowstr string) {
  6801. defer wg.Done()
  6802. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  6803. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  6804. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  6805. montimeList = append(montimeList, m)
  6806. }(nowstr)
  6807. }
  6808. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6809. if err != nil {
  6810. logging.Error("GetDataByName err: ", err)
  6811. msg := geterrmsg(err.Error())
  6812. appG.Response(http.StatusOK, e.ERROR, msg)
  6813. }
  6814. wg.Wait()
  6815. for _, m := range montimeList {
  6816. montime += m
  6817. }
  6818. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  6819. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6820. return
  6821. }
  6822. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6823. if err != nil {
  6824. logging.Error("GetDataByName err: ", err)
  6825. msg := geterrmsg(err.Error())
  6826. appG.Response(http.StatusOK, e.ERROR, msg)
  6827. } else {
  6828. if sqlnamestr == "getFeedTrgaddressList" {
  6829. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6830. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6831. trgaddressList := []string{}
  6832. for _, str := range trgaddressList1 {
  6833. if str != "" {
  6834. trgaddressList = append(trgaddressList, str)
  6835. }
  6836. }
  6837. item["trgaddressList"] = trgaddressList
  6838. }
  6839. }
  6840. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6841. }
  6842. }
  6843. } else {
  6844. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6845. }
  6846. }
  6847. // func ToggleCcount(c *gin.Context) {
  6848. // appG := app.Gin{C: c}
  6849. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6850. // fsion := gofasion.NewFasion(string(dataByte))
  6851. // // 0 实际 1 软件
  6852. // status := fsion.Get("status").ValueDefaultInt64(0)
  6853. // pastureId := fsion.Get("pastureId").ValueStr()
  6854. // tx := restful.Engine.NewSession()
  6855. // err := tx.Begin()
  6856. // defer func() {
  6857. // switch {
  6858. // case err != nil:
  6859. // logging.Error("tx.Begin 事务启动失败__error:", err)
  6860. // if tx != nil {
  6861. // tx.Rollback()
  6862. // }
  6863. // default:
  6864. // if tx != nil {
  6865. // err = tx.Commit()
  6866. // }
  6867. // }
  6868. // if tx != nil {
  6869. // tx.Close()
  6870. // }
  6871. // }()
  6872. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  6873. // if err != nil {
  6874. // logs.Error(err)
  6875. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6876. // return
  6877. // }
  6878. // for _, bar := range barList {
  6879. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  6880. // if err != nil {
  6881. // logs.Error(err)
  6882. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6883. // return
  6884. // }
  6885. // if !exist {
  6886. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  6887. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  6888. // if err != nil {
  6889. // logs.Error(err)
  6890. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6891. // return
  6892. // }
  6893. // }
  6894. // }
  6895. // if status == 0 {
  6896. // tx.Exec(`update feedp set ccount = actualcount `)
  6897. // }else{
  6898. // tx.Exec(`update feedp set ccount = softccount `)
  6899. // }
  6900. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  6901. // if err != nil {
  6902. // logs.Error(err)
  6903. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6904. // return
  6905. // }
  6906. // for _, feedpData :=range feedpList{
  6907. // var feedpargs []interface{}
  6908. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  6909. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  6910. // if _, ok := feedpData["ftname"]; ok {
  6911. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  6912. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  6913. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  6914. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  6915. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6916. // } else {
  6917. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  6918. // }
  6919. // if _, ok := feedpData["ptsfname"]; ok {
  6920. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  6921. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  6922. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  6923. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  6924. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6925. // } else {
  6926. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  6927. // }
  6928. // upFeedpSql += " where barname = ? and pastureid = ? "
  6929. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  6930. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  6931. // if err != nil {
  6932. // logs.Error(err)
  6933. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6934. // return
  6935. // }
  6936. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  6937. // if err != nil {
  6938. // logs.Error(err)
  6939. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6940. // return
  6941. // }
  6942. // if !exist1 {
  6943. // _, 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) `,
  6944. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6945. // if err != nil {
  6946. // logs.Error(err)
  6947. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6948. // return
  6949. // }
  6950. // }
  6951. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  6952. // if err != nil {
  6953. // logs.Error(err)
  6954. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6955. // return
  6956. // }
  6957. // if !exist2 {
  6958. // _, 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) `,
  6959. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6960. // if err != nil {
  6961. // logs.Error(err)
  6962. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6963. // return
  6964. // }
  6965. // }
  6966. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  6967. // if err != nil {
  6968. // logs.Error(err)
  6969. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6970. // return
  6971. // }
  6972. // if !exist3 {
  6973. // _, 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) `,
  6974. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6975. // if err != nil {
  6976. // logs.Error(err)
  6977. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6978. // return
  6979. // }
  6980. // }
  6981. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  6982. // if err != nil {
  6983. // logs.Error(err)
  6984. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6985. // return
  6986. // }
  6987. // if !exist4 {
  6988. // _, 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) `,
  6989. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6990. // if err != nil {
  6991. // logs.Error(err)
  6992. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6993. // return
  6994. // }
  6995. // }
  6996. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  6997. // if err != nil {
  6998. // logs.Error(err)
  6999. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7000. // return
  7001. // }
  7002. // if !exist5 {
  7003. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  7004. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7005. // if err != nil {
  7006. // logs.Error(err)
  7007. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7008. // return
  7009. // }
  7010. // }
  7011. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7012. // if err != nil {
  7013. // logs.Error(err)
  7014. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7015. // return
  7016. // }
  7017. // if !exist6 {
  7018. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  7019. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7020. // if err != nil {
  7021. // logs.Error(err)
  7022. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7023. // return
  7024. // }
  7025. // }
  7026. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7027. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7028. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7029. // and pastureid = ? and times = ?`
  7030. // var fpdargs1 []interface{}
  7031. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7032. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7033. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7034. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7035. // if err != nil {
  7036. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7037. // return
  7038. // }
  7039. // var fpdargs2 []interface{}
  7040. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7041. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7042. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7043. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7044. // if err != nil {
  7045. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7046. // return
  7047. // }
  7048. // var fpdargs3 []interface{}
  7049. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7050. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7051. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7052. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7053. // if err != nil {
  7054. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7055. // return
  7056. // }
  7057. // var fpdargs4 []interface{}
  7058. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7059. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7060. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7061. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7062. // if err != nil {
  7063. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7064. // return
  7065. // }
  7066. // var fpdargs5 []interface{}
  7067. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7068. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7069. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7070. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7071. // if err != nil {
  7072. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7073. // return
  7074. // }
  7075. // var fpdargs6 []interface{}
  7076. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7077. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7078. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7079. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7080. // if err != nil {
  7081. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7082. // return
  7083. // }
  7084. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7085. // 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()
  7086. // if err != nil {
  7087. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7088. // return
  7089. // }
  7090. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7091. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7092. // upFpdetailList := make([]*upFpdetail, 0)
  7093. // for _, newfpd := range newList {
  7094. // for _, oldfpd := range oldFpdList {
  7095. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7096. // var oldweight, newweight float64
  7097. // if oldfpd["weight"] != nil {
  7098. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7099. // }
  7100. // if newfpd["weight"] != nil {
  7101. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7102. // }
  7103. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7104. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7105. // Old: oldweight,
  7106. // New: newweight,
  7107. // Times: newfpd["times"].(int64),
  7108. // Ptid: newfpd["ptid"].(int64),
  7109. // Fweight: fweight,
  7110. // Id: oldfpd["id"].(int64),
  7111. // })
  7112. // break
  7113. // }
  7114. // }
  7115. // }
  7116. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7117. // }
  7118. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7119. // }
  7120. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7121. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7122. if err != nil {
  7123. return err
  7124. }
  7125. for _, item := range feedpList {
  7126. // if item["ftid"].(string) != data["ftid"].(string) {
  7127. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7128. if err != nil {
  7129. return err
  7130. }
  7131. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7132. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7133. if err != nil {
  7134. return err
  7135. }
  7136. // }
  7137. }
  7138. return nil
  7139. }