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. fsionData := fsion.Get("data").Array()
  3232. for _, list := range fsionData {
  3233. ftmap := make(map[string]interface{})
  3234. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3235. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3236. ftmap["times"] = list.Get("times").ValueInt64()
  3237. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3238. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3239. // fmt.Println(ftmap)
  3240. 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 ,
  3241. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3242. WHERE fpdetail.pastureid = ? and barid =(select barid from feedp where id = ? ) and times = ?
  3243. UNION
  3244. 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 ,
  3245. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3246. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? ) t
  3247. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3248. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3249. if err != nil {
  3250. tx.Rollback()
  3251. logs.Error(err)
  3252. }
  3253. for _, fpd := range fpdDataList {
  3254. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3255. fttype := -1
  3256. if ftmap["ptid"].(string) != "-1" {
  3257. fttype = 1
  3258. }
  3259. var fweight float64
  3260. var lweight float64
  3261. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3262. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3263. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3264. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3265. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3266. if err != nil {
  3267. tx.Rollback()
  3268. logs.Error(err)
  3269. }
  3270. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3271. var w float64
  3272. var status int
  3273. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3274. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3275. if weight >= 0 {
  3276. continue
  3277. }
  3278. w = weight
  3279. status = 0
  3280. } else {
  3281. // continue
  3282. if weight <= 0 {
  3283. continue
  3284. }
  3285. w = weight
  3286. status = 1
  3287. }
  3288. for _, lppland := range lpplandtl1List {
  3289. lweight += lppland.Lweight
  3290. }
  3291. for _, lppland := range lpplandtl1List {
  3292. if status == 1 {
  3293. // if w <= lppland.Lweight {
  3294. if lppland.Maxweight <= lweight {
  3295. continue
  3296. }
  3297. if w+lweight <= lppland.Maxweight {
  3298. lppland.Lweight += w
  3299. lweight += w
  3300. fweight += w
  3301. w = 0
  3302. } else {
  3303. w = w - (lppland.Maxweight - lweight)
  3304. n := (lppland.Maxweight - lweight)
  3305. lppland.Lweight = lppland.Lweight + n
  3306. lweight += n
  3307. fweight += n
  3308. }
  3309. } else {
  3310. if lppland.Lweight == 0 {
  3311. continue
  3312. }
  3313. if w+lppland.Lweight >= 0 {
  3314. lppland.Lweight = lppland.Lweight + w
  3315. lweight = lweight + w
  3316. fweight = fweight + w
  3317. w = 0
  3318. } else {
  3319. w = w + lppland.Lweight
  3320. lweight = lweight - lppland.Lweight
  3321. fweight = fweight - lppland.Lweight
  3322. lppland.Lweight = 0
  3323. }
  3324. }
  3325. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3326. if err != nil {
  3327. tx.Rollback()
  3328. logs.Error(err)
  3329. return
  3330. }
  3331. break
  3332. }
  3333. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3334. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3335. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3336. if err != nil {
  3337. tx.Rollback()
  3338. logs.Error(err)
  3339. }
  3340. if w == 0 {
  3341. break
  3342. }
  3343. }
  3344. }
  3345. }
  3346. fmt.Println("33333333333333")
  3347. tx.Commit()
  3348. now := time.Now()
  3349. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3350. if err != nil {
  3351. logs.Error(err)
  3352. appG.Response(http.StatusOK, e.ERROR, false)
  3353. return
  3354. }
  3355. // newFpdDataList, err := tx.SQL(` select * from fpdetail where barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3356. // if err != nil {
  3357. // logs.Error(err)
  3358. // appG.Response(http.StatusOK, e.ERROR, false)
  3359. // return
  3360. // }
  3361. // newFeedpList, err := tx.SQL(` select * from feedp where barid = ? and pastureid = ?`, id, pastureid).Query().List()
  3362. // if err != nil {
  3363. // logs.Error(err)
  3364. // appG.Response(http.StatusOK, e.ERROR, false)
  3365. // return
  3366. // }
  3367. for _, newLpplandtl1 := range newLpplandtl1List {
  3368. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3369. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3370. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3371. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3372. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3373. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3374. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3375. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3376. if err != nil {
  3377. logs.Error(err)
  3378. appG.Response(http.StatusOK, e.ERROR, false)
  3379. return
  3380. }
  3381. }
  3382. appG.Response(http.StatusOK, e.SUCCESS, true)
  3383. }
  3384. func GetProcessAnalysis(c *gin.Context) {
  3385. appG := app.Gin{C: c}
  3386. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3387. fsion := gofasion.NewFasion(string(dataByte))
  3388. sqlnamestr := fsion.Get("name").ValueStr()
  3389. offset := fsion.Get("offset").ValueDefaultInt(0)
  3390. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3391. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3392. parammaps := fsion.Get("parammaps")
  3393. tx := restful.Engine.NewSession()
  3394. err := tx.Begin()
  3395. defer func() {
  3396. switch {
  3397. case err != nil:
  3398. logging.Error("tx.Begin 事务启动失败__error:", err)
  3399. if tx != nil {
  3400. tx.Rollback()
  3401. }
  3402. default:
  3403. if tx != nil {
  3404. err = tx.Commit()
  3405. }
  3406. }
  3407. if tx != nil {
  3408. tx.Close()
  3409. }
  3410. }()
  3411. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3412. s_params := make([]interface{}, 0)
  3413. paramslist := strings.Split(p, ",")
  3414. if len(paramslist) > 0 && p != "" {
  3415. for _, value := range paramslist {
  3416. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3417. if tempv, exists := c.Get("jwt_username"); exists {
  3418. s_params = append(s_params, tempv.(string))
  3419. } else {
  3420. s_params = append(s_params, "")
  3421. }
  3422. } else {
  3423. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3424. }
  3425. }
  3426. }
  3427. tmrtnameStr := ""
  3428. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3429. if len(tmrtnameStr) == 0 {
  3430. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3431. } else {
  3432. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3433. }
  3434. }
  3435. if len(tmrtnameStr) > 0 {
  3436. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3437. }
  3438. sql += " ORDER BY d.intime"
  3439. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3440. if err != nil {
  3441. logging.Error("GetDataByName err: ", err)
  3442. msg := geterrmsg(err.Error())
  3443. appG.Response(http.StatusOK, e.ERROR, msg)
  3444. } else {
  3445. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3446. }
  3447. }
  3448. func UpdateFeedtempletStatus(c *gin.Context) {
  3449. appG := app.Gin{C: c}
  3450. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3451. fsion := gofasion.NewFasion(string(dataByte))
  3452. parammaps := fsion.Get("parammaps")
  3453. tx := restful.Engine.NewSession()
  3454. tx.Begin()
  3455. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3456. if err != nil {
  3457. tx.Rollback()
  3458. logs.Error(err)
  3459. appG.Response(http.StatusOK, e.ERROR, err)
  3460. return
  3461. }
  3462. tx.Commit()
  3463. appG.Response(http.StatusOK, e.SUCCESS, true)
  3464. }
  3465. func AddFtdry(c *gin.Context) {
  3466. appG := app.Gin{C: c}
  3467. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3468. fsion := gofasion.NewFasion(string(dataByte))
  3469. sqlnamestr := fsion.Get("name").ValueStr()
  3470. s_params := make([]interface{}, 0)
  3471. tx := restful.Engine.NewSession()
  3472. err := tx.Begin()
  3473. defer func() {
  3474. switch {
  3475. case err != nil:
  3476. if tx != nil {
  3477. tx.Rollback()
  3478. }
  3479. default:
  3480. if tx != nil {
  3481. err = tx.Commit()
  3482. }
  3483. }
  3484. if tx != nil {
  3485. tx.Close()
  3486. }
  3487. }()
  3488. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3489. if sql != "" {
  3490. parammaps := fsion.Get("parammaps")
  3491. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3492. paramslist := strings.Split(p, ",")
  3493. if len(paramslist) > 0 && p != "" {
  3494. for _, value := range paramslist {
  3495. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3496. if tempv, exists := c.Get("jwt_username"); exists {
  3497. s_params = append(s_params, tempv.(string))
  3498. } else {
  3499. s_params = append(s_params, "")
  3500. }
  3501. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3502. ids, err := setting.SnowIds.NextId()
  3503. if err != nil {
  3504. ids = time.Now().UnixNano()
  3505. logging.Info("create SnowIds err", err)
  3506. }
  3507. s_params = append(s_params, ids)
  3508. } else {
  3509. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3510. }
  3511. }
  3512. }
  3513. var actweight float64
  3514. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3515. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3516. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3517. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3518. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3519. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3520. 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()
  3521. if err != nil {
  3522. logging.Error("AddFtdry err: ", err)
  3523. msg := geterrmsg(err.Error())
  3524. appG.Response(http.StatusOK, e.ERROR, msg)
  3525. }
  3526. if len(actweightList) > 0 {
  3527. for _, item := range actweightList {
  3528. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3529. if err != nil {
  3530. logging.Error("AddFtdry err: ", err)
  3531. msg := geterrmsg(err.Error())
  3532. appG.Response(http.StatusOK, e.ERROR, msg)
  3533. }
  3534. actweight = fl
  3535. }
  3536. } else {
  3537. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3538. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3539. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3540. if err != nil {
  3541. logging.Error("AddFtdry err: ", err)
  3542. msg := geterrmsg(err.Error())
  3543. appG.Response(http.StatusOK, e.ERROR, msg)
  3544. }
  3545. for _, item := range dryList {
  3546. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3547. if err != nil {
  3548. logging.Error("AddFtdry err: ", err)
  3549. msg := geterrmsg(err.Error())
  3550. appG.Response(http.StatusOK, e.ERROR, msg)
  3551. }
  3552. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3553. }
  3554. }
  3555. if sqlnamestr == "insertFtdry" {
  3556. s_params = append(s_params, actweight)
  3557. } else if sqlnamestr == "updateFtdry" {
  3558. sql = fmt.Sprintf(sql, actweight)
  3559. }
  3560. queryData, err := execDataBySqlT(sql, s_params, tx)
  3561. if err != nil {
  3562. logging.Error("AddFtdry err: ", err)
  3563. msg := geterrmsg(err.Error())
  3564. appG.Response(http.StatusOK, e.ERROR, msg)
  3565. } else {
  3566. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3567. }
  3568. } else {
  3569. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3570. }
  3571. }
  3572. func CheckDates(c *gin.Context) {
  3573. tx := restful.Engine.NewSession()
  3574. defer tx.Close()
  3575. appG := app.Gin{C: c}
  3576. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3577. tempval_ := make(map[string]interface{})
  3578. tempCommon := make(map[string]interface{})
  3579. tempval := make([]map[string]interface{}, 0)
  3580. err := json.Unmarshal(dataByte, &tempval_)
  3581. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3582. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3583. if err != nil {
  3584. } else {
  3585. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3586. tempCommon = v
  3587. }
  3588. if v, ok := tempval_["data"].([]interface{}); ok {
  3589. for _, Tvalue := range v {
  3590. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3591. tempval = append(tempval, v1)
  3592. }
  3593. }
  3594. }
  3595. if err == nil {
  3596. if tempv, exists := c.Get("jwt_username"); exists {
  3597. tempCommon["jwt_username"] = tempv.(string)
  3598. }
  3599. for _, paramvalue := range tempval {
  3600. if _, ok := paramvalue["resultname"]; !ok {
  3601. paramvalue["resultname"] = paramvalue["name"]
  3602. }
  3603. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3604. if err != nil {
  3605. logging.Error("ExecDataParam error:", err)
  3606. }
  3607. }
  3608. if err == nil {
  3609. vmsg := ""
  3610. for _, item := range tempval {
  3611. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3612. for _, childrenList := range list.([]interface{}) {
  3613. for k, children := range childrenList.(map[string]interface{}) {
  3614. if k != "children" {
  3615. continue
  3616. }
  3617. for _, v := range children.([]map[string]interface{}) {
  3618. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3619. if k1 == "list" {
  3620. for _, v2 := range v1.([]map[string]interface{}) {
  3621. if v2["vmsg"].(string) != "1" {
  3622. if len(vmsg) == 0 {
  3623. vmsg = v2["vmsg"].(string)
  3624. } else {
  3625. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3626. }
  3627. }
  3628. }
  3629. }
  3630. }
  3631. }
  3632. }
  3633. }
  3634. }
  3635. }
  3636. if len(vmsg) > 0 {
  3637. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3638. } else {
  3639. appG.Response(http.StatusOK, e.SUCCESS, true)
  3640. }
  3641. } else {
  3642. msg := geterrmsg(err.Error())
  3643. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3644. }
  3645. }
  3646. }
  3647. if err != nil {
  3648. msg := geterrmsg(err.Error())
  3649. appG.Response(http.StatusOK, e.ERROR, msg)
  3650. }
  3651. }
  3652. 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) {
  3653. sqlname := fasion["name"].(string)
  3654. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3655. if v, ok := fasion["type"]; ok {
  3656. sqltype = v.(string)
  3657. }
  3658. sql := ""
  3659. p := ""
  3660. s_params := make([]interface{}, 0)
  3661. if sqltype != "" {
  3662. sql, p = restful.GetSqlByName(sqlname, tx)
  3663. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3664. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3665. paramslist := strings.Split(p, ",")
  3666. if len(paramslist) > 0 && p != "" {
  3667. for _, value := range paramslist {
  3668. ss := ""
  3669. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3670. ids, err := setting.SnowIds.NextId()
  3671. if err != nil {
  3672. ids = time.Now().UnixNano()
  3673. logging.Info("create SnowIds err", err)
  3674. }
  3675. s_params = append(s_params, ids)
  3676. } else {
  3677. if ss == "" && CommonParamMap != nil {
  3678. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3679. ss = valuestring
  3680. tempstrb := strings.IndexAny(valuestring, "@")
  3681. tempstre := strings.IndexAny(valuestring, ".")
  3682. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3683. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3684. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3685. }
  3686. } else {
  3687. ss = ""
  3688. }
  3689. }
  3690. }
  3691. if ss == "" && ParentParamMap != nil {
  3692. ss = getParamValue_(v, value, ParentParamMap)
  3693. }
  3694. if ss == "" && sameParamMap != nil {
  3695. ss = getParamValue(v, value, sameParamMap)
  3696. }
  3697. if ss == "" && ParamMap != nil {
  3698. ss = getParamValue(v, value, ParamMap)
  3699. }
  3700. s_params = append(s_params, ss)
  3701. }
  3702. }
  3703. }
  3704. }
  3705. }
  3706. if sql == "" {
  3707. sqltype = ""
  3708. }
  3709. if sql != "" {
  3710. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3711. if err != nil {
  3712. return nil, err
  3713. }
  3714. // fmt.Println(tempValParam)
  3715. return tempValParam.(map[string]interface{}), nil
  3716. } else {
  3717. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3718. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3719. if err != nil {
  3720. return nil, err
  3721. }
  3722. return nil, err
  3723. }
  3724. }
  3725. return nil, nil
  3726. }
  3727. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3728. var err error
  3729. subarray, ok := fasion["children"]
  3730. if ok {
  3731. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3732. tempVal_arrary := make([]map[string]interface{}, 0)
  3733. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3734. tempVal_ := make(map[string]interface{})
  3735. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3736. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3737. } else {
  3738. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3739. }
  3740. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3741. if err != nil {
  3742. return err
  3743. }
  3744. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3745. }
  3746. v.(map[string]interface{})["children"] = tempVal_arrary
  3747. }
  3748. }
  3749. return nil
  3750. }
  3751. func FpdImportExcel(c *gin.Context) {
  3752. appG := app.Gin{C: c}
  3753. inputdata := ""
  3754. c.Request.ParseForm()
  3755. params := c.Request.Form
  3756. file, _, err := c.Request.FormFile("file")
  3757. if err != nil {
  3758. appG.Response(http.StatusOK, e.ERROR, err)
  3759. return
  3760. }
  3761. sqlnamestrs := params.Get("name")
  3762. sheetname := params.Get("sheetname")
  3763. pastureid := params.Get("pastureid")
  3764. // importParams := params.Get("importParams")
  3765. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3766. // 必输项参数 (字符串格式 "field1,field2,field3")
  3767. requiredParams := params.Get("requiredParams")
  3768. // 日期参数
  3769. dateParams := params.Get("dateParams")
  3770. // 数字参数
  3771. numParams := params.Get("numParams")
  3772. //将字符串分割开
  3773. dateParamslist := strings.Split(dateParams, ",")
  3774. requiredParamslist := strings.Split(requiredParams, ",")
  3775. numParamslist := strings.Split(numParams, ",")
  3776. queryData := make([]interface{}, 0)
  3777. sqlslist := strings.Split(sqlnamestrs, ",")
  3778. xlsx1, err := excelize.OpenReader(file)
  3779. if err != nil {
  3780. fmt.Println(err)
  3781. return
  3782. }
  3783. ok := 0
  3784. error := 0
  3785. isdone := true
  3786. tx := restful.Engine.NewSession()
  3787. defer tx.Close()
  3788. 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
  3789. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3790. if err != nil {
  3791. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3792. return
  3793. }
  3794. rows := xlsx1.GetRows(sheetname)
  3795. // 限制10000条,多余的截取掉
  3796. if len(rows) > 10000 {
  3797. rows = rows[:10000]
  3798. }
  3799. for i, row := range rows {
  3800. if i > 0 {
  3801. entry := make(map[string]interface{})
  3802. outentry := make(map[string]interface{})
  3803. for j, colCell := range rows[0] {
  3804. for k, colCell1 := range row {
  3805. if j == k {
  3806. outentry[colCell] = colCell1
  3807. entry[colCell] = colCell1
  3808. }
  3809. }
  3810. }
  3811. inputdata = ""
  3812. a := ""
  3813. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3814. //校验日期格式
  3815. for _, v := range dateParamslist {
  3816. if v == "" {
  3817. continue
  3818. }
  3819. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3820. dtime, err := TransfTime(d.(string))
  3821. if err != nil {
  3822. a = strings.Trim(v, " ")
  3823. break
  3824. }
  3825. outentry[strings.Trim(v, " ")] = dtime
  3826. }
  3827. }
  3828. if a != "" {
  3829. outentry["error_msg"] = a + " 格式错误"
  3830. error++
  3831. queryData = append(queryData, outentry)
  3832. continue
  3833. }
  3834. a = ""
  3835. //校验必填格式
  3836. for _, v := range requiredParamslist {
  3837. if v == "" {
  3838. continue
  3839. }
  3840. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3841. a = strings.Trim(v, " ")
  3842. break
  3843. }
  3844. }
  3845. if a != "" {
  3846. outentry["error_msg"] = a + " 未填或格式错误"
  3847. error++
  3848. queryData = append(queryData, outentry)
  3849. continue
  3850. }
  3851. a = ""
  3852. //校验数字格式
  3853. for _, v := range numParamslist {
  3854. if v == "" {
  3855. continue
  3856. }
  3857. d, ok := outentry[strings.Trim(v, " ")]
  3858. if !ok || d == "" {
  3859. outentry[strings.Trim(v, " ")] = 0
  3860. } else {
  3861. var fl float64
  3862. switch d.(type) {
  3863. case string:
  3864. fl, err = strconv.ParseFloat(d.(string), 64)
  3865. }
  3866. if err != nil || fl < 0 {
  3867. a = strings.Trim(v, " ")
  3868. break
  3869. }
  3870. }
  3871. }
  3872. if a != "" {
  3873. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3874. error++
  3875. queryData = append(queryData, outentry)
  3876. continue
  3877. }
  3878. errExist := false
  3879. for _, sqlnamestr := range sqlslist {
  3880. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3881. paramslist := strings.Split(paramslists, ",")
  3882. if len(paramslist) > 0 {
  3883. s_params := make([]interface{}, 0)
  3884. for _, value := range paramslist {
  3885. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3886. if tempv, exists := c.Get("jwt_username"); exists {
  3887. s_params = append(s_params, tempv.(string))
  3888. } else {
  3889. s_params = append(s_params, "")
  3890. }
  3891. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3892. s_params = append(s_params, pastureid)
  3893. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3894. ids, err := setting.SnowIds.NextId()
  3895. if err != nil {
  3896. ids = time.Now().UnixNano()
  3897. logging.Info("create SnowIds err", err)
  3898. }
  3899. s_params = append(s_params, ids)
  3900. } else {
  3901. if outentry[strings.Trim(value, " ")] == nil {
  3902. s_params = append(s_params, "")
  3903. } else {
  3904. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3905. }
  3906. }
  3907. }
  3908. outentry["input"] = inputdata
  3909. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3910. if err != nil {
  3911. errExist = true
  3912. // if tx != nil {
  3913. // tx.Rollback()
  3914. // }
  3915. // if tx != nil {
  3916. // tx.Close()
  3917. // }
  3918. msg := geterrmsg(err.Error())
  3919. outentry["error_msg"] = msg
  3920. error++
  3921. queryData = append(queryData, outentry)
  3922. isdone = true
  3923. break
  3924. } else {
  3925. if len(returnmsgmap1) > 0 {
  3926. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3927. // if tx != nil {
  3928. // tx.Rollback()
  3929. // }
  3930. // if tx != nil {
  3931. // tx.Close()
  3932. // }
  3933. msg := geterrmsg(va.(string))
  3934. outentry["error_msg"] = msg
  3935. error++
  3936. queryData = append(queryData, outentry)
  3937. isdone = true
  3938. break
  3939. }
  3940. }
  3941. isdone = false
  3942. }
  3943. }
  3944. }
  3945. if !errExist {
  3946. dataexcel := make(map[string]interface{}, 0)
  3947. if _, ok := outentry["栏舍名称"]; ok {
  3948. dataexcel["barname"] = outentry["栏舍名称"]
  3949. }
  3950. if _, ok := outentry["实际牛头数"]; ok {
  3951. dataexcel["ccount"] = outentry["实际牛头数"]
  3952. }
  3953. if _, ok := outentry["系数(%)"]; ok {
  3954. dataexcel["ratio"] = outentry["系数(%)"]
  3955. }
  3956. if _, ok := outentry["配方模板"]; ok {
  3957. dataexcel["ftname"] = outentry["配方模板"]
  3958. }
  3959. if _, ok := outentry["补料配方"]; ok {
  3960. dataexcel["ptsfname"] = outentry["补料配方"]
  3961. }
  3962. if _, ok := outentry["第一班比例(%)"]; ok {
  3963. dataexcel["1"] = outentry["第一班比例(%)"]
  3964. }
  3965. if _, ok := outentry["第二班比例(%)"]; ok {
  3966. dataexcel["2"] = outentry["第二班比例(%)"]
  3967. }
  3968. if _, ok := outentry["第三班比例(%)"]; ok {
  3969. dataexcel["3"] = outentry["第三班比例(%)"]
  3970. }
  3971. if _, ok := outentry["第四班比例(%)"]; ok {
  3972. dataexcel["4"] = outentry["第四班比例(%)"]
  3973. }
  3974. if _, ok := outentry["第五班比例(%)"]; ok {
  3975. dataexcel["5"] = outentry["第四班比例(%)"]
  3976. }
  3977. if _, ok := outentry["第六班比例(%)"]; ok {
  3978. dataexcel["6"] = outentry["第六班比例(%)"]
  3979. }
  3980. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3981. if err != nil {
  3982. logs.Error(err)
  3983. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3984. return
  3985. }
  3986. if !existbar {
  3987. continue
  3988. }
  3989. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  3990. if err != nil {
  3991. logs.Error(err)
  3992. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3993. return
  3994. }
  3995. if !ftexist {
  3996. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  3997. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3998. if err != nil {
  3999. logs.Error(err)
  4000. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4001. return
  4002. }
  4003. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4004. if err != nil {
  4005. logs.Error(err)
  4006. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4007. return
  4008. }
  4009. }
  4010. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4011. if err != nil {
  4012. logs.Error(err)
  4013. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4014. return
  4015. }
  4016. if !exist {
  4017. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4018. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4019. if err != nil {
  4020. logs.Error(err)
  4021. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4022. return
  4023. }
  4024. }
  4025. var feedpargs []interface{}
  4026. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4027. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4028. if _, ok := dataexcel["ftname"]; ok {
  4029. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4030. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4031. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4032. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4033. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4034. } else {
  4035. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4036. }
  4037. if _, ok := dataexcel["ptsfname"]; ok {
  4038. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4039. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4040. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4041. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4042. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4043. } else {
  4044. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4045. }
  4046. upFeedpSql += " where barname = ? and pastureid = ? "
  4047. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4048. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4049. if err != nil {
  4050. logs.Error(err)
  4051. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4052. return
  4053. }
  4054. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4055. if err != nil {
  4056. logs.Error(err)
  4057. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4058. return
  4059. }
  4060. if !exist1 {
  4061. _, 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) `,
  4062. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4063. if err != nil {
  4064. logs.Error(err)
  4065. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4066. return
  4067. }
  4068. }
  4069. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4070. if err != nil {
  4071. logs.Error(err)
  4072. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4073. return
  4074. }
  4075. if !exist2 {
  4076. _, 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) `,
  4077. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4078. if err != nil {
  4079. logs.Error(err)
  4080. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4081. return
  4082. }
  4083. }
  4084. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4085. if err != nil {
  4086. logs.Error(err)
  4087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4088. return
  4089. }
  4090. if !exist3 {
  4091. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  4092. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4093. if err != nil {
  4094. logs.Error(err)
  4095. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4096. return
  4097. }
  4098. }
  4099. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4100. if err != nil {
  4101. logs.Error(err)
  4102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4103. return
  4104. }
  4105. if !exist4 {
  4106. _, 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) `,
  4107. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4108. if err != nil {
  4109. logs.Error(err)
  4110. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4111. return
  4112. }
  4113. }
  4114. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4115. if err != nil {
  4116. logs.Error(err)
  4117. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4118. return
  4119. }
  4120. if !exist5 {
  4121. _, 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) `,
  4122. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4123. if err != nil {
  4124. logs.Error(err)
  4125. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4126. return
  4127. }
  4128. }
  4129. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4130. if err != nil {
  4131. logs.Error(err)
  4132. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4133. return
  4134. }
  4135. if !exist6 {
  4136. _, 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) `,
  4137. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4138. if err != nil {
  4139. logs.Error(err)
  4140. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4141. return
  4142. }
  4143. }
  4144. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4145. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4146. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4147. and pastureid = ? and times = ?`
  4148. var fpdargs1 []interface{}
  4149. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4150. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4151. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4152. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4153. if err != nil {
  4154. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4155. return
  4156. }
  4157. var fpdargs2 []interface{}
  4158. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4159. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4160. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4161. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4162. if err != nil {
  4163. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4164. return
  4165. }
  4166. var fpdargs3 []interface{}
  4167. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4168. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4169. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4170. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4171. if err != nil {
  4172. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4173. return
  4174. }
  4175. var fpdargs4 []interface{}
  4176. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4177. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4178. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4179. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4180. if err != nil {
  4181. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4182. return
  4183. }
  4184. var fpdargs5 []interface{}
  4185. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4186. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4187. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4188. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4189. if err != nil {
  4190. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4191. return
  4192. }
  4193. var fpdargs6 []interface{}
  4194. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4195. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4196. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4197. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4198. if err != nil {
  4199. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4200. return
  4201. }
  4202. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4203. 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()
  4204. if err != nil {
  4205. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4206. return
  4207. }
  4208. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4209. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4210. upFpdetailList := make([]*upFpdetail, 0)
  4211. for _, newfpd := range newList {
  4212. for _, oldfpd := range oldFpdList {
  4213. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4214. var oldweight, newweight float64
  4215. if oldfpd["weight"] != nil {
  4216. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4217. }
  4218. if newfpd["weight"] != nil {
  4219. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4220. }
  4221. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4222. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4223. Old: oldweight,
  4224. New: newweight,
  4225. Times: newfpd["times"].(int64),
  4226. Ptid: newfpd["ptid"].(int64),
  4227. Fweight: fweight,
  4228. Id: oldfpd["id"].(int64),
  4229. })
  4230. break
  4231. }
  4232. }
  4233. }
  4234. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4235. }
  4236. }
  4237. if !isdone {
  4238. ok++
  4239. isdone = true
  4240. }
  4241. }
  4242. data := make(map[string]interface{})
  4243. data["result"] = queryData
  4244. data["success"] = ok
  4245. data["err_count"] = error
  4246. appG.Response(http.StatusOK, e.SUCCESS, data)
  4247. }
  4248. type upFpdetail struct {
  4249. Old float64
  4250. New float64
  4251. Times int64
  4252. Ptid int64
  4253. Fweight float64
  4254. Id int64
  4255. // Ptsid string
  4256. }
  4257. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4258. tx := restful.Engine.NewSession()
  4259. defer tx.Close()
  4260. tx.Begin()
  4261. 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 `,
  4262. pastureid, barname).Query().List()
  4263. if err != nil {
  4264. logs.Error(err)
  4265. }
  4266. for _, fpd := range fpdList {
  4267. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4268. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4269. pastureid, fpd["id"], fpd["times"]).Query().List()
  4270. if err != nil {
  4271. tx.Rollback()
  4272. logs.Error(err)
  4273. return err
  4274. }
  4275. var lweight float64
  4276. for _, lppland := range lpplandList {
  4277. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4278. lweight += lweight1
  4279. }
  4280. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4281. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4282. if fpdweight >= ptuse && lweight == ptuse {
  4283. continue
  4284. } else {
  4285. if lweight <= fpdweight {
  4286. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4287. if err != nil {
  4288. tx.Rollback()
  4289. logs.Error(err)
  4290. return err
  4291. }
  4292. } else {
  4293. weight := lweight - fpdweight
  4294. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4295. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4296. if err != nil {
  4297. tx.Rollback()
  4298. logs.Error(err)
  4299. return err
  4300. }
  4301. for _, lppland := range lpplandList {
  4302. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4303. if weight >= lpplandlweight {
  4304. weight = weight - lpplandlweight
  4305. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4306. if err != nil {
  4307. tx.Rollback()
  4308. logs.Error(err)
  4309. return err
  4310. }
  4311. } else {
  4312. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4313. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4314. if err != nil {
  4315. tx.Rollback()
  4316. logs.Error(err)
  4317. return err
  4318. }
  4319. weight = 0
  4320. break
  4321. }
  4322. }
  4323. }
  4324. }
  4325. }
  4326. for _, list := range dataList {
  4327. ftmap := make(map[string]interface{})
  4328. ftmap["old"] = list.Old
  4329. ftmap["new"] = list.New
  4330. ftmap["times"] = list.Times
  4331. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4332. ftmap["ptsid"] = ""
  4333. // fmt.Println(ftmap)
  4334. 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 ,
  4335. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4336. WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4337. UNION
  4338. 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 ,
  4339. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4340. WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  4341. order by t.barname,t.times`, pastureid, barname, ftmap["times"], pastureid, barname, ftmap["times"]).Query().List()
  4342. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4343. if err != nil {
  4344. tx.Rollback()
  4345. logs.Error(err)
  4346. }
  4347. for _, fpd := range fpdDataList {
  4348. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4349. fttype := -1
  4350. if ftmap["ptid"].(string) != "-1" {
  4351. fttype = 1
  4352. }
  4353. var fweight float64
  4354. var lweight float64
  4355. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4356. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4357. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4358. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4359. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4360. if err != nil {
  4361. tx.Rollback()
  4362. logs.Error(err)
  4363. }
  4364. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4365. // ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4366. var w float64
  4367. var status int
  4368. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  4369. if weight >= 0 {
  4370. continue
  4371. }
  4372. w = weight
  4373. status = 0
  4374. } else {
  4375. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4376. continue
  4377. }
  4378. w = weight
  4379. status = 1
  4380. }
  4381. for _, lppland := range lpplandtl1List {
  4382. lweight += lppland.Lweight
  4383. }
  4384. for _, lppland := range lpplandtl1List {
  4385. if status == 1 {
  4386. // if w <= lppland.Lweight {
  4387. if lppland.Maxweight <= lweight {
  4388. continue
  4389. }
  4390. if w+lweight <= lppland.Maxweight {
  4391. lppland.Lweight += w
  4392. lweight += w
  4393. fweight += w
  4394. w = 0
  4395. } else {
  4396. w = w - (lppland.Maxweight - lweight)
  4397. n := (lppland.Maxweight - lweight)
  4398. lppland.Lweight = lppland.Lweight + n
  4399. lweight += n
  4400. fweight += n
  4401. }
  4402. } else {
  4403. if lppland.Lweight == 0 {
  4404. continue
  4405. }
  4406. if w+lppland.Lweight >= 0 {
  4407. lppland.Lweight = lppland.Lweight + w
  4408. lweight = lweight + w
  4409. fweight = fweight + w
  4410. w = 0
  4411. } else {
  4412. w = w + lppland.Lweight
  4413. lweight = lweight - lppland.Lweight
  4414. fweight = fweight - lppland.Lweight
  4415. lppland.Lweight = 0
  4416. }
  4417. }
  4418. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4419. if err != nil {
  4420. tx.Rollback()
  4421. logs.Error(err)
  4422. return err
  4423. }
  4424. break
  4425. }
  4426. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4427. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4428. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4429. if err != nil {
  4430. tx.Rollback()
  4431. logs.Error(err)
  4432. }
  4433. if w == 0 {
  4434. break
  4435. }
  4436. }
  4437. }
  4438. }
  4439. // for _, data := range dataList {
  4440. // fttype := -1
  4441. // if data.Ptid != -1 {
  4442. // fttype = 1
  4443. // }
  4444. // var fweight float64
  4445. // var lweight float64
  4446. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4447. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4448. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4449. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4450. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4451. // if err != nil {
  4452. // tx.Rollback()
  4453. // logs.Error(err)
  4454. // return err
  4455. // }
  4456. // weight := data.Fweight
  4457. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4458. // var w float64
  4459. // var status int
  4460. // if data.New < data.Old {
  4461. // if weight >= 0 {
  4462. // continue
  4463. // }
  4464. // w = weight
  4465. // status = 0
  4466. // } else {
  4467. // // if weight-(data.New-data.Old) > 0 {
  4468. // // continue
  4469. // // }
  4470. // w = data.New - data.Old
  4471. // status = 1
  4472. // }
  4473. // for _, lppland := range lpplandtl1List {
  4474. // var lppdata lpplandtlInfo
  4475. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4476. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4477. // if err != nil {
  4478. // tx.Rollback()
  4479. // logs.Error(err)
  4480. // return err
  4481. // }
  4482. // lweight = lppdata.Lweight
  4483. // if status == 1 {
  4484. // // if w <= lppland.Lweight {
  4485. // if lppland.Maxweight <= lweight {
  4486. // continue
  4487. // }
  4488. // if w+lweight <= lppland.Maxweight {
  4489. // lppland.Lweight += w
  4490. // lweight += w
  4491. // fweight += w
  4492. // w = 0
  4493. // } else {
  4494. // w = w - (lppland.Maxweight - lweight)
  4495. // n := (lppland.Maxweight - lweight)
  4496. // lppland.Lweight = lppland.Lweight + n
  4497. // lweight += n
  4498. // fweight += n
  4499. // }
  4500. // } else {
  4501. // if lppland.Lweight == 0 {
  4502. // continue
  4503. // }
  4504. // if w+lppland.Lweight >= 0 {
  4505. // lppland.Lweight = lppland.Lweight + w
  4506. // lweight = lweight + w
  4507. // fweight = fweight + w
  4508. // w = 0
  4509. // } else {
  4510. // w = w + lppland.Lweight
  4511. // lweight = lweight - lppland.Lweight
  4512. // fweight = fweight - lppland.Lweight
  4513. // lppland.Lweight = 0
  4514. // }
  4515. // }
  4516. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4517. // if err != nil {
  4518. // tx.Rollback()
  4519. // logs.Error(err)
  4520. // return err
  4521. // }
  4522. // break
  4523. // }
  4524. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4525. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4526. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4527. // if err != nil {
  4528. // tx.Rollback()
  4529. // logs.Error(err)
  4530. // return err
  4531. // }
  4532. // // if w == 0 {
  4533. // // break
  4534. // // }
  4535. // // }
  4536. // }
  4537. err = tx.Commit()
  4538. if err != nil {
  4539. logs.Error(err)
  4540. tx.Rollback()
  4541. return err
  4542. }
  4543. now := time.Now()
  4544. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4545. if err != nil {
  4546. logs.Error(err)
  4547. return nil
  4548. }
  4549. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4550. if err != nil {
  4551. logs.Error(err)
  4552. return nil
  4553. }
  4554. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4555. if err != nil {
  4556. logs.Error(err)
  4557. return nil
  4558. }
  4559. for _, newLpplandtl1 := range newLpplandtl1List {
  4560. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4561. background,cowcount,ccountradio,lweighthis,createdate)
  4562. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4563. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4564. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4565. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4566. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4567. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4568. if err != nil {
  4569. logs.Error(err)
  4570. // appG.Response(http.StatusOK, e.ERROR, false)
  4571. return nil
  4572. }
  4573. }
  4574. for _, newFpd := range newFpdDataList {
  4575. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4576. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4577. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4578. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4579. if err != nil {
  4580. logs.Error(err)
  4581. // appG.Response(http.StatusOK, e.ERROR, false)
  4582. return nil
  4583. }
  4584. }
  4585. for _, newFeedp := range newFeedpList {
  4586. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4587. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4588. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4589. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4590. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4591. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4592. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4593. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4594. if err != nil {
  4595. logs.Error(err)
  4596. // appG.Response(http.StatusOK, e.ERROR, false)
  4597. return nil
  4598. }
  4599. }
  4600. return nil
  4601. }
  4602. func DeleteFTdetail(c *gin.Context) {
  4603. appG := app.Gin{C: c}
  4604. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4605. fsion := gofasion.NewFasion(string(dataByte))
  4606. parammaps := fsion.Get("parammaps")
  4607. pastureid := parammaps.Get("pastureid").ValueStr()
  4608. ftid := parammaps.Get("ftid").ValueStr()
  4609. tx := restful.Engine.NewSession()
  4610. defer tx.Close()
  4611. tx.Begin()
  4612. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4613. if err != nil {
  4614. tx.Rollback()
  4615. logs.Error(err)
  4616. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4617. return
  4618. }
  4619. if parammaps.Get("type").ValueStr() == "1" {
  4620. _, err := tx.SQL(`UPDATE feedp fp
  4621. set
  4622. fp.ftweight= IFNULL(IF(
  4623. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4624. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4625. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4626. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4627. ),0),fp.feedweight = IFNULL(IF(
  4628. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4629. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4630. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4631. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4632. ),0) +ifnull(fp.supplyweight,0)
  4633. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4634. if err != nil {
  4635. tx.Rollback()
  4636. logs.Error(err)
  4637. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4638. return
  4639. }
  4640. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4641. _, err = tx.SQL(`
  4642. UPDATE fpdetail fpd
  4643. INNER JOIN feedp fp
  4644. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4645. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4646. ptuse= 0
  4647. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4648. if err != nil {
  4649. tx.Rollback()
  4650. logs.Error(err)
  4651. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4652. return
  4653. }
  4654. } else {
  4655. _, err := tx.SQL(`UPDATE feedp fp
  4656. SET
  4657. fp.supplyweight= IFNULL(IF(
  4658. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4659. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4660. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4661. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4662. ),0),fp.feedweight = IFNULL(IF(
  4663. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4664. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4665. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4666. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4667. ),0) + ifnull(fp.supplyweight,0)
  4668. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4669. if err != nil {
  4670. tx.Rollback()
  4671. logs.Error(err)
  4672. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4673. return
  4674. }
  4675. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4676. _, err = tx.SQL(`
  4677. UPDATE fpdetail fpd
  4678. INNER JOIN feedp fp
  4679. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4680. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4681. ptsrate = 0
  4682. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4683. if err != nil {
  4684. tx.Rollback()
  4685. logs.Error(err)
  4686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4687. return
  4688. }
  4689. }
  4690. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4691. if err != nil {
  4692. tx.Rollback()
  4693. logs.Error(err)
  4694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4695. return
  4696. }
  4697. err = tx.Commit()
  4698. if err != nil {
  4699. tx.Rollback()
  4700. logs.Error(err)
  4701. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4702. return
  4703. }
  4704. appG.Response(http.StatusOK, e.SUCCESS, true)
  4705. }
  4706. func DeleteSpillageAll(c *gin.Context) {
  4707. appG := app.Gin{C: c}
  4708. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4709. fsion := gofasion.NewFasion(string(dataByte))
  4710. parammaps := fsion.Get("parammaps")
  4711. pastureid := parammaps.Get("pastureid").ValueStr()
  4712. times := parammaps.Get("times").ValueStr()
  4713. barid := parammaps.Get("barid").ValueStr()
  4714. tx := restful.Engine.NewSession()
  4715. defer tx.Close()
  4716. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4717. if err != nil {
  4718. logs.Error(err)
  4719. appG.Response(http.StatusOK, e.ERROR, false)
  4720. return
  4721. }
  4722. now := time.Now()
  4723. for _, item := range lpplandtl1List {
  4724. go func(item map[string]interface{}) {
  4725. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4726. background,cowcount,ccountradio,lweighthis,createdate)
  4727. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4728. item["pastureid"], item["lppid"], item["barid"],
  4729. item["barname"], item["fpdid"], item["fttype"],
  4730. item["lweight"], item["sort"], item["tmrid"],
  4731. item["tmrname"], item["background"], item["cowcount"],
  4732. item["ccountradio"], item["lweighthis"], now).Execute()
  4733. if err != nil {
  4734. logs.Error(err)
  4735. appG.Response(http.StatusOK, e.ERROR, false)
  4736. return
  4737. }
  4738. }(item)
  4739. }
  4740. tx.Begin()
  4741. _, 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()
  4742. if err != nil {
  4743. tx.Rollback()
  4744. logs.Error(err)
  4745. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4746. return
  4747. }
  4748. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4749. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4750. if err != nil {
  4751. tx.Rollback()
  4752. logs.Error(err)
  4753. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4754. return
  4755. }
  4756. err = tx.Commit()
  4757. if err != nil {
  4758. tx.Rollback()
  4759. logs.Error(err)
  4760. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4761. return
  4762. }
  4763. appG.Response(http.StatusOK, e.SUCCESS, true)
  4764. }
  4765. func GetTMRListEnableTypeAll(c *gin.Context) {
  4766. appG := app.Gin{C: c}
  4767. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4768. fsion := gofasion.NewFasion(string(dataByte))
  4769. parammaps := fsion.Get("parammaps")
  4770. pastureid := parammaps.Get("pastureid").ValueStr()
  4771. tx := restful.Engine.NewSession()
  4772. defer tx.Close()
  4773. dataList, err := tx.SQL(`SELECT
  4774. eqcode,
  4775. tname,
  4776. datacaptureno,
  4777. trim(tclassid) tclassid,
  4778. concat(tname,' / ',eqcode) tmrmix,
  4779. d.label tclassname,
  4780. maxstirfeed,
  4781. remark,
  4782. tmr.enable,
  4783. TRIM(tmr.id) id,
  4784. TRIM(tmr.pastureid)pastureid
  4785. FROM
  4786. tmr
  4787. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4788. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4789. ORDER BY id DESC`, pastureid).Query().List()
  4790. if err != nil {
  4791. logs.Error(err)
  4792. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4793. return
  4794. }
  4795. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4796. if err != nil {
  4797. logs.Error(err)
  4798. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4799. return
  4800. }
  4801. var carNum int64
  4802. for _, sysopt := range sysoptData {
  4803. if sysopt["inforvalue"] == nil {
  4804. carNum = 1
  4805. } else {
  4806. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4807. }
  4808. }
  4809. id := 200
  4810. n := 0
  4811. for i := carNum; i > 0; i-- {
  4812. id++
  4813. n++
  4814. data := make(map[string]interface{}, 0)
  4815. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4816. data["tname"] = fmt.Sprintf("任意车%d", n)
  4817. data["datacaptureno"] = -2
  4818. data["tclassid"] = -2
  4819. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4820. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4821. data["maxstirfeed"] = 100000
  4822. data["remark"] = fmt.Sprintf("任意车%d", n)
  4823. data["enable"] = 1
  4824. data["id"] = fmt.Sprintf("%d", id)
  4825. data["pastureid"] = pastureid
  4826. dataList = append(dataList, data)
  4827. }
  4828. // UNION ALL
  4829. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4830. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4831. }
  4832. func GetFeedpHistory(c *gin.Context) {
  4833. appG := app.Gin{C: c}
  4834. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4835. fsion := gofasion.NewFasion(string(dataByte))
  4836. // parammaps := fsion.Get("parammaps")
  4837. bar := fsion.Get("barname").ValueStr()
  4838. startDate := fsion.Get("startDate").ValueStr()
  4839. endDate := fsion.Get("endDate").ValueStr()
  4840. tx := restful.Engine.NewSession()
  4841. defer tx.Close()
  4842. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4843. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  4844. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4845. if err != nil {
  4846. logs.Error(err)
  4847. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4848. return
  4849. }
  4850. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  4851. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  4852. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4853. if err != nil {
  4854. logs.Error(err)
  4855. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4856. return
  4857. }
  4858. for _, feedp := range feedpList {
  4859. // LastftList, err := tx.SQL(` select tname ,id
  4860. // from feedtemplethistory where id = ?
  4861. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4862. // if err != nil {
  4863. // logs.Error(err)
  4864. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4865. // return
  4866. // }
  4867. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4868. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4869. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4870. if err != nil {
  4871. logs.Error(err)
  4872. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4873. return
  4874. }
  4875. var ftname interface{}
  4876. ftnamestatus := 0
  4877. ftname = feedp["ftname"]
  4878. var lastftid int64
  4879. if len(nextfeedpList) > 0 {
  4880. for _, ft := range nextfeedpList {
  4881. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4882. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4883. lastftid = ft["ftid"].(int64)
  4884. ftnamestatus = 1
  4885. break
  4886. }
  4887. }
  4888. }
  4889. for i, fpd := range fpdList {
  4890. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4891. fpd["weightstatus"] = 0
  4892. fpd["tratiostatus"] = 0
  4893. fpd["ftnamestatus"] = ftnamestatus
  4894. for k, fpd2 := range fpdList {
  4895. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4896. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4897. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4898. fpd["weightstatus"] = 1
  4899. }
  4900. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4901. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4902. fpd["tratiostatus"] = 1
  4903. }
  4904. break
  4905. }
  4906. }
  4907. fpd["barid"] = feedp["barid"]
  4908. fpd["barname"] = feedp["barname"]
  4909. fpd["ccount"] = feedp["ccount"]
  4910. fpd["ratio"] = feedp["ratio"]
  4911. fpd["ccountratio"] = feedp["ccountratio"]
  4912. fpd["ftid"] = feedp["ftid"]
  4913. fpd["ftname"] = ftname
  4914. fpd["ccountstatus"] = 0
  4915. fpd["ccountratiostatus"] = 0
  4916. fpd["ratiostatus"] = 0
  4917. fpd["ftnamestatus"] = 0
  4918. fpd["lastftid"] = lastftid
  4919. for _, next := range nextfeedpList {
  4920. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4921. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4922. fpd["ccountstatus"] = 1
  4923. }
  4924. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4925. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4926. fpd["ccountratiostatus"] = 1
  4927. }
  4928. if next["ratio"].(string) != fpd["ratio"].(string) {
  4929. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4930. fpd["ratiostatus"] = 1
  4931. }
  4932. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4933. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4934. // fpd["ftnamestatus"] = 1
  4935. // }
  4936. }
  4937. }
  4938. }
  4939. }
  4940. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4941. }
  4942. // func GetLpplandtl1History(c *gin.Context) {
  4943. // appG := app.Gin{C: c}
  4944. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4945. // fsion := gofasion.NewFasion(string(dataByte))
  4946. // // parammaps := fsion.Get("parammaps")
  4947. // barid := fsion.Get("barid").ValueStr()
  4948. // startDate := fsion.Get("startDate").ValueStr()
  4949. // endDate := fsion.Get("endDate").ValueStr()
  4950. // tx := restful.Engine.NewSession()
  4951. // defer tx.Close()
  4952. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4953. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4954. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4955. // // if err != nil {
  4956. // // logs.Error(err)
  4957. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4958. // // return
  4959. // // }
  4960. // // for _, feedp := range feedpList {
  4961. // // fmt.Println(feedp)
  4962. // // for i, fpd := range fpdList {
  4963. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4964. // // for k, fpd2 := range fpdList {
  4965. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4966. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4967. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4968. // // }
  4969. // // break
  4970. // // }
  4971. // // }
  4972. // // fpd["barid"] = feedp["barid"]
  4973. // // fpd["barname"] = feedp["barname"]
  4974. // // fpd["ccount"] = feedp["ccount"]
  4975. // // fpd["ratio"] = feedp["ratio"]
  4976. // // fpd["ccountratio"] = feedp["ccountratio"]
  4977. // // fpd["ftid"] = feedp["ftid"]
  4978. // // fpd["ftname"] = feedp["ftname"]
  4979. // // }
  4980. // // }
  4981. // // }
  4982. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4983. // }
  4984. func GetRemind(c *gin.Context) {
  4985. appG := app.Gin{C: c}
  4986. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4987. fsion := gofasion.NewFasion(string(dataByte))
  4988. parammaps := fsion.Get("parammaps")
  4989. pastureid := parammaps.Get("pastureid").ValueStr()
  4990. tx := restful.Engine.NewSession()
  4991. defer tx.Close()
  4992. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4993. if err != nil {
  4994. logs.Error(err)
  4995. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4996. return
  4997. }
  4998. // pastureid = "3"
  4999. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5000. if err != nil {
  5001. logs.Error(err)
  5002. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5003. return
  5004. }
  5005. defer resp.Body.Close()
  5006. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5007. buf.ReadFrom(resp.Body)
  5008. fmt.Println(string(buf.Bytes()))
  5009. respMap := make(map[string]interface{}, 0)
  5010. err = json.Unmarshal(buf.Bytes(), &respMap)
  5011. if err != nil {
  5012. logs.Error(err)
  5013. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5014. return
  5015. }
  5016. for _, data := range dataList {
  5017. r := make(map[string]interface{}, 0)
  5018. r["sys_name"] = ""
  5019. r["service_id"] = ""
  5020. r["pasture_id"] = ""
  5021. r["type_name"] = ""
  5022. r["remind_type_id"] = ""
  5023. r["remind_type"] = ""
  5024. r["push_date"] = ""
  5025. r["push_time"] = ""
  5026. r["interval_time"] = ""
  5027. r["push_limit"] = ""
  5028. r["template_id"] = ""
  5029. r["roles_id"] = ""
  5030. r["users_id"] = ""
  5031. r["date_type"] = ""
  5032. r["cycle_type"] = ""
  5033. data["data"] = r
  5034. for _, resp := range respMap["data"].([]interface{}) {
  5035. resp1 := resp.(map[string]interface{})
  5036. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5037. if resp1["push_time"] == nil {
  5038. resp1["push_time"] = ""
  5039. }
  5040. data["data"] = resp1
  5041. break
  5042. }
  5043. }
  5044. }
  5045. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5046. }
  5047. type NoticeMsgtype struct {
  5048. SysName string `json:"sys_name"`
  5049. PastureId int64 `json:"pasture_id"`
  5050. ServiceId int64 `json:"service_id"`
  5051. TypeName string `json:"type_name"`
  5052. RemindType int64 `json:"remind_type"`
  5053. PushDate int64 `json:"push_date"`
  5054. PushTime string `json:"push_time"`
  5055. IntervalTime int64 `json:"interval_time"`
  5056. PushLimit int64 `json:"push_limit"`
  5057. TemplateId string `json:"template_id"`
  5058. UsersId string `json:"users_id"`
  5059. DateType int64 `json:"date_type"`
  5060. CycleType int64 `json:"cycle_type"`
  5061. DelayTime int64 `json:"delay_time"`
  5062. Status int64 `json:"status"`
  5063. }
  5064. func UpdateRemind(c *gin.Context) {
  5065. appG := app.Gin{C: c}
  5066. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5067. parammaps := gofasion.NewFasion(string(dataByte))
  5068. // parammaps := fsion.Get("parammaps")
  5069. // user := parammaps.Get("user").ValueStr()
  5070. id := parammaps.Get("id").ValueInt64()
  5071. noticeMsgtype := new(NoticeMsgtype)
  5072. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5073. noticeMsgtype.ServiceId = id
  5074. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5075. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5076. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5077. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5078. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5079. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5080. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5081. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5082. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5083. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5084. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5085. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5086. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5087. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5088. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5089. //TODO
  5090. noticeMsgtype.SysName = "tmrWatch"
  5091. userList := parammaps.Get("user").Array()
  5092. var userstr []string
  5093. for _, user := range userList {
  5094. userstr = append(userstr, user.ValueStr())
  5095. }
  5096. tx := restful.Engine.NewSession()
  5097. defer tx.Close()
  5098. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5099. if err != nil {
  5100. logs.Error(err)
  5101. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5102. return
  5103. }
  5104. // var jsonStr = []byte(noticeMsgtype
  5105. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5106. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5107. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5108. req.Header.Set("Content-Type", "application/json")
  5109. client := &http.Client{}
  5110. resp, err := client.Do(req)
  5111. if err != nil {
  5112. logs.Error(err)
  5113. }
  5114. defer resp.Body.Close()
  5115. body, _ := ioutil.ReadAll(resp.Body)
  5116. fmt.Println("response Body:", string(body))
  5117. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5118. if err != nil {
  5119. logs.Error(err)
  5120. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5121. return
  5122. }
  5123. defer getresp.Body.Close()
  5124. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5125. buf.ReadFrom(getresp.Body)
  5126. // fmt.Println(string(buf.Bytes()))
  5127. respMap := make(map[string]interface{}, 0)
  5128. err = json.Unmarshal(buf.Bytes(), &respMap)
  5129. if err != nil {
  5130. logs.Error(err)
  5131. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5132. return
  5133. }
  5134. for _, resp := range respMap["data"].([]interface{}) {
  5135. resp1 := resp.(map[string]interface{})
  5136. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5137. if err != nil {
  5138. logs.Error(err)
  5139. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5140. return
  5141. }
  5142. }
  5143. appG.Response(http.StatusOK, e.SUCCESS, true)
  5144. }
  5145. func GetSpillageallHistory(c *gin.Context) {
  5146. appG := app.Gin{C: c}
  5147. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5148. parammaps := gofasion.NewFasion(string(dataByte))
  5149. barname := parammaps.Get("barname").ValueStr()
  5150. pastureid := parammaps.Get("pastureid").ValueStr()
  5151. startdate := parammaps.Get("startDate").ValueStr()
  5152. enddate := parammaps.Get("endDate").ValueStr()
  5153. tx := restful.Engine.NewSession()
  5154. defer tx.Close()
  5155. 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
  5156. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5157. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5158. if err != nil {
  5159. logs.Error(err)
  5160. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5161. return
  5162. }
  5163. respMap := make([]map[string]interface{}, 0)
  5164. data := make(map[interface{}]interface{})
  5165. for _, history := range historyList {
  5166. data[history["createdate"]] = history["createdate"]
  5167. }
  5168. createList := []string{}
  5169. for _, v := range data {
  5170. createList = append(createList, v.(string))
  5171. }
  5172. // sort.Sort()
  5173. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5174. sort.Slice(createList, func(i, j int) bool {
  5175. return createList[i] > createList[j]
  5176. })
  5177. for _, v := range createList {
  5178. a := make(map[string]interface{})
  5179. a["createdate"] = data[v]
  5180. // createList = append(createList, v.(string))
  5181. respMap = append(respMap, a)
  5182. }
  5183. number := 0
  5184. dataMap := make([]interface{}, 0)
  5185. for k, resp := range respMap {
  5186. createdate := resp["createdate"].(string)
  5187. var nextcreatedate string
  5188. if len(respMap) > k+1 {
  5189. nextcreatedate = respMap[k+1]["createdate"].(string)
  5190. }
  5191. // dataList := make(map[string][]interface{})
  5192. // list := make(map[string]interface{})
  5193. times := make(map[interface{}]int)
  5194. for _, history := range historyList {
  5195. // List := make(map[interface{}][]interface{})
  5196. i := 0
  5197. if history["createdate"].(string) == createdate {
  5198. times[history["times"]]++
  5199. data := make(map[string]interface{})
  5200. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5201. // exist := false
  5202. if nextcreatedate != "" {
  5203. for _, history1 := range historyList {
  5204. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5205. history1["times"].(int64) == history["times"].(int64) {
  5206. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  5207. break
  5208. // exist = true
  5209. }
  5210. }
  5211. }
  5212. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5213. i++
  5214. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5215. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5216. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5217. // resp["times"] = history["times"]
  5218. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5219. data1 := make(map[string]interface{})
  5220. data1["times"] = history["times"]
  5221. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5222. data1["createdate"] = resp["createdate"]
  5223. // fmt.Println(dataList)
  5224. dataMap = append(dataMap, data1)
  5225. }
  5226. if i > number {
  5227. number = i
  5228. }
  5229. // respMap = append(respMap, dataList)
  5230. }
  5231. // for k, data := range dataList {
  5232. // resp[k] = data
  5233. // }
  5234. // resp["data"] = dataList
  5235. }
  5236. // resp := make(map[string]interface{})
  5237. // sort.Strings(createList)
  5238. //
  5239. // for _, create := range createList {
  5240. // for _, r := range respMap {
  5241. // if create == r["createdate"].(string) {
  5242. // resp[create] = r
  5243. // break
  5244. // }
  5245. // }
  5246. // }
  5247. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5248. var trainsList []interface{}
  5249. for i := 0; i < number; i++ {
  5250. trains := make(map[string]interface{})
  5251. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5252. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5253. trainsList = append(trainsList, trains)
  5254. }
  5255. respdata := make(map[string]interface{})
  5256. respdata["data"] = dataMap
  5257. respdata["trains"] = trainsList
  5258. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5259. }
  5260. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5261. appG := app.Gin{C: c}
  5262. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5263. parammaps := gofasion.NewFasion(string(dataByte))
  5264. ftid := parammaps.Get("ftid").ValueInt64()
  5265. lastftid := parammaps.Get("lastftid").ValueInt64()
  5266. pastureid := parammaps.Get("pastureid").ValueInt64()
  5267. // createdate := parammaps.Get("createdate").ValueStr()
  5268. tx := restful.Engine.NewSession()
  5269. defer tx.Close()
  5270. data := make(map[string]interface{})
  5271. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5272. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5273. if err != nil {
  5274. logs.Error(err)
  5275. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5276. return
  5277. }
  5278. feedtemplet := make(map[string]interface{})
  5279. for _, f := range feedtempletList {
  5280. feedtemplet = f
  5281. }
  5282. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5283. if err != nil {
  5284. logs.Error(err)
  5285. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5286. return
  5287. }
  5288. feedtemplet["fit"] = fitList
  5289. data["current"] = feedtemplet
  5290. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5291. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5292. if err != nil {
  5293. logs.Error(err)
  5294. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5295. return
  5296. }
  5297. lastfeedtemplet := make(map[string]interface{})
  5298. for _, f := range lastfeedtempletList {
  5299. lastfeedtemplet = f
  5300. }
  5301. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5302. if err != nil {
  5303. logs.Error(err)
  5304. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5305. return
  5306. }
  5307. lastfeedtemplet["fit"] = lastfitList
  5308. data["last"] = lastfeedtemplet
  5309. appG.Response(http.StatusOK, e.SUCCESS, data)
  5310. }
  5311. func GetFeedtempletHistory(c *gin.Context) {
  5312. appG := app.Gin{C: c}
  5313. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5314. parammaps := gofasion.NewFasion(string(dataByte))
  5315. ftid := parammaps.Get("ftid").ValueStr()
  5316. pastureid := parammaps.Get("pastureid").ValueInt64()
  5317. start := parammaps.Get("startdate").ValueStr()
  5318. end := parammaps.Get("enddate").ValueStr()
  5319. tx := restful.Engine.NewSession()
  5320. defer tx.Close()
  5321. 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 ?
  5322. and id = ? and pastureid = ? order by createdate desc `,
  5323. start, end, ftid, pastureid).Query().List()
  5324. if err != nil {
  5325. logs.Error(err)
  5326. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5327. return
  5328. }
  5329. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5330. ftid, pastureid).Query().List()
  5331. if err != nil {
  5332. logs.Error(err)
  5333. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5334. return
  5335. }
  5336. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5337. for i, ft := range ftList {
  5338. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5339. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5340. (select empname from user where id = fit.userId) empname,
  5341. 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
  5342. where fit.fitid = ?
  5343. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5344. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5345. if err != nil {
  5346. logs.Error(err)
  5347. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5348. return
  5349. }
  5350. ft["createdate"] = ft["createdate1"]
  5351. // data["tname"] = ft["tname"]
  5352. // data["tcode"] = ft["tcode"]
  5353. // data["tcolor"] = ft["tcolor"]
  5354. // data["fttype"] = ft["fttype"]
  5355. // data["ccname"] = ft["ccname"]
  5356. // data["source"] = ft["source"]
  5357. // data["version"] = ft["version"]
  5358. // data["remark"] = ft["remark"]
  5359. for n, ft2 := range ftList {
  5360. if i < n {
  5361. if ft["tname"].(string) != ft2["tname"].(string) {
  5362. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5363. }
  5364. if _, ok := ft["tcode"]; ok {
  5365. if _, ok := ft2["tcode"]; ok {
  5366. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5367. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5368. }
  5369. }
  5370. }
  5371. if _, ok := ft["tcolor"]; ok {
  5372. if _, ok := ft2["tcolor"]; ok {
  5373. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5374. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5375. }
  5376. }
  5377. }
  5378. if _, ok := ft["fttype"]; ok {
  5379. if _, ok := ft2["fttype"]; ok {
  5380. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5381. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5382. }
  5383. }
  5384. }
  5385. if _, ok := ft["ccname"]; ok {
  5386. if _, ok := ft2["ccname"]; ok {
  5387. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5388. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5389. }
  5390. }
  5391. }
  5392. if _, ok := ft["source"]; ok {
  5393. if _, ok := ft2["source"]; ok {
  5394. if ft["source"].(string) != ft2["source"].(string) {
  5395. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5396. }
  5397. }
  5398. }
  5399. if _, ok := ft["version"]; ok {
  5400. if _, ok := ft2["version"]; ok {
  5401. if ft["version"].(int64) != ft2["version"].(int64) {
  5402. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5403. }
  5404. }
  5405. }
  5406. if _, ok := ft["remark"]; ok {
  5407. if _, ok := ft2["remark"]; ok {
  5408. if ft["remark"].(string) != ft2["remark"].(string) {
  5409. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5410. }
  5411. }
  5412. }
  5413. break
  5414. }
  5415. }
  5416. dataList := make([]map[string]interface{}, 0)
  5417. if len(fithisList) > 0 {
  5418. for _, fit := range fithisList {
  5419. data := make(map[string]interface{})
  5420. data["feedgroup"] = fit["feedgroup"]
  5421. data["fname"] = fit["fname"]
  5422. data["empname"] = fit["empname"]
  5423. if fit["Eweight"] != nil {
  5424. if fit["Eweight"].(string) != fit["weight"].(string) {
  5425. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5426. } else {
  5427. data["fweight"] = fit["Eweight"]
  5428. }
  5429. data["fweightstatus"] = 1
  5430. } else {
  5431. data["fweight"] = fit["weight"]
  5432. data["fweightstatus"] = 0
  5433. }
  5434. data["autosecond"] = fit["autosecond"]
  5435. // data["tname"] = ft["tname"]
  5436. // data["tcode"] = ft["tcode"]
  5437. // data["tcolor"] = ft["tcolor"]
  5438. // data["fttype"] = ft["fttype"]
  5439. // data["ccname"] = ft["ccname"]
  5440. // data["source"] = ft["source"]
  5441. // data["version"] = ft["version"]
  5442. // data["remark"] = ft["remark"]
  5443. // data["createdate"] = ft["createdate1"]
  5444. // ft["fit"] = data
  5445. dataList = append(dataList, data)
  5446. }
  5447. } else {
  5448. for _, fit := range ftdetailList {
  5449. data := make(map[string]interface{})
  5450. data["feedgroup"] = fit["feedgroup"]
  5451. data["fname"] = fit["fname"]
  5452. // if fit["Eweight"] != nil {
  5453. // data["weight"] = fit["Eweight"]
  5454. // } else {
  5455. data["fweight"] = fit["fweight"]
  5456. // }
  5457. data["autosecond"] = fit["autosecond"]
  5458. // ft["fit"] = data
  5459. dataList = append(dataList, data)
  5460. }
  5461. }
  5462. ft["fit"] = dataList
  5463. }
  5464. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5465. }
  5466. func UpdateMaterialTMR(c *gin.Context) {
  5467. appG := app.Gin{C: c}
  5468. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5469. parammaps := gofasion.NewFasion(string(dataByte))
  5470. tmrid := parammaps.Get("tmrid").ValueStr()
  5471. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5472. lppid := parammaps.Get("lppid").ValueStr()
  5473. times := parammaps.Get("times").ValueStr()
  5474. pastureid := parammaps.Get("pastureid").ValueStr()
  5475. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5476. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5477. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5478. tx := restful.Engine.NewSession()
  5479. defer tx.Close()
  5480. tx.Begin()
  5481. if tmrid != "1000" {
  5482. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5483. if err != nil {
  5484. logs.Error(err)
  5485. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5486. return
  5487. }
  5488. var maxstirfeed float64
  5489. for _, tmr := range tmrList {
  5490. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5491. }
  5492. if status == 0 {
  5493. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5494. if err != nil {
  5495. tx.Rollback()
  5496. logs.Error(err)
  5497. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5498. return
  5499. }
  5500. var lweight float64
  5501. for _, item := range lpplandtl1List {
  5502. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5503. lweight += fl
  5504. }
  5505. if lweight > maxstirfeed {
  5506. lweight = lweight - maxstirfeed
  5507. } else {
  5508. lweight = 0
  5509. }
  5510. if lweight > 0 {
  5511. lweight1 := lweight / float64(len(lpplandtl1List))
  5512. number := 0
  5513. for _, item := range lpplandtl1List {
  5514. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5515. if lweight1 >= fl {
  5516. number++
  5517. }
  5518. }
  5519. lweight := lweight / float64((len(lpplandtl1List) - number))
  5520. for _, item := range lpplandtl1List {
  5521. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5522. if lweight1 >= fl {
  5523. continue
  5524. }
  5525. if tmrtype == "1" {
  5526. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5527. if err != nil {
  5528. tx.Rollback()
  5529. logs.Error(err)
  5530. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5531. return
  5532. }
  5533. } else if tmrtype == "2" {
  5534. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5535. if err != nil {
  5536. tx.Rollback()
  5537. logs.Error(err)
  5538. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5539. return
  5540. }
  5541. }
  5542. if item["fttype"].(int64) == 0 {
  5543. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5544. if err != nil {
  5545. tx.Rollback()
  5546. logs.Error(err)
  5547. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5548. return
  5549. }
  5550. } else {
  5551. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5552. if err != nil {
  5553. tx.Rollback()
  5554. logs.Error(err)
  5555. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5556. return
  5557. }
  5558. }
  5559. }
  5560. } else {
  5561. for _, item := range lpplandtl1List {
  5562. // 自走式
  5563. if tmrtype == "1" {
  5564. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5565. if err != nil {
  5566. logs.Error(err)
  5567. tx.Rollback()
  5568. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5569. return
  5570. }
  5571. } else if tmrtype == "2" {
  5572. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5573. if err != nil {
  5574. logs.Error(err)
  5575. tx.Rollback()
  5576. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5577. return
  5578. }
  5579. }
  5580. }
  5581. }
  5582. } else if status == 1 {
  5583. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5584. if err != nil {
  5585. logs.Error(err)
  5586. tx.Rollback()
  5587. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5588. return
  5589. }
  5590. var lweight float64
  5591. for _, item := range lpplandtl1List {
  5592. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5593. lweight += fl
  5594. }
  5595. if lweight > maxstirfeed {
  5596. lweight = lweight - maxstirfeed
  5597. } else {
  5598. lweight = 0
  5599. }
  5600. for _, item := range lpplandtl1List {
  5601. if lweight > 0 {
  5602. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5603. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5604. if fl >= lweight {
  5605. item["lweight"] = fl - lweight
  5606. lweight = 0
  5607. if tmrtype == "1" {
  5608. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5609. if err != nil {
  5610. logs.Error(err)
  5611. tx.Rollback()
  5612. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5613. return
  5614. }
  5615. } else if tmrtype == "2" {
  5616. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5617. if err != nil {
  5618. logs.Error(err)
  5619. tx.Rollback()
  5620. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5621. return
  5622. }
  5623. }
  5624. if item["fttype"].(int64) == 0 {
  5625. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5626. if err != nil {
  5627. logs.Error(err)
  5628. tx.Rollback()
  5629. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5630. return
  5631. }
  5632. } else {
  5633. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5634. if err != nil {
  5635. logs.Error(err)
  5636. tx.Rollback()
  5637. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5638. return
  5639. }
  5640. }
  5641. } else {
  5642. lweight = lweight - fl
  5643. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5644. if err != nil {
  5645. logs.Error(err)
  5646. tx.Rollback()
  5647. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5648. return
  5649. }
  5650. if item["fttype"].(int64) == 0 {
  5651. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5652. if err != nil {
  5653. logs.Error(err)
  5654. tx.Rollback()
  5655. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5656. return
  5657. }
  5658. } else {
  5659. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5660. if err != nil {
  5661. logs.Error(err)
  5662. tx.Rollback()
  5663. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5664. return
  5665. }
  5666. }
  5667. }
  5668. } else {
  5669. // 自走式
  5670. if tmrtype == "1" {
  5671. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5672. if err != nil {
  5673. logs.Error(err)
  5674. tx.Rollback()
  5675. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5676. return
  5677. }
  5678. } else if tmrtype == "2" {
  5679. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5680. if err != nil {
  5681. logs.Error(err)
  5682. tx.Rollback()
  5683. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5684. return
  5685. }
  5686. }
  5687. }
  5688. }
  5689. } else {
  5690. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5691. if err != nil {
  5692. logs.Error(err)
  5693. tx.Rollback()
  5694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5695. return
  5696. }
  5697. for _, item := range lpplandtl1List {
  5698. if item["fttype"].(int64) == 0 {
  5699. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5700. if err != nil {
  5701. logs.Error(err)
  5702. tx.Rollback()
  5703. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5704. return
  5705. }
  5706. } else {
  5707. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5708. if err != nil {
  5709. logs.Error(err)
  5710. tx.Rollback()
  5711. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5712. return
  5713. }
  5714. }
  5715. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5716. if err != nil {
  5717. logs.Error(err)
  5718. tx.Rollback()
  5719. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5720. return
  5721. }
  5722. }
  5723. }
  5724. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5725. if err != nil {
  5726. logs.Error(err)
  5727. tx.Rollback()
  5728. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5729. return
  5730. }
  5731. } else {
  5732. if status == 2 {
  5733. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5734. if err != nil {
  5735. logs.Error(err)
  5736. tx.Rollback()
  5737. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5738. return
  5739. }
  5740. for _, item := range lpplandtl1List {
  5741. if item["fttype"].(int64) == 0 {
  5742. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5743. if err != nil {
  5744. logs.Error(err)
  5745. tx.Rollback()
  5746. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5747. return
  5748. }
  5749. } else {
  5750. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5751. if err != nil {
  5752. logs.Error(err)
  5753. tx.Rollback()
  5754. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5755. return
  5756. }
  5757. }
  5758. }
  5759. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  5760. if err != nil {
  5761. logs.Error(err)
  5762. tx.Rollback()
  5763. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5764. return
  5765. }
  5766. } else {
  5767. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  5768. if err != nil {
  5769. logs.Error(err)
  5770. tx.Rollback()
  5771. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5772. return
  5773. }
  5774. }
  5775. }
  5776. err := tx.Commit()
  5777. if err != nil {
  5778. logs.Error(err)
  5779. tx.Rollback()
  5780. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5781. return
  5782. }
  5783. appG.Response(http.StatusOK, e.SUCCESS, true)
  5784. }
  5785. func UpdateMaterialTMRDate(c *gin.Context) {
  5786. appG := app.Gin{C: c}
  5787. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5788. parammaps := gofasion.NewFasion(string(dataByte))
  5789. tmrid := parammaps.Get("tmrid").ValueStr()
  5790. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5791. lppid := parammaps.Get("lppid").ValueStr()
  5792. times := parammaps.Get("times").ValueStr()
  5793. pastureid := parammaps.Get("pastureid").ValueStr()
  5794. date := parammaps.Get("date").ValueStr()
  5795. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5796. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5797. tx := restful.Engine.NewSession()
  5798. defer tx.Close()
  5799. tx.Begin()
  5800. if tmrid != "1000" {
  5801. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5802. if err != nil {
  5803. logs.Error(err)
  5804. tx.Rollback()
  5805. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5806. return
  5807. }
  5808. var maxstirfeed float64
  5809. for _, tmr := range tmrList {
  5810. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5811. }
  5812. if status == 0 {
  5813. 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()
  5814. if err != nil {
  5815. logs.Error(err)
  5816. tx.Rollback()
  5817. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5818. return
  5819. }
  5820. var lweight float64
  5821. for _, item := range lpplandtl1List {
  5822. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5823. lweight += fl
  5824. }
  5825. if lweight > maxstirfeed {
  5826. lweight = lweight - maxstirfeed
  5827. } else {
  5828. lweight = 0
  5829. }
  5830. if lweight > 0 {
  5831. lweight1 := lweight / float64(len(lpplandtl1List))
  5832. number := 0
  5833. for _, item := range lpplandtl1List {
  5834. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5835. if lweight1 >= fl {
  5836. number++
  5837. }
  5838. }
  5839. lweight := lweight / float64((len(lpplandtl1List) - number))
  5840. for _, item := range lpplandtl1List {
  5841. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5842. if lweight1 >= fl {
  5843. continue
  5844. }
  5845. if tmrtype == "1" {
  5846. _, 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()
  5847. if err != nil {
  5848. logs.Error(err)
  5849. tx.Rollback()
  5850. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5851. return
  5852. }
  5853. } else if tmrtype == "2" {
  5854. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5855. if err != nil {
  5856. logs.Error(err)
  5857. tx.Rollback()
  5858. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5859. return
  5860. }
  5861. }
  5862. if item["fttype"].(int64) == 0 {
  5863. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5864. if err != nil {
  5865. logs.Error(err)
  5866. tx.Rollback()
  5867. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5868. return
  5869. }
  5870. } else {
  5871. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5872. if err != nil {
  5873. logs.Error(err)
  5874. tx.Rollback()
  5875. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5876. return
  5877. }
  5878. }
  5879. }
  5880. } else {
  5881. for _, item := range lpplandtl1List {
  5882. // 自走式
  5883. if tmrtype == "1" {
  5884. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5885. if err != nil {
  5886. logs.Error(err)
  5887. tx.Rollback()
  5888. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5889. return
  5890. }
  5891. } else if tmrtype == "2" {
  5892. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5893. if err != nil {
  5894. logs.Error(err)
  5895. tx.Rollback()
  5896. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5897. return
  5898. }
  5899. }
  5900. }
  5901. }
  5902. } else if status == 1 {
  5903. 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()
  5904. if err != nil {
  5905. logs.Error(err)
  5906. tx.Rollback()
  5907. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5908. return
  5909. }
  5910. var lweight float64
  5911. for _, item := range lpplandtl1List {
  5912. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5913. lweight += fl
  5914. }
  5915. if lweight > maxstirfeed {
  5916. lweight = lweight - maxstirfeed
  5917. } else {
  5918. lweight = 0
  5919. }
  5920. for _, item := range lpplandtl1List {
  5921. if lweight > 0 {
  5922. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5923. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5924. if fl >= lweight {
  5925. item["lweight"] = fl - lweight
  5926. lweight = 0
  5927. if tmrtype == "1" {
  5928. _, 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()
  5929. if err != nil {
  5930. logs.Error(err)
  5931. tx.Rollback()
  5932. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5933. return
  5934. }
  5935. } else if tmrtype == "2" {
  5936. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5937. if err != nil {
  5938. logs.Error(err)
  5939. tx.Rollback()
  5940. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5941. return
  5942. }
  5943. }
  5944. if item["fttype"].(int64) == 0 {
  5945. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5946. if err != nil {
  5947. logs.Error(err)
  5948. tx.Rollback()
  5949. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5950. return
  5951. }
  5952. } else {
  5953. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5954. if err != nil {
  5955. logs.Error(err)
  5956. tx.Rollback()
  5957. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5958. return
  5959. }
  5960. }
  5961. } else {
  5962. lweight = lweight - fl
  5963. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5964. if err != nil {
  5965. logs.Error(err)
  5966. tx.Rollback()
  5967. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5968. return
  5969. }
  5970. if item["fttype"].(int64) == 0 {
  5971. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5972. if err != nil {
  5973. logs.Error(err)
  5974. tx.Rollback()
  5975. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5976. return
  5977. }
  5978. } else {
  5979. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5980. if err != nil {
  5981. logs.Error(err)
  5982. tx.Rollback()
  5983. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5984. return
  5985. }
  5986. }
  5987. }
  5988. } else {
  5989. // 自走式
  5990. if tmrtype == "1" {
  5991. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5992. if err != nil {
  5993. logs.Error(err)
  5994. tx.Rollback()
  5995. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5996. return
  5997. }
  5998. } else if tmrtype == "2" {
  5999. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6000. if err != nil {
  6001. logs.Error(err)
  6002. tx.Rollback()
  6003. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6004. return
  6005. }
  6006. }
  6007. }
  6008. }
  6009. } else {
  6010. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6011. if err != nil {
  6012. logs.Error(err)
  6013. tx.Rollback()
  6014. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6015. return
  6016. }
  6017. for _, item := range lpplandtl1List {
  6018. if item["fttype"].(int64) == 0 {
  6019. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6020. if err != nil {
  6021. logs.Error(err)
  6022. tx.Rollback()
  6023. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6024. return
  6025. }
  6026. } else {
  6027. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6028. if err != nil {
  6029. logs.Error(err)
  6030. tx.Rollback()
  6031. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6032. return
  6033. }
  6034. }
  6035. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6036. if err != nil {
  6037. logs.Error(err)
  6038. tx.Rollback()
  6039. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6040. return
  6041. }
  6042. }
  6043. }
  6044. _, 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()
  6045. if err != nil {
  6046. logs.Error(err)
  6047. tx.Rollback()
  6048. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6049. return
  6050. }
  6051. } else {
  6052. if status == 2 {
  6053. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6054. if err != nil {
  6055. logs.Error(err)
  6056. tx.Rollback()
  6057. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6058. return
  6059. }
  6060. for _, item := range lpplandtl1List {
  6061. if item["fttype"].(int64) == 0 {
  6062. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6063. if err != nil {
  6064. logs.Error(err)
  6065. tx.Rollback()
  6066. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6067. return
  6068. }
  6069. } else {
  6070. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6071. if err != nil {
  6072. logs.Error(err)
  6073. tx.Rollback()
  6074. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6075. return
  6076. }
  6077. }
  6078. }
  6079. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6080. if err != nil {
  6081. logs.Error(err)
  6082. tx.Rollback()
  6083. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6084. return
  6085. }
  6086. } else {
  6087. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6088. if err != nil {
  6089. logs.Error(err)
  6090. tx.Rollback()
  6091. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6092. return
  6093. }
  6094. }
  6095. }
  6096. err := tx.Commit()
  6097. if err != nil {
  6098. logs.Error(err)
  6099. tx.Rollback()
  6100. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6101. return
  6102. }
  6103. appG.Response(http.StatusOK, e.SUCCESS, true)
  6104. }
  6105. func Decimal(value float64) float64 {
  6106. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6107. return value
  6108. }
  6109. func UpdateDailyData(c *gin.Context) {
  6110. appG := app.Gin{C: c}
  6111. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6112. parammaps := gofasion.NewFasion(string(dataByte))
  6113. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6114. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6115. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6116. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6117. date := parammaps.Get("date").ValueStr()
  6118. tx := restful.Engine.NewSession()
  6119. defer tx.Close()
  6120. tx.Begin()
  6121. if location == 0 {
  6122. fid := parammaps.Get("fid").ValueStr()
  6123. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6124. if err != nil {
  6125. logs.Error("UpdateDailyData-error-1:", err)
  6126. tx.Rollback()
  6127. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6128. return
  6129. }
  6130. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6131. if err != nil {
  6132. logs.Error("UpdateDailyData-error-1:", err)
  6133. tx.Rollback()
  6134. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6135. return
  6136. }
  6137. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6138. if err != nil {
  6139. fmt.Println("Error:", err)
  6140. return
  6141. }
  6142. actualWeight := weight - num
  6143. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6144. if err != nil {
  6145. logs.Error("UpdateDailyData-error-2:", err)
  6146. tx.Rollback()
  6147. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6148. return
  6149. }
  6150. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6151. if err != nil {
  6152. logs.Error("UpdateDailyData-error-3:", err)
  6153. tx.Rollback()
  6154. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6155. return
  6156. }
  6157. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6158. if err != nil {
  6159. logs.Error("UpdateDailyData-error-4:", err)
  6160. tx.Rollback()
  6161. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6162. return
  6163. }
  6164. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6165. if err != nil {
  6166. logs.Error("UpdateDailyData-error-5:", err)
  6167. tx.Rollback()
  6168. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6169. return
  6170. }
  6171. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6172. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6173. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6174. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6175. if err != nil {
  6176. fmt.Println("Error:", err)
  6177. return
  6178. }
  6179. // actual := actualWeight / float64(len(downloadedplanList))
  6180. for _, item := range downloadedplanList {
  6181. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6182. if err != nil {
  6183. fmt.Println("Error:", err)
  6184. return
  6185. }
  6186. actual := itemLweight / lweight * actualWeight
  6187. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6188. if err != nil {
  6189. logs.Error("UpdateDailyData-error-6:", err)
  6190. tx.Rollback()
  6191. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6192. return
  6193. }
  6194. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6195. if err != nil {
  6196. logs.Error("UpdateDailyData-error-7:", err)
  6197. tx.Rollback()
  6198. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6199. return
  6200. }
  6201. _, 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()
  6202. if err != nil {
  6203. logs.Error("UpdateDailyData-error-8:", err)
  6204. tx.Rollback()
  6205. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6206. return
  6207. }
  6208. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6209. if err != nil {
  6210. logs.Error("UpdateDailyData-error-9:", err)
  6211. tx.Rollback()
  6212. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6213. return
  6214. }
  6215. }
  6216. } else {
  6217. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6218. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6219. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6220. // if err != nil {
  6221. // fmt.Println("Error:", err)
  6222. // return
  6223. // }
  6224. for _, item := range downloadedplanList {
  6225. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6226. if err != nil {
  6227. logs.Error("UpdateDailyData-error-6:", err)
  6228. tx.Rollback()
  6229. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6230. return
  6231. }
  6232. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6233. item["lweight"], actualWeight, item["id"]).Execute()
  6234. if err != nil {
  6235. logs.Error("UpdateDailyData-error-7:", err)
  6236. tx.Rollback()
  6237. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6238. return
  6239. }
  6240. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6241. where pid = ?`, item["id"]).Execute()
  6242. if err != nil {
  6243. logs.Error("UpdateDailyData-error-8:", err)
  6244. tx.Rollback()
  6245. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6246. return
  6247. }
  6248. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6249. if err != nil {
  6250. logs.Error("UpdateDailyData-error-9:", err)
  6251. tx.Rollback()
  6252. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6253. return
  6254. }
  6255. }
  6256. }
  6257. } else {
  6258. fbarid := parammaps.Get("fbarid").ValueStr()
  6259. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6260. if err != nil {
  6261. logs.Error("UpdateDailyData-error-10:", err)
  6262. tx.Rollback()
  6263. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6264. return
  6265. }
  6266. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6267. if err != nil {
  6268. logs.Error("UpdateDailyData-error-1:", err)
  6269. tx.Rollback()
  6270. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6271. return
  6272. }
  6273. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6274. if err != nil {
  6275. fmt.Println("Error:", err)
  6276. return
  6277. }
  6278. actualWeight := weight - num
  6279. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6280. if err != nil {
  6281. logs.Error("UpdateDailyData-error-11:", err)
  6282. tx.Rollback()
  6283. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6284. return
  6285. }
  6286. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6287. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6288. if err != nil {
  6289. logs.Error("UpdateDailyData-error-12:", err)
  6290. tx.Rollback()
  6291. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6292. return
  6293. }
  6294. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6295. where pid = ? `, pid).Execute()
  6296. if err != nil {
  6297. logs.Error("UpdateDailyData-error-13:", err)
  6298. tx.Rollback()
  6299. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6300. return
  6301. }
  6302. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6303. if err != nil {
  6304. logs.Error("UpdateDailyData-error-14:", err)
  6305. tx.Rollback()
  6306. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6307. return
  6308. }
  6309. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6310. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6311. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6312. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6313. if err != nil {
  6314. fmt.Println("Error:", err)
  6315. return
  6316. }
  6317. for _, item := range downloadedplanList {
  6318. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6319. if err != nil {
  6320. fmt.Println("Error:", err)
  6321. return
  6322. }
  6323. actual := itemLweight / lweight * actualWeight
  6324. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6325. if err != nil {
  6326. logs.Error("UpdateDailyData-error-6:", err)
  6327. tx.Rollback()
  6328. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6329. return
  6330. }
  6331. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6332. if err != nil {
  6333. logs.Error("UpdateDailyData-error-7:", err)
  6334. tx.Rollback()
  6335. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6336. return
  6337. }
  6338. _, 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()
  6339. if err != nil {
  6340. logs.Error("UpdateDailyData-error-8:", err)
  6341. tx.Rollback()
  6342. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6343. return
  6344. }
  6345. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6346. if err != nil {
  6347. logs.Error("UpdateDailyData-error-9:", err)
  6348. tx.Rollback()
  6349. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6350. return
  6351. }
  6352. }
  6353. } else {
  6354. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6355. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6356. for _, item := range downloadedplanList {
  6357. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6358. // if err != nil {
  6359. // fmt.Println("Error:", err)
  6360. // return
  6361. // }
  6362. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6363. if err != nil {
  6364. logs.Error("UpdateDailyData-error-6:", err)
  6365. tx.Rollback()
  6366. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6367. return
  6368. }
  6369. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6370. item["lweight"], actualWeight, item["id"]).Execute()
  6371. if err != nil {
  6372. logs.Error("UpdateDailyData-error-7:", err)
  6373. tx.Rollback()
  6374. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6375. return
  6376. }
  6377. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6378. where pid = ?`, item["id"]).Execute()
  6379. if err != nil {
  6380. logs.Error("UpdateDailyData-error-8:", err)
  6381. tx.Rollback()
  6382. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6383. return
  6384. }
  6385. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6386. if err != nil {
  6387. logs.Error("UpdateDailyData-error-9:", err)
  6388. tx.Rollback()
  6389. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6390. return
  6391. }
  6392. }
  6393. }
  6394. }
  6395. err := tx.Commit()
  6396. if err != nil {
  6397. logs.Error("UpdateDailyData-error-20:", err)
  6398. tx.Rollback()
  6399. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6400. return
  6401. }
  6402. appG.Response(http.StatusOK, e.SUCCESS, true)
  6403. }
  6404. func GetFormulaStatistics(c *gin.Context) {
  6405. appG := app.Gin{C: c}
  6406. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6407. parammaps := gofasion.NewFasion(string(dataByte))
  6408. startTime := parammaps.Get("startTime").ValueStr()
  6409. endTime := parammaps.Get("endTime").ValueStr()
  6410. pastureId := parammaps.Get("pastureId").ValueStr()
  6411. tx := restful.Engine.NewSession()
  6412. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6413. if err != nil {
  6414. logs.Error("GetFormulaStatistics-error-1:", err)
  6415. tx.Rollback()
  6416. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6417. return
  6418. }
  6419. var feedtemplet, dateList []string
  6420. for _, f := range feedtempletList {
  6421. feedtemplet = append(feedtemplet, f["tname"].(string))
  6422. }
  6423. layout := "2006-01-02"
  6424. // s := "2023-05-01"
  6425. // e := "2023-05-23"
  6426. start, err := time.Parse(layout, startTime)
  6427. if err != nil {
  6428. fmt.Println(err)
  6429. return
  6430. }
  6431. end, err := time.Parse(layout, endTime)
  6432. if err != nil {
  6433. fmt.Println(err)
  6434. return
  6435. }
  6436. end = end.AddDate(0, 0, 1)
  6437. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6438. dateList = append(dateList, d.Format("2006-01-02"))
  6439. }
  6440. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6441. 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= ?
  6442. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6443. if err != nil {
  6444. logs.Error("GetFormulaStatistics-error-2:", err)
  6445. tx.Rollback()
  6446. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6447. return
  6448. }
  6449. var data2 [][]interface{}
  6450. for _, f := range feedtemplet {
  6451. var data1 []interface{}
  6452. for _, date := range dateList {
  6453. exist := false
  6454. for _, item := range downloadedplanList {
  6455. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6456. data1 = append(data1, item["total"])
  6457. exist = true
  6458. break
  6459. }
  6460. }
  6461. if !exist {
  6462. data1 = append(data1, 0)
  6463. }
  6464. }
  6465. data2 = append(data2, data1)
  6466. }
  6467. //前端让加的
  6468. feedtemplet = append(feedtemplet, "")
  6469. {
  6470. var data1 []interface{}
  6471. for _, f := range dateList {
  6472. // f = f + "\n"
  6473. fmt.Println(f)
  6474. data1 = append(data1, 0)
  6475. }
  6476. data2 = append(data2, data1)
  6477. }
  6478. resp := make(map[string]interface{}, 0)
  6479. resp["xdata"] = dateList
  6480. resp["data1"] = feedtemplet
  6481. resp["data2"] = data2
  6482. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6483. }
  6484. func GetPlanData(c *gin.Context) {
  6485. appG := app.Gin{C: c}
  6486. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6487. fsion := gofasion.NewFasion(string(dataByte))
  6488. sqlnamestr := fsion.Get("name").ValueStr()
  6489. sqlnamestr1 := fsion.Get("name1").ValueStr()
  6490. offset := fsion.Get("offset").ValueDefaultInt(0)
  6491. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  6492. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6493. month := fsion.Get("month").ValueDefaultStr("map")
  6494. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  6495. tx := restful.Engine.NewSession()
  6496. err := tx.Begin()
  6497. defer func() {
  6498. switch {
  6499. case err != nil:
  6500. if tx != nil {
  6501. tx.Rollback()
  6502. }
  6503. default:
  6504. if tx != nil {
  6505. err = tx.Commit()
  6506. }
  6507. }
  6508. if tx != nil {
  6509. tx.Close()
  6510. }
  6511. }()
  6512. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6513. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  6514. if sql != "" {
  6515. s_params := make([]interface{}, 0)
  6516. if fsion.HasKey("parammaps") {
  6517. parammaps := fsion.Get("parammaps")
  6518. paramslist := strings.Split(p, ",")
  6519. if len(paramslist) > 0 && p != "" {
  6520. for _, value := range paramslist {
  6521. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6522. if tempv, exists := c.Get("jwt_username"); exists {
  6523. s_params = append(s_params, tempv.(string))
  6524. } else {
  6525. s_params = append(s_params, "")
  6526. }
  6527. } else {
  6528. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6529. }
  6530. }
  6531. }
  6532. }
  6533. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6534. if err != nil {
  6535. appG.Response(http.StatusOK, e.ERROR, err.Error())
  6536. } else {
  6537. paramslist1 := strings.Split(p1, ",")
  6538. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6539. s_params1 := make([]interface{}, 0)
  6540. if len(paramslist1) > 0 && p1 != "" {
  6541. for _, v := range paramslist1 {
  6542. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  6543. }
  6544. }
  6545. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  6546. for _, item := range arr {
  6547. trgaddressList := []string{}
  6548. if _, ok := item["trgaddress"]; ok {
  6549. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6550. for _, str := range trgaddressList1 {
  6551. if str != "" {
  6552. trgaddressList = append(trgaddressList, str)
  6553. }
  6554. }
  6555. }
  6556. item["trgaddressList"] = trgaddressList
  6557. }
  6558. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  6559. }
  6560. // var wg sync.WaitGroup
  6561. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6562. // wg.Add(1)
  6563. // go func(value map[string]interface{}) {
  6564. // defer wg.Done()
  6565. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  6566. // }(value)
  6567. // }
  6568. // wg.Wait()
  6569. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6570. }
  6571. } else {
  6572. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6573. }
  6574. }
  6575. func PostPlanData(c *gin.Context) {
  6576. appG := app.Gin{C: c}
  6577. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6578. fsion := gofasion.NewFasion(string(dataByte))
  6579. logging.Info("PostRJSBData err: ", string(dataByte))
  6580. s_params := make([]interface{}, 0)
  6581. tx := restful.Engine.NewSession()
  6582. err := tx.Begin()
  6583. defer func() {
  6584. switch {
  6585. case err != nil:
  6586. if tx != nil {
  6587. tx.Rollback()
  6588. }
  6589. default:
  6590. if tx != nil {
  6591. err = tx.Commit()
  6592. }
  6593. }
  6594. if tx != nil {
  6595. tx.Close()
  6596. }
  6597. }()
  6598. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  6599. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  6600. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  6601. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  6602. if !fsion.HasKey("parammaps") {
  6603. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  6604. return
  6605. }
  6606. parammaps := fsion.Get("parammaps")
  6607. paramslist := strings.Split(p, ",")
  6608. if len(paramslist) > 0 && p != "" {
  6609. for _, value := range paramslist {
  6610. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6611. }
  6612. }
  6613. _, err = tx.SQL(sql, s_params...).Execute()
  6614. if err != nil {
  6615. logging.Error("PostRJSBData err: ", err)
  6616. msg := geterrmsg(err.Error())
  6617. appG.Response(http.StatusOK, e.ERROR, msg)
  6618. return
  6619. }
  6620. s_params = make([]interface{}, 0)
  6621. paramslist = strings.Split(p1, ",")
  6622. if len(paramslist) > 0 && p1 != "" {
  6623. for _, value := range paramslist {
  6624. // if value == "ID" {
  6625. // id := parammaps.Get("ID").ValueStr()
  6626. // pastureid := parammaps.Get("pastureid").ValueStr()
  6627. // 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
  6628. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6629. // if err != nil {
  6630. // logging.Error("PostRJSBData err: ", err)
  6631. // msg := geterrmsg(err.Error())
  6632. // appG.Response(http.StatusOK, e.ERROR, msg)
  6633. // return
  6634. // }
  6635. // for _, item := range datalist {
  6636. // id = item["id"]
  6637. // }
  6638. // s_params = append(s_params, id)
  6639. // } else {
  6640. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6641. // }
  6642. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6643. }
  6644. }
  6645. _, err = tx.SQL(sql1, s_params...).Execute()
  6646. if err != nil {
  6647. logging.Error("PostRJSBData1 err: ", err)
  6648. msg := geterrmsg(err.Error())
  6649. appG.Response(http.StatusOK, e.ERROR, msg)
  6650. return
  6651. }
  6652. s_params = make([]interface{}, 0)
  6653. paramslist = strings.Split(p2, ",")
  6654. if len(paramslist) > 0 && p2 != "" {
  6655. for _, value := range paramslist {
  6656. if value == "ID" {
  6657. id := parammaps.Get("ID").ValueStr()
  6658. pastureid := parammaps.Get("pastureid").ValueStr()
  6659. 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
  6660. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6661. if err != nil {
  6662. logging.Error("PostRJSBData err: ", err)
  6663. msg := geterrmsg(err.Error())
  6664. appG.Response(http.StatusOK, e.ERROR, msg)
  6665. return
  6666. }
  6667. for _, item := range datalist {
  6668. id = item["id"]
  6669. }
  6670. s_params = append(s_params, id)
  6671. } else {
  6672. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6673. }
  6674. }
  6675. }
  6676. _, err = tx.SQL(sql2, s_params...).Execute()
  6677. if err != nil {
  6678. logging.Error("PostRJSBData2 err: ", err)
  6679. msg := geterrmsg(err.Error())
  6680. appG.Response(http.StatusOK, e.ERROR, msg)
  6681. return
  6682. }
  6683. s_params = make([]interface{}, 0)
  6684. paramslist = strings.Split(p3, ",")
  6685. if len(paramslist) > 0 && p3 != "" {
  6686. for _, value := range paramslist {
  6687. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6688. }
  6689. }
  6690. _, err = tx.SQL(sql3, s_params...).Execute()
  6691. if err != nil {
  6692. logging.Error("PostRJSBData3 err: ", err)
  6693. msg := geterrmsg(err.Error())
  6694. appG.Response(http.StatusOK, e.ERROR, msg)
  6695. return
  6696. }
  6697. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6698. }
  6699. func CheckFeedTrgaddress(c *gin.Context) {
  6700. appG := app.Gin{C: c}
  6701. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6702. fsion := gofasion.NewFasion(string(dataByte))
  6703. fclassid := fsion.Get("fclassid").ValueStr()
  6704. feedId := fsion.Get("feedId").ValueStr()
  6705. backup1 := fsion.Get("backup1").ValueStr()
  6706. backup1List := strings.Split(backup1, ",")
  6707. tx := restful.Engine.NewSession()
  6708. defer tx.Close()
  6709. // if backup1 != "" {
  6710. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  6711. for _, feed := range feedList {
  6712. if feed["backup1"] == "" {
  6713. continue
  6714. }
  6715. feedbackupList := strings.Split(feed["backup1"], ",")
  6716. for _, feedbackup := range feedbackupList {
  6717. for _, backup := range backup1List {
  6718. if feedbackup == backup {
  6719. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  6720. return
  6721. }
  6722. }
  6723. }
  6724. }
  6725. // }
  6726. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6727. }
  6728. func ThiGetDataByName(c *gin.Context) {
  6729. appG := app.Gin{C: c}
  6730. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6731. fsion := gofasion.NewFasion(string(dataByte))
  6732. sqlnamestr := fsion.Get("name").ValueStr()
  6733. offset := fsion.Get("offset").ValueDefaultInt(0)
  6734. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  6735. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6736. tx := restful.Engine.NewSession()
  6737. err := tx.Begin()
  6738. defer func() {
  6739. switch {
  6740. case err != nil:
  6741. logging.Error("tx.Begin 事务启动失败__error:", err)
  6742. if tx != nil {
  6743. tx.Rollback()
  6744. }
  6745. default:
  6746. if tx != nil {
  6747. err = tx.Commit()
  6748. }
  6749. }
  6750. if tx != nil {
  6751. tx.Close()
  6752. }
  6753. }()
  6754. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6755. if sql != "" {
  6756. s_params := make([]interface{}, 0)
  6757. if fsion.HasKey("parammaps") {
  6758. parammaps := fsion.Get("parammaps")
  6759. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  6760. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  6761. }
  6762. paramslist := strings.Split(p, ",")
  6763. if len(paramslist) > 0 && p != "" {
  6764. for _, value := range paramslist {
  6765. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6766. if tempv, exists := c.Get("jwt_username"); exists {
  6767. s_params = append(s_params, tempv.(string))
  6768. } else {
  6769. s_params = append(s_params, "")
  6770. }
  6771. } else {
  6772. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6773. }
  6774. }
  6775. }
  6776. } else if fsion.HasKey("params") {
  6777. params := fsion.Get("params").Array()
  6778. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  6779. for _, v_params := range params {
  6780. s_params = append(s_params, v_params.ValueStr())
  6781. }
  6782. }
  6783. if returntype == "xlsx" {
  6784. var xlsxfile *xlsx.File
  6785. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  6786. //c.File("c:/dd.xlsx")
  6787. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  6788. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  6789. c.Header("Content-Transfer-Encoding", "binary")
  6790. _ = xlsxfile.Write(c.Writer)
  6791. } else {
  6792. if sqlnamestr == "getHomepageStr" {
  6793. parammaps := fsion.Get("parammaps")
  6794. pastureid := parammaps.Get("pastureid").ValueStr()
  6795. var montimeList []float64
  6796. var montime float64
  6797. var wg sync.WaitGroup
  6798. now := time.Now()
  6799. for i := 0; i < 30; i++ {
  6800. wg.Add(1)
  6801. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  6802. go func(nowstr string) {
  6803. defer wg.Done()
  6804. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  6805. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  6806. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  6807. montimeList = append(montimeList, m)
  6808. }(nowstr)
  6809. }
  6810. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6811. if err != nil {
  6812. logging.Error("GetDataByName err: ", err)
  6813. msg := geterrmsg(err.Error())
  6814. appG.Response(http.StatusOK, e.ERROR, msg)
  6815. }
  6816. wg.Wait()
  6817. for _, m := range montimeList {
  6818. montime += m
  6819. }
  6820. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  6821. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6822. return
  6823. }
  6824. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6825. if err != nil {
  6826. logging.Error("GetDataByName err: ", err)
  6827. msg := geterrmsg(err.Error())
  6828. appG.Response(http.StatusOK, e.ERROR, msg)
  6829. } else {
  6830. if sqlnamestr == "getFeedTrgaddressList" {
  6831. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6832. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6833. trgaddressList := []string{}
  6834. for _, str := range trgaddressList1 {
  6835. if str != "" {
  6836. trgaddressList = append(trgaddressList, str)
  6837. }
  6838. }
  6839. item["trgaddressList"] = trgaddressList
  6840. }
  6841. }
  6842. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6843. }
  6844. }
  6845. } else {
  6846. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6847. }
  6848. }
  6849. // func ToggleCcount(c *gin.Context) {
  6850. // appG := app.Gin{C: c}
  6851. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6852. // fsion := gofasion.NewFasion(string(dataByte))
  6853. // // 0 实际 1 软件
  6854. // status := fsion.Get("status").ValueDefaultInt64(0)
  6855. // pastureId := fsion.Get("pastureId").ValueStr()
  6856. // tx := restful.Engine.NewSession()
  6857. // err := tx.Begin()
  6858. // defer func() {
  6859. // switch {
  6860. // case err != nil:
  6861. // logging.Error("tx.Begin 事务启动失败__error:", err)
  6862. // if tx != nil {
  6863. // tx.Rollback()
  6864. // }
  6865. // default:
  6866. // if tx != nil {
  6867. // err = tx.Commit()
  6868. // }
  6869. // }
  6870. // if tx != nil {
  6871. // tx.Close()
  6872. // }
  6873. // }()
  6874. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  6875. // if err != nil {
  6876. // logs.Error(err)
  6877. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6878. // return
  6879. // }
  6880. // for _, bar := range barList {
  6881. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  6882. // if err != nil {
  6883. // logs.Error(err)
  6884. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6885. // return
  6886. // }
  6887. // if !exist {
  6888. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  6889. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  6890. // if err != nil {
  6891. // logs.Error(err)
  6892. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6893. // return
  6894. // }
  6895. // }
  6896. // }
  6897. // if status == 0 {
  6898. // tx.Exec(`update feedp set ccount = actualcount `)
  6899. // }else{
  6900. // tx.Exec(`update feedp set ccount = softccount `)
  6901. // }
  6902. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  6903. // if err != nil {
  6904. // logs.Error(err)
  6905. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6906. // return
  6907. // }
  6908. // for _, feedpData :=range feedpList{
  6909. // var feedpargs []interface{}
  6910. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  6911. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  6912. // if _, ok := feedpData["ftname"]; ok {
  6913. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  6914. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  6915. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  6916. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  6917. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6918. // } else {
  6919. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  6920. // }
  6921. // if _, ok := feedpData["ptsfname"]; ok {
  6922. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  6923. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  6924. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  6925. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  6926. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6927. // } else {
  6928. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  6929. // }
  6930. // upFeedpSql += " where barname = ? and pastureid = ? "
  6931. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  6932. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  6933. // if err != nil {
  6934. // logs.Error(err)
  6935. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6936. // return
  6937. // }
  6938. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  6939. // if err != nil {
  6940. // logs.Error(err)
  6941. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6942. // return
  6943. // }
  6944. // if !exist1 {
  6945. // _, 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) `,
  6946. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6947. // if err != nil {
  6948. // logs.Error(err)
  6949. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6950. // return
  6951. // }
  6952. // }
  6953. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  6954. // if err != nil {
  6955. // logs.Error(err)
  6956. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6957. // return
  6958. // }
  6959. // if !exist2 {
  6960. // _, 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) `,
  6961. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6962. // if err != nil {
  6963. // logs.Error(err)
  6964. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6965. // return
  6966. // }
  6967. // }
  6968. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  6969. // if err != nil {
  6970. // logs.Error(err)
  6971. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6972. // return
  6973. // }
  6974. // if !exist3 {
  6975. // _, 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) `,
  6976. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6977. // if err != nil {
  6978. // logs.Error(err)
  6979. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6980. // return
  6981. // }
  6982. // }
  6983. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  6984. // if err != nil {
  6985. // logs.Error(err)
  6986. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6987. // return
  6988. // }
  6989. // if !exist4 {
  6990. // _, 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) `,
  6991. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6992. // if err != nil {
  6993. // logs.Error(err)
  6994. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6995. // return
  6996. // }
  6997. // }
  6998. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  6999. // if err != nil {
  7000. // logs.Error(err)
  7001. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7002. // return
  7003. // }
  7004. // if !exist5 {
  7005. // _, 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) `,
  7006. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7007. // if err != nil {
  7008. // logs.Error(err)
  7009. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7010. // return
  7011. // }
  7012. // }
  7013. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7014. // if err != nil {
  7015. // logs.Error(err)
  7016. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7017. // return
  7018. // }
  7019. // if !exist6 {
  7020. // _, 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) `,
  7021. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7022. // if err != nil {
  7023. // logs.Error(err)
  7024. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7025. // return
  7026. // }
  7027. // }
  7028. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7029. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7030. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7031. // and pastureid = ? and times = ?`
  7032. // var fpdargs1 []interface{}
  7033. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7034. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7035. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7036. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7037. // if err != nil {
  7038. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7039. // return
  7040. // }
  7041. // var fpdargs2 []interface{}
  7042. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7043. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7044. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7045. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7046. // if err != nil {
  7047. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7048. // return
  7049. // }
  7050. // var fpdargs3 []interface{}
  7051. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7052. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7053. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7054. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7055. // if err != nil {
  7056. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7057. // return
  7058. // }
  7059. // var fpdargs4 []interface{}
  7060. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7061. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7062. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7063. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7064. // if err != nil {
  7065. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7066. // return
  7067. // }
  7068. // var fpdargs5 []interface{}
  7069. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7070. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7071. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7072. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7073. // if err != nil {
  7074. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7075. // return
  7076. // }
  7077. // var fpdargs6 []interface{}
  7078. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7079. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7080. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7081. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7082. // if err != nil {
  7083. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7084. // return
  7085. // }
  7086. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7087. // 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()
  7088. // if err != nil {
  7089. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7090. // return
  7091. // }
  7092. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7093. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7094. // upFpdetailList := make([]*upFpdetail, 0)
  7095. // for _, newfpd := range newList {
  7096. // for _, oldfpd := range oldFpdList {
  7097. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7098. // var oldweight, newweight float64
  7099. // if oldfpd["weight"] != nil {
  7100. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7101. // }
  7102. // if newfpd["weight"] != nil {
  7103. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7104. // }
  7105. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7106. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7107. // Old: oldweight,
  7108. // New: newweight,
  7109. // Times: newfpd["times"].(int64),
  7110. // Ptid: newfpd["ptid"].(int64),
  7111. // Fweight: fweight,
  7112. // Id: oldfpd["id"].(int64),
  7113. // })
  7114. // break
  7115. // }
  7116. // }
  7117. // }
  7118. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7119. // }
  7120. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7121. // }
  7122. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7123. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7124. if err != nil {
  7125. return err
  7126. }
  7127. for _, item := range feedpList {
  7128. // if item["ftid"].(string) != data["ftid"].(string) {
  7129. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7130. if err != nil {
  7131. return err
  7132. }
  7133. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7134. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7135. if err != nil {
  7136. return err
  7137. }
  7138. // }
  7139. }
  7140. return nil
  7141. }