123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129 |
- package api
- import (
- "bytes"
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
- "os"
- "path"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- "tmr-watch/conf/setting"
- "tmr-watch/http/handle/jpud"
- "tmr-watch/http/handle/restful"
- "tmr-watch/http/handle/ymy"
- "tmr-watch/models"
- "tmr-watch/module"
- "tmr-watch/pkg/app"
- "tmr-watch/pkg/e"
- "tmr-watch/pkg/logging"
- "github.com/360EntSecGroup-Skylar/excelize"
- "github.com/Anderson-Lu/gofasion/gofasion"
- "github.com/astaxie/beego/logs"
- "github.com/gin-gonic/gin"
- "github.com/qichengzx/coordtransform"
- "github.com/tealeg/xlsx"
- "github.com/xormplus/xorm"
- excelizexuri "github.com/xuri/excelize/v2"
- )
- // @Summary 根据SQL执行得到数据集
- // @Tags getData
- // @Accept json
- // @Produce json
- // @Param sql query string true "sql"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/getdata [POST]
- func GetData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func Testpartitions(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
- user := fsion.Get("user").ValueStr() //获取新数据库用户
- passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
- host := fsion.Get("host").ValueStr() //获取新数据库名称
- port := fsion.Get("port").ValueStr() //获取新数据库名称
- sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
- if sqls == nil || err1 != nil {
- appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
- }
- sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
- connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
- mydb, err := sql.Open("mysql", connecting) //连接新连接
- if err != nil {
- println("err1", err.Error())
- }
- _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
- if err != nil {
- println("err2", err.Error())
- }
- mydb.Close()
- connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
- mydb, err = sql.Open("mysql", connecting)
- if err != nil {
- println("err3", err.Error())
- }
- defer mydb.Close()
- if err == nil {
- mydb.SetMaxOpenConns(10)
- mydb.SetMaxIdleConns(10)
- }
- errmsg := ""
- if err == nil {
- //tx ,_ :=mydb.Begin()
- for _, sqlstr := range sqlstrs {
- //println("sqlstr---",sqlstr)
- if sqlstr == "" {
- continue
- }
- _, err = mydb.Exec(sqlstr)
- if err != nil {
- println("err4", err.Error())
- errmsg = err.Error()
- //err1 :=tx.Rollback()
- }
- }
- //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
- //err =tx.Commit()
- }
- if errmsg == "" {
- appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
- }
- }
- func TestData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- token := ""
- if tempv, exists := c.Get("jwt_username"); exists {
- token = tempv.(string)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
- // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
- // tmrNameList := []string{}
- // for _, tmr := range tmrArray {
- // tmrNameList = append(tmrNameList, tmr.ValueStr())
- // }
- // s_params = append(s_params, strings.Join(tmrNameList, ","))
- // } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- if sqlnamestr == "getHomepageStr" {
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- var montimeList []float64
- var montime float64
- var wg sync.WaitGroup
- now := time.Now()
- for i := 0; i < 30; i++ {
- wg.Add(1)
- nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
- go func(nowstr string) {
- defer wg.Done()
- sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
- slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
- if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
- m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
- montimeList = append(montimeList, m)
- }
- }(nowstr)
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- wg.Wait()
- for _, m := range montimeList {
- montime += m
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataBySqlIN(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // 错误处理
- // 将报错信息处理成汉字
- func geterrmsg(errstr string) (msgstr string) {
- var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
- rs := []rune(errstr)
- if hzRegexp.MatchString(string(rs[0])) {
- msgstr = errstr
- return
- }
- if strings.Contains(errstr, "Duplicate entry") {
- strs := strings.Split(errstr, ` key '`)
- if len(strs) > 1 {
- if len(strs[len(strs)-1]) > 1 {
- errstr = "Duplicate entry :" + strs[len(strs)-1]
- }
- }
- }
- msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
- if err != nil {
- msgstr = errstr
- return
- }
- if msg == nil || len(msg) == 0 {
- var param []interface{}
- param = append(param, errstr, errstr)
- go func() {
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
- if err != nil {
- logging.Error("insert into err_msg(err,msg) err", err)
- }
- }()
- msgstr = errstr
- } else {
- msgstr = msg[0]["msg"]
- }
- return
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname body json true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Param s formData json true "ss"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNameForm [POST]
- func GetDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- //sqlnamestr := c.PostForm("measureNumber")
- //dataByte, _ := ioutil.ReadAll(c.Request.Body)
- //fsion := gofasion.NewFasion(string(dataByte))
- //sqlnamestr := fsion.Get("name").ValueStr()
- //offset := fsion.Get("offset").ValueInt()
- //pagecount := fsion.Get("pagecount").ValueInt()
- //returntype := fsion.Get("returntype").ValueStr()
- //params := fsion.Get("params").Array()
- c.Request.ParseForm()
- params := c.Request.Form
- offset := 0
- pageSize_ := 0
- returntype := params.Get("page")
- if returntype == "" {
- returntype = "0"
- }
- if tempv, exists := c.Get("jwt_username"); exists {
- params.Set("JwtUserName", tempv.(string))
- } else {
- params.Set("JwtUserName", "")
- }
- sqlnamestr := params.Get("name")
- logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- if returntype == "1" {
- pageNum, error := strconv.Atoi(params.Get("pageNum"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
- }
- pageSize, error := strconv.Atoi(params.Get("pageSize"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
- }
- pageSize_ = pageSize
- offset = pageNum
- }
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- c.Header("Content-Type", "application/octet-stream")
- c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // @Summary 递归获取所有
- // @Tags menu
- // @Accept json
- // @Produce json
- // @Param Ton query string true "Ton"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Router /authdata/GetRoleMenus [GET]
- func GetRecuDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- parentidname := fsion.Get("idname").ValueStr()
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- params := make(map[string]interface{})
- s_params := make([]interface{}, 0)
- if fsion.HasKey("params") {
- for _, v_params := range fsion.Get("params").Array() {
- s_params = append(s_params, v_params.ValueStr())
- }
- params["params"] = s_params
- } else {
- jparams := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- params[value] = tempv.(string)
- } else {
- params[value] = ""
- }
- } else {
- params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
- }
- }
- }
- }
- queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
- logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNames
- // @Accept json
- // @Produce json
- // @RequestBody sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNames [POST]
- func GetDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没找到"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- offset := fsion2.Get("offset").ValueInt()
- pagecount := fsion2.Get("pagecount").ValueInt()
- returntype := fsion2.Get("returntype").ValueStr()
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
- if err != nil {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- queryData[fsion2.Get("name").ValueStr()] = errorm
- logging.Error("GetDataByNames err: ", err)
- continue
- } else {
- queryData[fsion2.Get("name").ValueStr()] = queryData1
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByNameForm [POST]
- func PostDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- c.Request.ParseForm()
- params := c.Request.Form
- sqlnamestr := params.Get("name")
- logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // GetReportform 将数据集转换格式
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- func GetReportform(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- checked := fsion.Get("checked").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
- mode := parammaps.Get("mode").ValueDefaultInt(0)
- logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- // GetUpkeepPlan 保养计划
- func GetUpkeepPlan(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- if v, ok := value["id"]; ok {
- //month = "2020-03"
- seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
- if seviceplans != nil {
- for _, va := range seviceplans { //根据保养计划获取保养单
- //day,_ :=strconv.Atoi(va["day"])
- bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
- //buk := make(map[string]map[string]string)
- for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
- jstr := ""
- if bu["plantime"][8:9] == "0" {
- jstr = "m" + bu["plantime"][9:]
- } else {
- jstr = "m" + bu["plantime"][8:]
- }
- if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- if bu["flowCompeleted"] >= "2" {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
- }
- }
- }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
- // todo 优化性能 children统一查询
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- func GetArrList(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetAccount(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // PostDataByName 根据APISQL表中SQL执行得到数据集
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func PostDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- var err error
- queryData, err := module.PostDataByName(c, fsion)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- var (
- keyWord string
- )
- switch fsion.Get("name").ValueStr() {
- case "insertFeedclass":
- keyWord = "feed"
- err = module.GroupCategorySync(keyWord, fsion)
- case "deleteFeedclass":
- keyWord = "feed_delete"
- err = module.GroupCategoryDelete(keyWord, fsion)
- case "insertCowclass":
- keyWord = "cow"
- err = module.GroupCategorySync(keyWord, fsion)
- case "deleteCowclass":
- keyWord = "cow_delete"
- err = module.GroupCategoryDelete(keyWord, fsion)
- // case "updateFT":
- // FtdetailSurplus(fsion)
- // case "updateFeed":
- // FeedSurplus(fsion)
- default:
- }
- if err != nil {
- logging.Error(keyWord, err)
- }
- if queryData != nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- //人脸识别/格润富德接口
- func GetRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- pagecount = 1
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
- _, err = tx.SQL(`update tmr set xianfeng = (select id from downloadedplan where lpplantype = 5 and mydate = date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted = 0 )
- where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
- date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
- and lpplantype in(0,1)) `).Execute()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- var wg sync.WaitGroup
- for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- wg.Add(1)
- go func(value map[string]interface{}) {
- defer wg.Done()
- // ,havebutton = 1
- _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
- }(value)
- }
- wg.Wait()
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- fmt.Println("先锋获取数据:", time.Now(), queryData)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBData err: ", string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- projuctid := parammaps.Get("projuctid").ValueStr()
- _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
- where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
- and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
- where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
- and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
- if err != nil {
- logging.Error("PostRJSBData-0 err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func PostRJSBDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte)).Array()
- logging.Info("PostRJSBDatas err: ", string(dataByte))
- fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
- for _, fsion := range fsions {
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- ID := parammaps.Get("ID").ValueStr()
- if ID == "" {
- continue
- }
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err := tx.SQL(sql, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- // ALTER TABLE `tmr`
- // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
- projuctid := parammaps.Get("projuctid").ValueStr()
- _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
- where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
- and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
- where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
- and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
- projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
- if err != nil {
- logging.Error("PostRJSBData-0 err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
- if count == 0 {
- fmt.Println(projuctid, "先锋回传计划已完成", count, err)
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags ExecDataByConfig
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func ExecDataByConfig(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- fmt.Println(paramvalue["name"])
- if paramvalue["name"].(string) == "updateBigFP" {
- err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- // if paramvalue["name"].(string) == "createdownloadedplan" {
- // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
- // }
- }
- if err == nil {
- if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
- appG.Response(http.StatusOK, e.SUCCESS, tempval)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- func interfacetostring(val interface{}) string {
- switch val.(type) {
- case string:
- ss := val.(string)
- return ss
- break
- case int:
- ss := val.(int)
- return strconv.Itoa(ss)
- break
- case int64:
- ss := val.(int64)
- return strconv.FormatInt(ss, 10)
- break
- case float64:
- ss := val.(float64)
- return strconv.FormatFloat(ss, 'E', -1, 32)
- break
- }
- return ""
- }
- func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- for _, ParamMapList := range ParamMap {
- if v, ok := ParamMapList["resultname"]; ok {
- if v == valuestring[tempstrb+1:tempstre] {
- if v1, ok := ParamMapList["resultmaps"]; ok {
- if newA, ok := v1.([]map[string]interface{}); ok {
- return interfacetostring(newA[0][valuestring[tempstre+1:]])
- } else if newA, ok := v1.(map[string]interface{}); ok {
- return interfacetostring(newA[valuestring[tempstre+1:]])
- }
- }
- }
- }
- }
- } else {
- return valuestring
- }
- } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
- return fmt.Sprintf("%f", valuestring)
- }
- return ""
- }
- func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
- if s, ok := v.(string); ok {
- return s
- } else if s, ok := v.(float64); ok {
- return strconv.FormatFloat(s, 'f', -1, 64)
- // return strconv.FormatInt(int64(s), 10)
- }
- }
- }
- }
- return ""
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- if sqlname != "checkPassword" && sqlname != "updatePwd" {
- ss = ""
- }
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- if sqltype == "s1" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "sm" {
- tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "v" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- }
- if err != nil {
- return nil, err
- }
- if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
- return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
- }
- } else if sqltype == "e" {
- tempVal_arrary := make([]map[string]interface{}, 0)
- tempVal_map := make(map[string]interface{})
- tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
- if err == nil {
- fasion["resultmaps"] = tempValParam.(map[string]interface{})
- tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
- tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
- tempVal_arrary = append(tempVal_arrary, tempVal_map)
- return tempVal_arrary, err
- }
- return nil, err
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- // @Summary 删除图片
- // @Tags RemovePicByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemovePicByName(c *gin.Context) {
- logging.Info("RemovePicByName ", c.Keys)
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- picname := fsion.Get("picname").ValueStr()
- sql, _ := restful.GetSqlByNameDB(sqlnamestr)
- params := fsion.Get("params").Array()
- s_params := make([]interface{}, 0)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if picname != "" {
- // Destination
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
- err := os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- }
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 删除文件
- // @Tags RemoveFileByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemoveFileByName(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Param("id")
- logging.Info("DownloadFile ", c.Keys, id)
- eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
- if eqdoc == nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
- appG.Response(http.StatusOK, e.SUCCESS, "OK")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func UpdateDataRelation(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- tablename := fsion.Get("name").ValueStr()
- dataname := fsion.Get("dataname").ValueStr()
- datavalue := fsion.Get("datavalue").ValueStr()
- valuename := fsion.Get("valuename").ValueStr()
- logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
- values := fsion.Get("values").Array()
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
- " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
- d_params := make([]interface{}, 4)
- d_params[0] = datavalue
- s_params := ""
- for _, v_values := range values {
- d_params[1] = v_values.ValueStr()
- if s_params == "" {
- s_params = v_values.ValueStr()
- } else {
- s_params = s_params + "," + v_values.ValueStr()
- }
- d_params[2] = d_params[1]
- d_params[3] = d_params[0]
- _, err := execDataBySqlT(insertSqlstr, d_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- break
- }
- }
- if s_params != "" {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDatasByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDatasByName [POST]
- func PostDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Get("array").Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- ss := fsion2.Get("name")
- aa := fsion2.Get("params")
- fmt.Println(ss, aa)
- logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没有找到"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- //ids,err := setting.SnowIds.NextId()
- //if err !=nil{
- // ids = time.Now().UnixNano()
- // logging.Info("create SnowIds err",err)
- //}
- //s_params = append(s_params, ids)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- _, err := execDataBySql(sql, s_params)
- if err != nil {
- logging.Error("PostDataByName err: ", err)
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- errorm["param"] = s_params
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.SUCCESS
- errorm["message"] = "success"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- }
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "NO SQL"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else {
- queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
- return queryData, err
- }
- }
- func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else {
- fmt.Println(params)
- queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- }
- }
- func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
- paramslist := strings.Split(Params, ",")
- s_params := make([]interface{}, 0)
- if isList {
- for _, v_params := range thisParams["params"].([]interface{}) {
- s_params = append(s_params, v_params)
- }
- } else {
- paramslist := strings.Split(Params, ",")
- if len(paramslist) > 0 && Params != "" {
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
- for _, queryData_ := range queryData {
- if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
- if isList {
- if queryData_[idname] != nil {
- thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
- }
- } else {
- if queryData_[idname] != nil {
- thisParams[idname] = queryData_[idname].(interface{})
- }
- if len(paramslist) > 0 && Params != "" {
- s_params = make([]interface{}, 0)
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
- } else {
- }
- }
- return queryData, err
- }
- func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- queryData, err := restful.ExecQueryT(sqlstr, params, tx)
- return queryData, err
- }
- func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- // @Summary 导入excel文件到数据库,excel第一行作为参数
- // @Tags ImportExcel
- // @Accept json
- // @Produce json
- // @Param file query string true "文件名"
- // @Param name header string true "执行sql的名字"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/ImportExcel [POST]
- func ImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- //importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- fmt.Println(outentry, entry)
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- fmt.Println(sql, s_params)
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func TransfTime(timestr string) (string, error) {
- if timestr == "" {
- return time.Now().Format("2006-01-02"), nil
- }
- days, err := strconv.Atoi(timestr)
- if err != nil {
- if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
- return "20" + timestr[6:] + "-" + timestr[:5], nil
- }
- _, err := time.Parse("2006-01-02", timestr)
- if err != nil {
- t, err := time.Parse("2006/01/02", timestr)
- if err != nil {
- t, err := time.Parse("2006.01.02", timestr)
- if err != nil {
- return "", err
- } else {
- return t.Format("2006-01-02"), nil
- }
- } else {
- return t.Format("2006-01-02"), nil
- }
- } else {
- return timestr, nil
- }
- }
- times, _ := time.Parse("2006-01-02", "1899-12-30")
- times = times.AddDate(0, 0, days)
- return times.Format("2006-01-02"), nil
- }
- func Createchart(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- chart_name := fsion.Get("chart_name").ValueStr()
- desc := fsion.Get("desc").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- source_id := fsion.Get("source_id").ValueStr()
- emp := fsion.Get("emp").ValueStr()
- content := fsion.Get("content").Json()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
- ids, pastureid, chart_name, 0, emp, desc, source_id)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Updatedashboard(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- dashboard_id := fsion.Get("dashboard_id").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- content := fsion.Get("content").Json()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- layout := mapResult["layout"]
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
- if err != nil {
- println("2", err.Error())
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- if exec != nil {
- if exec[0]["content"] == nil {
- mapR := make(map[string]interface{})
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- } else {
- var mapR map[string]interface{}
- err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err2)
- }
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
- }
- }
- }
- func ExecSQL(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- content := fsion.Get("content").Json()
- pastureid := fsion.Get("pastureid").ValueStr()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- sqlstr := "select "
- groupstr := " GROUP BY "
- for _, value := range mapResult["selectedDimension"].([]interface{}) {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- }
- for _, value := range mapResult["selectedCalcul"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- if _, ok := mapResult["selectedCalcul2"]; ok {
- for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
- sqlstr = sqlstr + " where pastureid=" + pastureid
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr + " and "
- }
- println(len(mapResult["filters"].([]interface{})), sqlstr)
- for _, value := range mapResult["filters"].([]interface{}) {
- switch value.(map[string]interface{})["filterOperator"].(string) {
- case ">", "=", "<", ">=", "<=", "!=", "like":
- 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 "
- case "IN":
- sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
- for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
- sqlstr = sqlstr + value1.(string) + ","
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + ")" + " AND "
- case "BETWEEN":
- 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 "
- }
- }
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr[0 : len(sqlstr)-4]
- }
- //
- groupstr = groupstr[0 : len(groupstr)-1]
- sqlstr = sqlstr + groupstr + " "
- if len(mapResult["orderByStrs"].([]interface{})) > 0 {
- sqlstr = sqlstr + " order by "
- }
- //
- for key, value := range mapResult["orderByStrs"].([]interface{}) {
- if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
- sqlstr = sqlstr + value.(string) + " "
- } else {
- sqlstr = sqlstr + value.(string) + ","
- }
- }
- //
- sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- exec, err := tx.SQL(sqlstr).Query().List()
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Dashboards(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- //sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- //paramslist1 := strings.Split(p1, ",")
- dids := make([]interface{}, 0)
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- var mapResult map[string]interface{}
- dids = append(dids, value["dashboard_id"])
- if value["content"] != nil {
- err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
- if err1 != nil {
- println("JsonToMapDemo1 err: ", err1)
- }
- temap := make(map[string]interface{})
- tem := mapResult["layout"].([]interface{})
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- a := false
- for _, v2 := range tem {
- if v2.(map[string]interface{})["id"].(string) == va {
- a = true
- //println("va1======",va)
- }
- }
- if !a {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- } else {
- temap := make(map[string]interface{})
- tem := make([]interface{}, 0)
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- }
- }
- queryData.(map[string]interface{})["order"] = dids
- queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
- fsion := gofasion.NewFasion(parammaps)
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- body := []byte("")
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- body, _ = json.Marshal(queryData)
- }
- }
- }
- bs := bytes.NewBuffer(body)
- client := &http.Client{}
- //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
- req, err := http.NewRequest(RequestMethod,
- url,
- bs,
- )
- if err != nil {
- }
- req.Header.Set("Content-Type", "application/json;charset=utf-8")
- req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
- if err != nil {
- // handle error
- }
- resp, err := client.Do(req)
- if err != nil {
- return ""
- }
- defer resp.Body.Close()
- result_body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return ""
- }
- fmt.Println(string(result_body))
- return ""
- }
- func GetSummary(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- parammaps := fsion.Get("parammaps")
- status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
- genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
- isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
- tx := restful.Engine.NewSession()
- defer tx.Close()
- sqlnamestr := ""
- if genre == "0" {
- if status == "0" {
- sqlnamestr = "getAccuracyJSY"
- } else if status == "1" {
- sqlnamestr = "getAccuracyHFT"
- } else if status == "2" {
- sqlnamestr = "getAccuracyHNS"
- } else if status == "3" {
- sqlnamestr = "getAccuracyHSC"
- } else if status == "4" {
- sqlnamestr = "getAccuracyHCC"
- } else if status == "5" {
- sqlnamestr = "getAccuracyMC"
- } else if status == "6" {
- sqlnamestr = "getAccuracyFeedHL"
- } else if status == "7" {
- sqlnamestr = "getAccuracyRT"
- }
- } else {
- if status == "0" {
- sqlnamestr = "getAccuracySCCJSY"
- } else if status == "1" {
- sqlnamestr = "getAccuracySFT"
- } else if status == "2" {
- sqlnamestr = "getAccuracySNS"
- } else if status == "3" {
- sqlnamestr = "getAccuracySSC"
- } else if status == "4" {
- sqlnamestr = "getAccuracySCC"
- } else if status == "5" {
- sqlnamestr = "getAccuracySLCL"
- } else if status == "7" {
- sqlnamestr = "getAccuracySCCRT"
- }
- }
- if isDate == "1" {
- sqlnamestr += "Date"
- }
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- // fmt.Println(sqlnamestr, sql)
- if sql != "" {
- s_params := make([]interface{}, 0)
- // if fsion.HasKey("parammaps") {
- fmt.Println(s_params, "222", p)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // type lpplanStruct struct {
- // Id int64 `xorm:"id"`
- // Tmrname string `xorm:"tmrname"`
- // Tmrid int64 `xorm:"tmrid"`
- // Sort int64 `xorm:"sort"`
- // Sel int64 `xorm:"sel"`
- // Times int64 `xorm:"times"`
- // Ftname string `xorm:"ftname"`
- // Ftid int64 `xorm:"ftid"`
- // Maxweight float64 `xorm:"maxweight"`
- // Sumweight float64 `xorm:"sumweight"`
- // Sumcowcount int64 `xorm:"sumcowcount"`
- // Pastureid string `xorm:"pastureid"`
- // Display string `xorm:"display"`
- // Issplit int64 `xorm:"issplit"`
- // BeginTime string `xorm:"begintime"`
- // }
- func UpdateFTdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- fTChange := make(map[string]interface{}, 0)
- // fpdOldDataList := make([]map[string]interface{}, 0)
- // fpdDataList := make([]map[string]interface{}, 0)
- fsion := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- createdate := time.Now().Format("2006-01-02 15:04:05")
- err := json.Unmarshal(dataByte, &tempval_)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- tx := restful.Engine.NewSession()
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- if v1["name"] == "updateFPbyFTChange" {
- fTChange = v1
- continue
- }
- tempval = append(tempval, v1)
- }
- }
- }
- parammaps := fTChange["parammaps"].(map[string]interface{})
- // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- err = tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- // 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 ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
- // UNION
- // 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 ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
- // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- tx.Commit()
- // go func() {
- if fTChange != nil {
- parammaps := fTChange["parammaps"].(map[string]interface{})
- if parammaps["type"].(float64) == 1 {
- _, err = tx.SQL(`UPDATE feedp fp
- set
- ccountratio = ccount *(ratio /100 ),
- fp.ftweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- _, err = tx.SQL(`UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100
- WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- } else {
- _, err = tx.SQL(`UPDATE feedp fp
- SET ccountratio = ccount *(ratio /100 ),
- fp.supplyweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- _, err = tx.SQL(`UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- }
- values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
- ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
- ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
- ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
- ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
- ),0) as '6' from feedp fp join bar b on b.id = fp.barid
- join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
- // fmt.Println(ftId)
- FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
- // 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((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
- // UNION
- // SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
- // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
- // lpplanList := make([]*lpplanStruct, 0)
- // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
- // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
- // (select ifnull(volume,0) from feedtemplet where id = lpplan.ftid) ) maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
- // if err != nil {
- // logs.Error(err, 1)
- // return
- // }
- // lppidlist := []string{}
- // for _, lpp := range lpplanList {
- // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
- // }
- // if len(lppidlist) <= 0 {
- // appG.Response(http.StatusOK, e.SUCCESS, true)
- // return
- // }
- // lpplandtl1AllList := make([]*lpplandtl1, 0)
- // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
- // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
- // if err != nil {
- // // tx.Rollback()
- // logs.Error(err, 2, parammaps["pastureid"])
- // return
- // }
- // for _, lpp := range lpplandtl1AllList {
- // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
- // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // }
- // var wg sync.WaitGroup
- // for _, old := range fpdOldDataList {
- // for _, fpd := range fpdDataList {
- // wg.Add(1)
- // go func(old, fpd map[string]interface{}) {
- // updateLppandList := make([]*lpplandtl1, 0)
- // defer wg.Done()
- // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
- // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
- // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
- // // if weight > oldweight {
- // // return
- // // }
- // var w float64
- // var status int
- // if weight < oldweight {
- // if weight >= 0 {
- // return
- // }
- // w = weight
- // status = 0
- // } else {
- // if oldweight > 0 {
- // return
- // }
- // w = weight
- // status = 1
- // }
- // // fweight = w
- // for _, lpp := range lpplanList {
- // var fweight float64
- // var lweight float64
- // lpplandtl1List := make([]*lpplandtl1, 0)
- // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
- // for _, lppland := range lpplandtl1AllList {
- // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
- // lpplandtl1List = append(lpplandtl1List, lppland)
- // }
- // }
- // if len(lpplandtl1List) == 0 {
- // continue
- // }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- // if status == 0 {
- // if lweight <= 0 {
- // continue
- // }
- // } else {
- // if lpp.Maxweight <= lweight {
- // continue
- // }
- // }
- // for _, lppland := range lpplandtl1List {
- // if fpdid == lppland.Fpdid {
- // if status == 1 {
- // // if w <= lppland.Lweight {
- // if lpp.Maxweight <= lweight {
- // continue
- // }
- // if w+lweight <= lpp.Maxweight {
- // lppland.Lweight += w
- // lweight += w
- // fweight += w
- // w = 0
- // } else {
- // w = w - (lpp.Maxweight - lweight)
- // n := (lpp.Maxweight - lweight)
- // lppland.Lweight = lppland.Lweight + n
- // lweight += n
- // fweight += n
- // }
- // } else {
- // if lppland.Lweight == 0 {
- // continue
- // }
- // if w+lppland.Lweight >= 0 {
- // lppland.Lweight = lppland.Lweight + w
- // lweight = lweight + w
- // fweight = fweight + w
- // w = 0
- // } else {
- // w = w + lppland.Lweight
- // lweight = lweight - lppland.Lweight
- // fweight = fweight - lppland.Lweight
- // lppland.Lweight = 0
- // }
- // }
- // updateLppandList = append(updateLppandList, lppland)
- // break
- // }
- // }
- // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
- // if err != nil {
- // // tx.Rollback()
- // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
- // return
- // }
- // for _, lppland := range updateLppandList {
- // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
- // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
- // if err != nil {
- // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
- // // tx.Rollback()
- // logs.Error(err, 3)
- // return
- // }
- // // defer wg.Done()
- // }
- // updateLppandList = []*lpplandtl1{}
- // if w == 0 {
- // break
- // }
- // }
- // }
- // }(old, fpd)
- // }
- // }
- // wg.Wait()
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- now := createdate
- // for _, oldFpd := range oldFpdDataList {
- for _, newFpd := range newFpdDataList {
- // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
- // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
- // go func() {
- _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- // }()
- }
- // break
- // }
- // }
- // }
- // for _, oldLpplandtl1 := range oldLpplandtl1List {
- for _, newLpplandtl1 := range newLpplandtl1List {
- // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
- // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
- // go func() {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- // }()
- // }
- // break
- // }
- // }
- }
- // for _, oldFeedp := range oldFeedpList {
- for _, newFeedp := range newFeedpList {
- // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
- // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
- // go func() {
- _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }
- // ,,parammaps["ftid"])
- // surplus, surplusId, id, pastureId string
- // FtdetailSurplusFt(parammaps["ftid"].)
- ftList1, err := tx.SQL(` SELECT
- f.id,
- f.surplus surplusId,
- f.pastureid,
- s.surplus
- FROM
- feedtemplet f
- JOIN surplus s ON s.id = f.surplus
- WHERE
- f.id = ?`, parammaps["ftid"]).QueryString()
- for _, ft := range ftList1 {
- FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- type lpplandtlInfo struct {
- Id int64 `xorm:"id"`
- Pastureid int64 `xorm:"pastureid"`
- Lppid int64 `xorm:"lppid"`
- Barid int64 `xorm:"barid"`
- Barname string `xorm:"barname"`
- Fpdid int64 `xorm:"fpdid"`
- Fttype int64 `xorm:"fttype"`
- Lweight float64 `xorm:"lweight"`
- Sort int64 `xorm:"sort"`
- Tmrid int64 `xorm:"tmrid"`
- Tmrname string `xorm:"tmrname"`
- Cowcount int64 `xorm:"cowcount"`
- Ccountradio float64 `xorm:"ccountradio"`
- Background string `xorm:"background"`
- Lweighthis float64 `xorm:"lweighthis"`
- Maxweight float64 `xorm:"maxweight"`
- }
- func UpdateFpdetailBar(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- pastureid := fsion.Get("pastureid").ValueStr()
- id := fsion.Get("id").ValueStr()
- tx := restful.Engine.NewSession()
- tx.Begin()
- 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 `,
- pastureid, id).Query().List()
- if err != nil {
- logs.Error(err)
- }
- for _, fpd := range fpdList {
- lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
- where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
- pastureid, fpd["id"]).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- } else {
- weight := fpdweight - lweight
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- } else {
- // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
- // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- weight = 0
- break
- }
- }
- }
- }
- }
- fsionData := fsion.Get("data").Array()
- for _, list := range fsionData {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
- ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
- ftmap["times"] = list.Get("times").ValueInt64()
- ftmap["ptid"] = list.Get("ptid").ValueStr()
- ftmap["ptsid"] = list.Get("ptsid").ValueStr()
- // fmt.Println(ftmap)
- // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
- // and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
- // if count == 1 {
- // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
- // and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // }
- fpdDataList, err := tx.SQL(`
- SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ifnull(ptsid,-1) ) ptsid ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
- fttype := -1
- if fpd["fttype"].(string) == "1" {
- fttype = 1
- }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
- t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
- (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // continue
- if weight <= 0 {
- continue
- }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return
- }
- }
- if w == 0 {
- break
- }
- // break
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- tx.Commit()
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- for _, newLpplandtl1 := range newLpplandtl1List {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetProcessAnalysis(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- parammaps := fsion.Get("parammaps")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- tmrtnameStr := ""
- for _, tmr := range parammaps.Get("tmrtname").Array() {
- if len(tmrtnameStr) == 0 {
- tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
- } else {
- tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
- }
- }
- if len(tmrtnameStr) > 0 {
- sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
- }
- sql += " ORDER BY d.intime"
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func UpdateFeedtempletStatus(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- tx := restful.Engine.NewSession()
- tx.Begin()
- _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- tx.Commit()
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func AddFtdry(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- parammaps := fsion.Get("parammaps")
- logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- var actweight float64
- actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
- where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
- and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
- where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
- and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
- group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
- 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()
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- if len(actweightList) > 0 {
- for _, item := range actweightList {
- fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- actweight = fl
- }
- } else {
- dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
- where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
- parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- for _, item := range dryList {
- dry, err := strconv.ParseFloat(item["dry"].(string), 64)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- actweight += parammaps.Get("freshweight").ValueFloat64() * dry
- }
- }
- if sqlnamestr == "insertFtdry" {
- s_params = append(s_params, actweight)
- } else if sqlnamestr == "updateFtdry" {
- sql = fmt.Sprintf(sql, actweight)
- }
- queryData, err := execDataBySqlT(sql, s_params, tx)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func CheckDates(c *gin.Context) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- }
- }
- if err == nil {
- vmsg := ""
- for _, item := range tempval {
- for _, list := range item["resultmaps"].(map[string]interface{}) {
- for _, childrenList := range list.([]interface{}) {
- for k, children := range childrenList.(map[string]interface{}) {
- if k != "children" {
- continue
- }
- for _, v := range children.([]map[string]interface{}) {
- for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
- if k1 == "list" {
- for _, v2 := range v1.([]map[string]interface{}) {
- if v2["vmsg"].(string) != "1" {
- if len(vmsg) == 0 {
- vmsg = v2["vmsg"].(string)
- } else {
- vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- if len(vmsg) > 0 {
- appG.Response(http.StatusOK, e.SUCCESS, vmsg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusInternalServerError, e.ERROR, msg)
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- ss = ""
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- if sql != "" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if err != nil {
- return nil, err
- }
- // fmt.Println(tempValParam)
- return tempValParam.(map[string]interface{}), nil
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- func FpdImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- // importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- tx := restful.Engine.NewSession()
- defer tx.Close()
- languageStatus := GetLanguageStatus()
- if languageStatus == "0" {
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- dataList := make(map[string][]*upFpdetail, 0)
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- // fmt.Println(outentry, entry, "aaaaaaaaaaa")
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- errExist := false
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- errExist = true
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- fmt.Println(outentry["栏舍名称"])
- if !errExist {
- dataexcel := make(map[string]interface{}, 0)
- if _, ok := outentry["栏舍名称"]; ok {
- dataexcel["barname"] = outentry["栏舍名称"]
- }
- if _, ok := outentry["实际牛头数"]; ok {
- dataexcel["ccount"] = outentry["实际牛头数"]
- }
- if _, ok := outentry["系数(%)"]; ok {
- dataexcel["ratio"] = outentry["系数(%)"]
- }
- if _, ok := outentry["配方模板"]; ok {
- dataexcel["ftname"] = outentry["配方模板"]
- }
- if _, ok := outentry["补料配方"]; ok {
- dataexcel["ptsfname"] = outentry["补料配方"]
- }
- if _, ok := outentry["第一班比例(%)"]; ok {
- dataexcel["1"] = outentry["第一班比例(%)"]
- if fmt.Sprintf("%v", dataexcel["1"]) == "" {
- dataexcel["1"] = 0
- }
- } else {
- dataexcel["1"] = 0
- }
- if _, ok := outentry["第二班比例(%)"]; ok {
- dataexcel["2"] = outentry["第二班比例(%)"]
- if fmt.Sprintf("%v", dataexcel["2"]) == "" {
- dataexcel["2"] = 0
- }
- } else {
- dataexcel["2"] = 0
- }
- if _, ok := outentry["第三班比例(%)"]; ok {
- dataexcel["3"] = outentry["第三班比例(%)"]
- if fmt.Sprintf("%v", dataexcel["3"]) == "" {
- dataexcel["3"] = 0
- }
- } else {
- dataexcel["3"] = 0
- }
- if _, ok := outentry["第四班比例(%)"]; ok {
- dataexcel["4"] = outentry["第四班比例(%)"]
- if fmt.Sprintf("%v", dataexcel["4"]) == "" {
- dataexcel["4"] = 0
- }
- } else {
- dataexcel["4"] = 0
- }
- if _, ok := outentry["第五班比例(%)"]; ok {
- dataexcel["5"] = outentry["第五班比例(%)"]
- if fmt.Sprintf("%v", dataexcel["5"]) == "" {
- dataexcel["5"] = 0
- }
- } else {
- dataexcel["5"] = 0
- }
- if _, ok := outentry["第六班比例(%)"]; ok {
- dataexcel["6"] = outentry["第六班比例(%)"]
- if fmt.Sprintf("%v", dataexcel["6"]) == "" {
- dataexcel["6"] = 0
- }
- } else {
- dataexcel["6"] = 0
- }
- dataWeight := new(models.FpdetailEdit)
- // dataWeightMap := make(map[string]interface{}, 0)
- if _, ok := outentry["第一班重量"]; ok {
- // dataWeightMap["weight1"] = outentry["第一班重量"]
- dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
- }
- if _, ok := outentry["第二班重量"]; ok {
- // dataWeightMap["weight2"] = outentry["第二班重量"]
- dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
- }
- if _, ok := outentry["第三班重量"]; ok {
- // dataWeightMap["weight3"] = outentry["第三班重量"]
- dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
- }
- if _, ok := outentry["第四班重量"]; ok {
- // dataWeightMap["weight4"] = outentry["第四班重量"]
- dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
- }
- if _, ok := outentry["第五班重量"]; ok {
- // dataWeightMap["weight5"] = outentry["第五班重量"]
- dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
- }
- if _, ok := outentry["第六班重量"]; ok {
- // dataWeightMap["weight6"] = outentry["第六班重量"]
- dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
- }
- // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
- // dataWeightByte, _ := json.Marshal(dataWeightMap)
- // err = json1.Unmarshal(dataWeightByte, &dataWeight)
- // fmt.Println(err)
- if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
- dataWeight.Weight1 = 0
- dataWeight.Weight2 = 0
- dataWeight.Weight3 = 0
- dataWeight.Weight4 = 0
- dataWeight.Weight5 = 0
- dataWeight.Weight6 = 0
- }
- weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
- if weight > 0 {
- existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !existbar {
- continue
- }
- _, err = tx.SQL(` update feedp fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` update fpdetail fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
- return
- }
- if !existft {
- continue
- }
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- // upFeedpSql += `,ftweight = ? `
- // feedpargs = append(feedpargs, weight)
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
- // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
- // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
- // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
- // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
- // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
- upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- // fmt.Println(dataexcel["barname"])
- dataList[dataexcel["barname"].(string)] = upFpdetailList
- } else {
- existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !existbar {
- continue
- }
- _, err = tx.SQL(` update feedp fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` update fpdetail fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
- return
- }
- if !existft {
- continue
- }
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- // fmt.Println(dataexcel["barname"])
- dataList[dataexcel["barname"].(string)] = upFpdetailList
- }
- // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- for barname, v := range dataList {
- // for _, v1 := range v {
- // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
- // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
- // if count == 1 {
- // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
- // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // }
- // }
- updateFpdetailByBar(pastureid, barname, v)
- }
- } else {
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- dataList := make(map[string][]*upFpdetail, 0)
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- // fmt.Println(outentry, entry, "aaaaaaaaaaa")
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[v]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = v
- break
- }
- outentry[v] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " format error"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[v]; !ok || d == "" {
- a = v
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[v]
- if !ok || d == "" {
- outentry[v] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = v
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " Numerical type and cannot be negative"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- errExist := false
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- errExist = true
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- if !errExist {
- dataexcel := make(map[string]interface{}, 0)
- if _, ok := outentry["Pen Name"]; ok {
- dataexcel["barname"] = outentry["Pen Name"]
- }
- if _, ok := outentry["Actual Cattle Number"]; ok {
- dataexcel["ccount"] = outentry["Actual Cattle Number"]
- }
- if _, ok := outentry["Coefficient(%)"]; ok {
- dataexcel["ratio"] = outentry["Coefficient(%)"]
- }
- if _, ok := outentry["Formula Template"]; ok {
- dataexcel["ftname"] = outentry["Formula Template"]
- }
- if _, ok := outentry["Supplement Formula"]; ok {
- dataexcel["ptsfname"] = outentry["Supplement Formula"]
- }
- if _, ok := outentry["First Shift Ratio(%)"]; ok {
- dataexcel["1"] = outentry["First Shift Ratio(%)"]
- }
- if _, ok := outentry["Second Shift Ratio(%)"]; ok {
- dataexcel["2"] = outentry["Second Shift Ratio(%)"]
- }
- if _, ok := outentry["Third Shift Ratio(%)"]; ok {
- dataexcel["3"] = outentry["Third Shift Ratio(%)"]
- }
- if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
- dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
- }
- if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
- dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
- }
- if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
- dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
- }
- existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !existbar {
- continue
- }
- _, err = tx.SQL(` update feedp fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` update fpdetail fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
- return
- }
- if !existft {
- continue
- }
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- // fmt.Println(dataexcel["barname"])
- dataList[dataexcel["barname"].(string)] = upFpdetailList
- // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- for barname, v := range dataList {
- _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
- and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- updateFpdetailByBar(pastureid, barname, v)
- }
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- type upFpdetail struct {
- Old float64
- New float64
- Times int64
- Ptid int64
- Fweight float64
- Id int64
- // Ptsid string
- }
- func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- 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 `,
- pastureid, barname).Query().List()
- if err != nil {
- logs.Error(err)
- }
- for _, fpd := range fpdList {
- lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
- where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
- pastureid, fpd["id"], fpd["times"]).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- weight := lweight - fpdweight
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
- WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- weight = 0
- break
- }
- }
- }
- }
- }
- for _, list := range dataList {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Old
- ftmap["new"] = list.New
- ftmap["times"] = list.Times
- ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
- ftmap["ptsid"] = ""
- // fmt.Println(ftmap)
- // 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 ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
- // UNION
- fpdDataList, err := tx.SQL(`
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
- // fttype := -1
- // if fpd["fttype"].(string) == "1" {
- fttype := 1
- // }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
- t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
- // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
- // barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:1 id:4828050527277810688 isfill:0 pastureid:1705635208 ptid:83 ptsid:-1 times:1 tratio:48.000 weight:32.0
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
- // continue
- // }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- }
- if w == 0 {
- break
- }
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- return err
- }
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- for _, newLpplandtl1 := range newLpplandtl1List {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- for _, newFpd := range newFpdDataList {
- _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- for _, newFeedp := range newFeedpList {
- _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- return nil
- }
- func DeleteFTdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- ftid := parammaps.Get("ftid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if parammaps.Get("type").ValueStr() == "1" {
- _, err := tx.SQL(`UPDATE feedp fp
- set
- fp.ftweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // UPDATE fpdetail SET ptuse=0 ,weight = 0
- _, err = tx.SQL(`
- UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100,
- ptuse= 0
- WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(`UPDATE feedp fp
- SET
- fp.supplyweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0) + ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- _, err = tx.SQL(`
- UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100,
- ptsrate = 0
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func DeleteSpillageAll(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- barid := parammaps.Get("barid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- now := time.Now()
- for _, item := range lpplandtl1List {
- go func(item map[string]interface{}) {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- item["pastureid"], item["lppid"], item["barid"],
- item["barname"], item["fpdid"], item["fttype"],
- item["lweight"], item["sort"], item["tmrid"],
- item["tmrname"], item["background"], item["cowcount"],
- item["ccountradio"], item["lweighthis"], now).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }(item)
- }
- tx.Begin()
- _, 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()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetTMRListEnableTypeAll(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`SELECT
- eqcode,
- tname,
- datacaptureno,
- trim(tclassid) tclassid,
- concat(tname,' / ',eqcode) tmrmix,
- d.label tclassname,
- maxstirfeed,
- remark,
- tmr.enable,
- TRIM(tmr.id) id,
- TRIM(tmr.pastureid)pastureid
- FROM
- tmr
- left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
- WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
- ORDER BY id DESC`, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var carNum int64
- for _, sysopt := range sysoptData {
- if sysopt["inforvalue"] == nil {
- carNum = 1
- } else {
- carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
- }
- }
- id := 200
- n := 0
- for i := carNum; i > 0; i-- {
- id++
- n++
- data := make(map[string]interface{}, 0)
- data["eqcode"] = fmt.Sprintf("任意车%d", n)
- data["tname"] = fmt.Sprintf("任意车%d", n)
- data["datacaptureno"] = -2
- data["tclassid"] = -2
- data["tmrmix"] = fmt.Sprintf("任意车%d", n)
- data["tclassname"] = fmt.Sprintf("任意车%d", n)
- data["maxstirfeed"] = 100000
- data["remark"] = fmt.Sprintf("任意车%d", n)
- data["enable"] = 1
- data["id"] = fmt.Sprintf("%d", id)
- data["pastureid"] = pastureid
- // data := make(map[string]interface{}, 0)
- // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
- // data["tname"] = fmt.Sprintf("AnyCar%d", n)
- // data["datacaptureno"] = -2
- // data["tclassid"] = -2
- // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
- // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
- // data["maxstirfeed"] = 100000
- // data["remark"] = fmt.Sprintf("AnyCar%d", n)
- // data["enable"] = 1
- // data["id"] = fmt.Sprintf("%d", id)
- // data["pastureid"] = pastureid
- dataList = append(dataList, data)
- }
- // UNION ALL
- // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- func GetFeedpHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- bar := fsion.Get("barname").ValueStr()
- startDate := fsion.Get("startDate").ValueStr()
- endDate := fsion.Get("endDate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
- DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
- and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
- (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
- and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, feedp := range feedpList {
- // LastftList, err := tx.SQL(` select tname ,id
- // from feedtemplethistory where id = ?
- // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
- DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
- and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var ftname interface{}
- ftnamestatus := 0
- ftname = feedp["ftname"]
- var lastftid int64
- if len(nextfeedpList) > 0 {
- for _, ft := range nextfeedpList {
- if ft["ftname"].(string) != feedp["ftname"].(string) {
- ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
- lastftid = ft["ftid"].(int64)
- ftnamestatus = 1
- break
- }
- }
- }
- for i, fpd := range fpdList {
- if feedp["createdate"].(string) == fpd["createdate"].(string) {
- fpd["weightstatus"] = 0
- fpd["tratiostatus"] = 0
- fpd["ftnamestatus"] = ftnamestatus
- for k, fpd2 := range fpdList {
- if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
- if fpd["weight"].(string) != fpd2["weight"].(string) {
- fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
- fpd["weightstatus"] = 1
- }
- if fpd["tratio"].(string) != fpd2["tratio"].(string) {
- fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
- fpd["tratiostatus"] = 1
- }
- break
- }
- }
- fpd["barid"] = feedp["barid"]
- fpd["barname"] = feedp["barname"]
- fpd["ccount"] = feedp["ccount"]
- fpd["ratio"] = feedp["ratio"]
- fpd["ccountratio"] = feedp["ccountratio"]
- fpd["ftid"] = feedp["ftid"]
- fpd["ftname"] = ftname
- fpd["ccountstatus"] = 0
- fpd["ccountratiostatus"] = 0
- fpd["ratiostatus"] = 0
- fpd["ftnamestatus"] = 0
- fpd["lastftid"] = lastftid
- for _, next := range nextfeedpList {
- if next["ccount"].(int64) != fpd["ccount"].(int64) {
- fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
- fpd["ccountstatus"] = 1
- }
- if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
- fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
- fpd["ccountratiostatus"] = 1
- }
- if next["ratio"].(string) != fpd["ratio"].(string) {
- fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
- fpd["ratiostatus"] = 1
- }
- // if next["ftname"].(string) != fpd["ftname"].(string) {
- // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
- // fpd["ftnamestatus"] = 1
- // }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, fpdList)
- }
- // func GetLpplandtl1History(c *gin.Context) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsion := gofasion.NewFasion(string(dataByte))
- // // parammaps := fsion.Get("parammaps")
- // barid := fsion.Get("barid").ValueStr()
- // startDate := fsion.Get("startDate").ValueStr()
- // endDate := fsion.Get("endDate").ValueStr()
- // tx := restful.Engine.NewSession()
- // defer tx.Close()
- // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
- // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
- // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
- // // if err != nil {
- // // logs.Error(err)
- // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // // return
- // // }
- // // for _, feedp := range feedpList {
- // // fmt.Println(feedp)
- // // for i, fpd := range fpdList {
- // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
- // // for k, fpd2 := range fpdList {
- // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
- // // if fpd["weight"].(string) != fpd2["weight"].(string) {
- // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
- // // }
- // // break
- // // }
- // // }
- // // fpd["barid"] = feedp["barid"]
- // // fpd["barname"] = feedp["barname"]
- // // fpd["ccount"] = feedp["ccount"]
- // // fpd["ratio"] = feedp["ratio"]
- // // fpd["ccountratio"] = feedp["ccountratio"]
- // // fpd["ftid"] = feedp["ftid"]
- // // fpd["ftname"] = feedp["ftname"]
- // // }
- // // }
- // // }
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- // }
- func GetRemind(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // pastureid = "3"
- resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- defer resp.Body.Close()
- buf := bytes.NewBuffer(make([]byte, 0, 512))
- buf.ReadFrom(resp.Body)
- fmt.Println(string(buf.Bytes()))
- respMap := make(map[string]interface{}, 0)
- err = json.Unmarshal(buf.Bytes(), &respMap)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, data := range dataList {
- r := make(map[string]interface{}, 0)
- r["sys_name"] = ""
- r["service_id"] = ""
- r["pasture_id"] = ""
- r["type_name"] = ""
- r["remind_type_id"] = ""
- r["remind_type"] = ""
- r["push_date"] = ""
- r["push_time"] = ""
- r["interval_time"] = ""
- r["push_limit"] = ""
- r["template_id"] = ""
- r["roles_id"] = ""
- r["users_id"] = ""
- r["date_type"] = ""
- r["cycle_type"] = ""
- data["data"] = r
- for _, resp := range respMap["data"].([]interface{}) {
- resp1 := resp.(map[string]interface{})
- if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
- if resp1["push_time"] == nil {
- resp1["push_time"] = ""
- }
- data["data"] = resp1
- break
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- type NoticeMsgtype struct {
- SysName string `json:"sys_name"`
- PastureId int64 `json:"pasture_id"`
- ServiceId int64 `json:"service_id"`
- TypeName string `json:"type_name"`
- RemindType int64 `json:"remind_type"`
- PushDate int64 `json:"push_date"`
- PushTime string `json:"push_time"`
- IntervalTime int64 `json:"interval_time"`
- PushLimit int64 `json:"push_limit"`
- TemplateId string `json:"template_id"`
- UsersId string `json:"users_id"`
- DateType int64 `json:"date_type"`
- CycleType int64 `json:"cycle_type"`
- DelayTime int64 `json:"delay_time"`
- Status int64 `json:"status"`
- }
- func UpdateRemind(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- // user := parammaps.Get("user").ValueStr()
- id := parammaps.Get("id").ValueInt64()
- noticeMsgtype := new(NoticeMsgtype)
- noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
- noticeMsgtype.ServiceId = id
- noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
- noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
- // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
- noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
- noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
- noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
- noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
- noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
- // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
- noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
- // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
- noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
- noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
- noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
- noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
- //TODO
- noticeMsgtype.SysName = "tmrWatch"
- userList := parammaps.Get("user").Array()
- var userstr []string
- for _, user := range userList {
- userstr = append(userstr, user.ValueStr())
- }
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // var jsonStr = []byte(noticeMsgtype
- noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
- fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
- req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println("response Body:", string(body))
- getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- defer getresp.Body.Close()
- buf := bytes.NewBuffer(make([]byte, 0, 512))
- buf.ReadFrom(getresp.Body)
- // fmt.Println(string(buf.Bytes()))
- respMap := make(map[string]interface{}, 0)
- err = json.Unmarshal(buf.Bytes(), &respMap)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, resp := range respMap["data"].([]interface{}) {
- resp1 := resp.(map[string]interface{})
- _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetSpillageallHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- barname := parammaps.Get("barname").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- startdate := parammaps.Get("startDate").ValueStr()
- enddate := parammaps.Get("endDate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
- order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- respMap := make([]map[string]interface{}, 0)
- data := make(map[interface{}]interface{})
- for _, history := range historyList {
- data[history["createdate"]] = history["createdate"]
- }
- createList := []string{}
- for _, v := range data {
- createList = append(createList, v.(string))
- }
- // sort.Sort()
- // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
- sort.Slice(createList, func(i, j int) bool {
- return createList[i] > createList[j]
- })
- for _, v := range createList {
- a := make(map[string]interface{})
- a["createdate"] = data[v]
- // createList = append(createList, v.(string))
- respMap = append(respMap, a)
- }
- number := 0
- dataMap := make([]interface{}, 0)
- for k, resp := range respMap {
- createdate := resp["createdate"].(string)
- var nextcreatedate string
- if len(respMap) > k+1 {
- nextcreatedate = respMap[k+1]["createdate"].(string)
- }
- // dataList := make(map[string][]interface{})
- // list := make(map[string]interface{})
- times := make(map[interface{}]int)
- for _, history := range historyList {
- // List := make(map[interface{}][]interface{})
- i := 0
- if history["createdate"].(string) == createdate {
- times[history["times"]]++
- data := make(map[string]interface{})
- data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
- // exist := false
- if nextcreatedate != "" {
- for _, history1 := range historyList {
- if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
- history1["times"].(int64) == history["times"].(int64) {
- data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
- break
- // exist = true
- }
- }
- }
- // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- i++
- // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
- // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
- // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
- // resp["times"] = history["times"]
- // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- data1 := make(map[string]interface{})
- data1["times"] = history["times"]
- data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- data1["createdate"] = resp["createdate"]
- // fmt.Println(dataList)
- dataMap = append(dataMap, data1)
- }
- if i > number {
- number = i
- }
- // respMap = append(respMap, dataList)
- }
- // for k, data := range dataList {
- // resp[k] = data
- // }
- // resp["data"] = dataList
- }
- // resp := make(map[string]interface{})
- // sort.Strings(createList)
- //
- // for _, create := range createList {
- // for _, r := range respMap {
- // if create == r["createdate"].(string) {
- // resp[create] = r
- // break
- // }
- // }
- // }
- sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
- var trainsList []interface{}
- for i := 0; i < number; i++ {
- trains := make(map[string]interface{})
- trains["label"] = fmt.Sprintf("第%s车", sz[i])
- trains["prop"] = fmt.Sprintf("a%d", i+1)
- trainsList = append(trainsList, trains)
- }
- respdata := make(map[string]interface{})
- respdata["data"] = dataMap
- respdata["trains"] = trainsList
- appG.Response(http.StatusOK, e.SUCCESS, respdata)
- }
- func GetRecipeTemplateRecordHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- ftid := parammaps.Get("ftid").ValueInt64()
- lastftid := parammaps.Get("lastftid").ValueInt64()
- pastureid := parammaps.Get("pastureid").ValueInt64()
- // createdate := parammaps.Get("createdate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- data := make(map[string]interface{})
- feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
- and fthis.pastureId = ?`, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- feedtemplet := make(map[string]interface{})
- for _, f := range feedtempletList {
- feedtemplet = f
- }
- fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- feedtemplet["fit"] = fitList
- data["current"] = feedtemplet
- lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
- and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- lastfeedtemplet := make(map[string]interface{})
- for _, f := range lastfeedtempletList {
- lastfeedtemplet = f
- }
- lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- lastfeedtemplet["fit"] = lastfitList
- data["last"] = lastfeedtemplet
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func GetFeedtempletHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- ftid := parammaps.Get("ftid").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueInt64()
- start := parammaps.Get("startdate").ValueStr()
- end := parammaps.Get("enddate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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 ?
- and id = ? and pastureid = ? order by createdate desc `,
- start, end, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
- ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
- for i, ft := range ftList {
- fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
- ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
- (select empname from user where id = fit.userId) empname,
-
- 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
- where fit.fitid = ?
- and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
- and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- ft["createdate"] = ft["createdate1"]
- // data["tname"] = ft["tname"]
- // data["tcode"] = ft["tcode"]
- // data["tcolor"] = ft["tcolor"]
- // data["fttype"] = ft["fttype"]
- // data["ccname"] = ft["ccname"]
- // data["source"] = ft["source"]
- // data["version"] = ft["version"]
- // data["remark"] = ft["remark"]
- for n, ft2 := range ftList {
- if i < n {
- if ft["tname"].(string) != ft2["tname"].(string) {
- ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
- }
- if _, ok := ft["tcode"]; ok {
- if _, ok := ft2["tcode"]; ok {
- if ft["tcode"].(string) != ft2["tcode"].(string) {
- ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
- }
- }
- }
- if _, ok := ft["tcolor"]; ok {
- if _, ok := ft2["tcolor"]; ok {
- if ft["tcolor"].(string) != ft2["tcolor"].(string) {
- ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
- }
- }
- }
- if _, ok := ft["fttype"]; ok {
- if _, ok := ft2["fttype"]; ok {
- if ft["fttype"].(string) != ft2["fttype"].(string) {
- ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
- }
- }
- }
- if _, ok := ft["ccname"]; ok {
- if _, ok := ft2["ccname"]; ok {
- if ft["ccname"].(string) != ft2["ccname"].(string) {
- ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
- }
- }
- }
- if _, ok := ft["source"]; ok {
- if _, ok := ft2["source"]; ok {
- if ft["source"].(string) != ft2["source"].(string) {
- ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
- }
- }
- }
- if _, ok := ft["version"]; ok {
- if _, ok := ft2["version"]; ok {
- if ft["version"].(int64) != ft2["version"].(int64) {
- ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
- }
- }
- }
- if _, ok := ft["remark"]; ok {
- if _, ok := ft2["remark"]; ok {
- if ft["remark"].(string) != ft2["remark"].(string) {
- ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
- }
- }
- }
- break
- }
- }
- dataList := make([]map[string]interface{}, 0)
- if len(fithisList) > 0 {
- for _, fit := range fithisList {
- data := make(map[string]interface{})
- data["feedgroup"] = fit["feedgroup"]
- data["fname"] = fit["fname"]
- data["empname"] = fit["empname"]
- if fit["Eweight"] != nil {
- if fit["Eweight"].(string) != fit["weight"].(string) {
- data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
- } else {
- data["fweight"] = fit["Eweight"]
- }
- data["fweightstatus"] = 1
- } else {
- data["fweight"] = fit["weight"]
- data["fweightstatus"] = 0
- }
- data["autosecond"] = fit["autosecond"]
- // data["tname"] = ft["tname"]
- // data["tcode"] = ft["tcode"]
- // data["tcolor"] = ft["tcolor"]
- // data["fttype"] = ft["fttype"]
- // data["ccname"] = ft["ccname"]
- // data["source"] = ft["source"]
- // data["version"] = ft["version"]
- // data["remark"] = ft["remark"]
- // data["createdate"] = ft["createdate1"]
- // ft["fit"] = data
- dataList = append(dataList, data)
- }
- } else {
- for _, fit := range ftdetailList {
- data := make(map[string]interface{})
- data["feedgroup"] = fit["feedgroup"]
- data["fname"] = fit["fname"]
- // if fit["Eweight"] != nil {
- // data["weight"] = fit["Eweight"]
- // } else {
- data["fweight"] = fit["fweight"]
- // }
- data["autosecond"] = fit["autosecond"]
- // ft["fit"] = data
- dataList = append(dataList, data)
- }
- }
- ft["fit"] = dataList
- }
- appG.Response(http.StatusOK, e.SUCCESS, ftList)
- }
- func UpdateMaterialTMR(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- tmrid := parammaps.Get("tmrid").ValueStr()
- tmrtype := parammaps.Get("tmrtype").ValueStr()
- lppid := parammaps.Get("lppid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
- // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
- status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- if tmrid != "1000" {
- tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var maxstirfeed float64
- for _, tmr := range tmrList {
- maxstirfeed += float64(tmr["maxstirfeed"].(int64))
- }
- if status == 0 {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- if lweight > 0 {
- lweight1 := lweight / float64(len(lpplandtl1List))
- number := 0
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- number++
- }
- }
- lweight := lweight / float64((len(lpplandtl1List) - number))
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- continue
- }
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- for _, item := range lpplandtl1List {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else if status == 1 {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- for _, item := range lpplandtl1List {
- if lweight > 0 {
- // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if fl >= lweight {
- item["lweight"] = fl - lweight
- lweight = 0
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- } else {
- lweight = lweight - fl
- _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- if status == 2 {
- lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func UpdateMaterialTMRDate(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- tmrid := parammaps.Get("tmrid").ValueStr()
- tmrtype := parammaps.Get("tmrtype").ValueStr()
- lppid := parammaps.Get("lppid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- date := parammaps.Get("date").ValueStr()
- // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
- status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- if tmrid != "1000" {
- tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var maxstirfeed float64
- for _, tmr := range tmrList {
- maxstirfeed += float64(tmr["maxstirfeed"].(int64))
- }
- if status == 0 {
- 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- if lweight > 0 {
- lweight1 := lweight / float64(len(lpplandtl1List))
- number := 0
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- number++
- }
- }
- lweight := lweight / float64((len(lpplandtl1List) - number))
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- continue
- }
- if tmrtype == "1" {
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- for _, item := range lpplandtl1List {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else if status == 1 {
- 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- for _, item := range lpplandtl1List {
- if lweight > 0 {
- // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if fl >= lweight {
- item["lweight"] = fl - lweight
- lweight = 0
- if tmrtype == "1" {
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- } else {
- lweight = lweight - fl
- _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- if status == 2 {
- lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func Decimal(value float64) float64 {
- value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
- return value
- }
- func UpdateDailyData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- pid := parammaps.Get("pid").ValueDefaultStr("0")
- weight := parammaps.Get("weight").ValueDefaultFloat64(0)
- sort := parammaps.Get("sort").ValueDefaultStr("0")
- location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
- date := parammaps.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- count, err := tx.SQL(`select count(1) from downloadedplan where pid in(select pid from downloadedplan where id= ? ) and havebutton = 1 and mydate = ?`, pid, date).Count()
- if err != nil {
- logs.Error("UpdateDailyData-error-0:", err)
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
- return
- }
- if count > 0 {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
- return
- }
- tx.Begin()
- if location == 0 {
- fid := parammaps.Get("fid").ValueStr()
- downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actualWeight := weight - num
- _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-2:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-3:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-4:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-5:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
- lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- // actual := actualWeight / float64(len(downloadedplanList))
- for _, item := range downloadedplanList {
- itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actual := itemLweight / lweight * actualWeight
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- } else {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
- // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- // if err != nil {
- // fmt.Println("Error:", err)
- // return
- // }
- for _, item := range downloadedplanList {
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
- item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- }
- } else {
- fbarid := parammaps.Get("fbarid").ValueStr()
- downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-10:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actualWeight := weight - num
- _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-11:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
- downloadedplan[0]["lweight"], actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-12:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
- where pid = ? `, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-13:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-14:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
- lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- for _, item := range downloadedplanList {
- itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actual := itemLweight / lweight * actualWeight
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- } else {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
- for _, item := range downloadedplanList {
- // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- // if err != nil {
- // fmt.Println("Error:", err)
- // return
- // }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
- item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error("UpdateDailyData-error-20:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetFormulaStatistics(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- startTime := parammaps.Get("startTime").ValueStr()
- endTime := parammaps.Get("endTime").ValueStr()
- pastureId := parammaps.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
- if err != nil {
- logs.Error("GetFormulaStatistics-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
- return
- }
- var feedtemplet, dateList []string
- for _, f := range feedtempletList {
- feedtemplet = append(feedtemplet, f["tname"].(string))
- }
- layout := "2006-01-02"
- // s := "2023-05-01"
- // e := "2023-05-23"
- start, err := time.Parse(layout, startTime)
- if err != nil {
- fmt.Println(err)
- return
- }
- end, err := time.Parse(layout, endTime)
- if err != nil {
- fmt.Println(err)
- return
- }
- end = end.AddDate(0, 0, 1)
- for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
- dateList = append(dateList, d.Format("2006-01-02"))
- }
- downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
- join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate join feedtemplet ftd on ftd.id = ft.id where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
- group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
- if err != nil {
- logs.Error("GetFormulaStatistics-error-2:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
- return
- }
- var data2 [][]interface{}
- for _, f := range feedtemplet {
- var data1 []interface{}
- for _, date := range dateList {
- exist := false
- for _, item := range downloadedplanList {
- if date == item["mydate"].(string) && f == item["tname"].(string) {
- data1 = append(data1, item["total"])
- exist = true
- break
- }
- }
- if !exist {
- data1 = append(data1, 0)
- }
- }
- data2 = append(data2, data1)
- }
- //前端让加的
- feedtemplet = append(feedtemplet, "")
- {
- var data1 []interface{}
- for _, f := range dateList {
- // f = f + "\n"
- fmt.Println(f)
- data1 = append(data1, 0)
- }
- data2 = append(data2, data1)
- }
- resp := make(map[string]interface{}, 0)
- resp["xdata"] = dateList
- resp["data1"] = feedtemplet
- resp["data2"] = data2
- appG.Response(http.StatusOK, e.SUCCESS, resp)
- }
- func GetPlanData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
- for _, item := range arr {
- trgaddressList := []string{}
- if _, ok := item["trgaddress"]; ok {
- trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
- for _, str := range trgaddressList1 {
- if str != "" {
- trgaddressList = append(trgaddressList, str)
- }
- }
- }
- item["trgaddressList"] = trgaddressList
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- // var wg sync.WaitGroup
- // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- // wg.Add(1)
- // go func(value map[string]interface{}) {
- // defer wg.Done()
- // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
- // }(value)
- // }
- // wg.Wait()
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostPlanData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBData err: ", string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- // paramslist := strings.Split(p, ",")
- // if len(paramslist) > 0 && p != "" {
- // for _, value := range paramslist {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- // }
- // _, err = tx.SQL(sql, s_params...).Execute()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- s_params = make([]interface{}, 0)
- paramslist := strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func CheckFeedTrgaddress(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- fclassid := fsion.Get("fclassid").ValueStr()
- feedId := fsion.Get("feedId").ValueStr()
- backup1 := fsion.Get("backup1").ValueStr()
- backup1List := strings.Split(backup1, ",")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- // if backup1 != "" {
- feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
- for _, feed := range feedList {
- if feed["backup1"] == "" {
- continue
- }
- feedbackupList := strings.Split(feed["backup1"], ",")
- for _, feedbackup := range feedbackupList {
- for _, backup := range backup1List {
- if feedbackup == backup {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
- return
- }
- }
- }
- }
- // }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func ThiGetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- if sqlnamestr == "getHomepageStr" {
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- var montimeList []float64
- var montime float64
- var wg sync.WaitGroup
- now := time.Now()
- for i := 0; i < 30; i++ {
- wg.Add(1)
- nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
- go func(nowstr string) {
- defer wg.Done()
- sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
- slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
- m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
- montimeList = append(montimeList, m)
- }(nowstr)
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- wg.Wait()
- for _, m := range montimeList {
- montime += m
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- if sqlnamestr == "getFeedTrgaddressList" {
- for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
- trgaddressList := []string{}
- for _, str := range trgaddressList1 {
- if str != "" {
- trgaddressList = append(trgaddressList, str)
- }
- }
- item["trgaddressList"] = trgaddressList
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // func ToggleCcount(c *gin.Context) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsion := gofasion.NewFasion(string(dataByte))
- // // 0 实际 1 软件
- // status := fsion.Get("status").ValueDefaultInt64(0)
- // pastureId := fsion.Get("pastureId").ValueStr()
- // tx := restful.Engine.NewSession()
- // err := tx.Begin()
- // defer func() {
- // switch {
- // case err != nil:
- // logging.Error("tx.Begin 事务启动失败__error:", err)
- // if tx != nil {
- // tx.Rollback()
- // }
- // default:
- // if tx != nil {
- // err = tx.Commit()
- // }
- // }
- // if tx != nil {
- // tx.Close()
- // }
- // }()
- // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // for _, bar := range barList {
- // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist {
- // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // }
- // if status == 0 {
- // tx.Exec(`update feedp set ccount = actualcount `)
- // }else{
- // tx.Exec(`update feedp set ccount = softccount `)
- // }
- // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // for _, feedpData :=range feedpList{
- // var feedpargs []interface{}
- // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
- // if _, ok := feedpData["ftname"]; ok {
- // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
- // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
- // } else {
- // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- // }
- // if _, ok := feedpData["ptsfname"]; ok {
- // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
- // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
- // } else {
- // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- // }
- // upFeedpSql += " where barname = ? and pastureid = ? "
- // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
- // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist1 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist2 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist3 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist4 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist5 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist6 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- // and pastureid = ? and times = ?`
- // var fpdargs1 []interface{}
- // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs2 []interface{}
- // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs3 []interface{}
- // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs4 []interface{}
- // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs5 []interface{}
- // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs6 []interface{}
- // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- // 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()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- // upFpdetailList := make([]*upFpdetail, 0)
- // for _, newfpd := range newList {
- // for _, oldfpd := range oldFpdList {
- // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- // var oldweight, newweight float64
- // if oldfpd["weight"] != nil {
- // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- // }
- // if newfpd["weight"] != nil {
- // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- // }
- // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- // upFpdetailList = append(upFpdetailList, &upFpdetail{
- // Old: oldweight,
- // New: newweight,
- // Times: newfpd["times"].(int64),
- // Ptid: newfpd["ptid"].(int64),
- // Fweight: fweight,
- // Id: oldfpd["id"].(int64),
- // })
- // break
- // }
- // }
- // }
- // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
- // }
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- // }
- func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
- feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
- if err != nil {
- return err
- }
- for _, item := range feedpList {
- // if item["ftid"].(string) != data["ftid"].(string) {
- _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
- if err != nil {
- return err
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
- if err != nil {
- return err
- }
- // }
- }
- return nil
- }
- func PostPlanDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBDatas err: ", string(dataByte))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- pastureId := fsions.Get("pastureid").ValueStr()
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
- for _, parammaps := range fsions.Get("arrList").Array() {
- fmt.Println(parammaps.Json())
- if parammaps.Json() == "null" {
- continue
- }
- // if !fsion.HasKey("arrList") {
- // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- // return
- // continue
- // }
- // parammaps := fsion.Get("arrList")
- s_params := make([]interface{}, 0)
- // paramslist := strings.Split(p, ",")
- // if len(paramslist) > 0 && p != "" {
- // for _, value := range paramslist {
- // if value == "pastureid" {
- // s_params = append(s_params, pastureId)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- // }
- // }
- // _, err = tx.SQL(sql, s_params...).Execute()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- s_params = make([]interface{}, 0)
- paramslist := strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func FpdBatchEdit(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- barList := fsions.Get("barList").Array()
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- for _, barFsions := range barList {
- dataexcel := make(map[string]interface{}, 0)
- dataexcel["barname"] = barFsions.Get("barname").ValueStr()
- dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
- dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
- dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
- dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
- if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
- continue
- }
- // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
- // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- dataexcel["1"] = barFsions.Get("times1").ValueStr()
- dataexcel["2"] = barFsions.Get("times2").ValueStr()
- dataexcel["3"] = barFsions.Get("times3").ValueStr()
- dataexcel["4"] = barFsions.Get("times4").ValueStr()
- dataexcel["5"] = barFsions.Get("times5").ValueStr()
- dataexcel["6"] = barFsions.Get("times6").ValueStr()
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdBarSync(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- // gm.UdBarSync(pastureid, pastureinfo.Werks)
- jpud.UdBarSync(pastureid, pastureinfo.Werks)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdFeedSync(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- // gm.UdFeedSync(pastureid, pastureinfo.Werks)
- jpud.UdFeedSync(pastureid, pastureinfo.Werks)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdFeedtempletPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
- jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdUtirPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
- jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdBarFeedRemainPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
- jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdMaterialIssuePush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
- jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- //搅拌
- func YmyUtirPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- //撒料
- func YmyMaterialIssuePush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func YmyFeedtempletPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- //饲料
- func YmySyncFeed(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- // date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- ymy.YmySyncFeed(pastureid)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- // 栏舍
- func YmySyncBar(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- // date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- ymy.YmySyncBar(pastureinfo.Werks, pastureid)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func DelFeedTemplet(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- ftId := fsions.Get("ftId").ValueStr()
- // userId := fsions.Get("userId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- return
- }
- /*
- _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- return
- }
- */
- _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
- return
- }
- _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
- return
- }
- count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
- if count > 0 {
- _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
- return
- }
- }
- _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
- return
- }
- // var barIdStr []string
- // for _, bar := range barIdList {
- // barIdStr = append(barIdStr, bar["barid"])
- // }
- // if len(barIdStr) > 0 {
- // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- // now := time.Now()
- // for _, newFpd := range newFpdDataList {
- // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
- // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // }
- // for _, newFeedp := range newFeedpList {
- // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
- // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // }
- // }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
- data := fasion["parammaps"].(map[string]interface{})
- plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
- fmt.Println(err)
- plancount1, err := tx.SQL(`SELECT
- count( 1 )
- FROM
- (
- SELECT
- d.id
- FROM
- downloadedplan d
- JOIN downloadplandtl1 d1 ON d1.pid = d.id
- JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
- JOIN downloadplandtl2 d2 ON d2.pid = d.id
- WHERE
- d.mydate = ?
- AND d.havebutton = 0
- AND lpplantype IN ( 0, 1, 2 )
- AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
- ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 and dd2.fname = d2.fname )
- GROUP BY
- d.id
- ) d
-
- `,
- data["startTime"]).Count()
- fmt.Println(err)
- if plancount != plancount1 && number < 10 {
- number++
- ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
- checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
- }
- }
- func EditPlanSort(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- planIdStr := fsions.Get("planId").ValueStr()
- mydate := fsions.Get("mydate").ValueStr()
- sort := fsions.Get("sort").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- type downloadedplan struct {
- Id int64 `xorm:"id"`
- Sort int `xorm:"sort"`
- Pid int64 `xorm:"pid"`
- }
- planInfo := new(downloadedplan)
- err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- sort1, _ := strconv.Atoi(sort)
- if sort1 == planInfo.Sort {
- appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
- tx.Rollback()
- return
- }
- count1, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and mydate = ? `, sort, mydate, mydate).Count()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- if count1 == 0 {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
- return
- }
- count, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and havebutton = 1 and mydate = ? `, sort, mydate, mydate).Count()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- if count > 0 {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
- return
- }
- if planInfo.Sort > sort1 {
- minSortList, err := tx.SQL(`select min(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- var minSort, pidCount int
- for _, sort := range minSortList {
- minSort, _ = strconv.Atoi(sort["sort"])
- }
- planList := make([]*downloadedplan, 0)
- err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort >= ? order by sort`, mydate, minSort).Find(&planList)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- planPid := planInfo.Pid
- planList1 := make([]*downloadedplan, 0)
- planList2 := make([]*downloadedplan, 0)
- for _, plan := range planList {
- if plan.Pid == planPid {
- pidCount++
- planList1 = append(planList1, plan)
- } else {
- planList2 = append(planList2, plan)
- }
- }
- planList1 = append(planList1, planList2...)
- for i, plan := range planList1 {
- _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- } else {
- maxSortList, err := tx.SQL(`select max(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- var maxSort int
- for _, sort := range maxSortList {
- maxSort, _ = strconv.Atoi(sort["sort"])
- }
- planList := make([]*downloadedplan, 0)
- err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort <= ? order by sort`, mydate, maxSort).Find(&planList)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- planPid := planInfo.Pid
- planList1 := make([]*downloadedplan, 0)
- planList2 := make([]*downloadedplan, 0)
- for _, plan := range planList {
- if plan.Pid == planPid {
- // pidCount++
- planList1 = append(planList1, plan)
- } else {
- planList2 = append(planList2, plan)
- }
- }
- planList2 = append(planList2, planList1...)
- for i, plan := range planList2 {
- _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func EditDownloadedplanArtificial(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- planIdStr := fsions.Get("planId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- planIdList := strings.Split(planIdStr, ",")
- for _, planId := range planIdList {
- _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- type PlanRFID struct {
- RFID string `json:"RFID"`
- Lweight string `json:"lweight"`
- Gear string `json:"gear"`
- Speed string `json:"speed"`
- }
- func GetPlanRFID(c *gin.Context) {
- appG := app.Gin{C: c}
- RFIDStr := c.Query("RFID")
- planRFIDList := make([]*PlanRFID, 0)
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1411.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1322.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1904.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1870.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "2041.1",
- Gear: "1",
- Speed: "10",
- })
- appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
- }
- type tmrEquipmentMuster struct {
- A string
- N string
- }
- func GetTmrEquipmentMuster(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Query("id")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
- for _, data := range dataList {
- json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
- for _, g := range tmrEquipmentMusterList {
- a, _ := strconv.ParseFloat(g.A, 64)
- n, _ := strconv.ParseFloat(g.N, 64)
- a1, n1 := ddmmtoddd(a, n)
- g.A = fmt.Sprintf("%f", n1)
- g.N = fmt.Sprintf("%f", a1)
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
- }
- func ddmmtoddd(lng, lat float64) (float64, float64) {
- lngDegree := fmt.Sprintf("%f", lng/100)
- lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
- lngDegreeInt := int(lngDegreefloat * 1000000)
- dd := lngDegreeInt / 100 * 100 / 60
- fmt.Println(dd)
- lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
- latDegree := fmt.Sprintf("%f", lat/100)
- // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
- latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
- latDegreeInt := int(latDegreefloat * 1000000)
- latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
- a, _ := strconv.ParseFloat(lngStr, 64)
- b, _ := strconv.ParseFloat(latStr, 64)
- return coordtransform.WGS84toGCJ02(b, a)
- }
- func EditDownloadedplanExecWeight(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pid := fsions.Get("pid").ValueStr()
- sort := fsions.Get("sort").ValueStr()
- weight := fsions.Get("weight").ValueStr()
- userId := fsions.Get("userId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
- values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
- pid, sort, pid, sort, weight, userId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- _, err = tx.Exec(` update downloadplandtl1 set actualweightminus = lweight / (select sum(lweight) from downloadplandtl1 where pid = ? and sort = ? ) * ? where pid = ? and sort = ? `, pid, sort, weight, pid, sort)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func EditDownloadplandtl2Weight(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pid := fsions.Get("pid").ValueStr()
- sort := fsions.Get("sort").ValueStr()
- weight := fsions.Get("weight").ValueStr()
- userId := fsions.Get("userId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
- values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
- pid, sort, pid, sort, weight, userId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func FtdetailSurplus(fasion *gofasion.Fasion) error {
- params := fasion.Get("parammaps")
- surplus := params.Get("surplus").ValueStr()
- surplusId := params.Get("surplusId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
- if surplusId != "0" {
- dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
- if err != nil {
- log.Println("PostDataByName-error-1: ", err)
- return errors.New("配方修改失败!")
- }
- type ftdetail struct {
- Id string
- Fname string
- Sort int64
- }
- ftList := make([]*ftdetail, 0)
- for _, data := range dataList {
- ft := new(ftdetail)
- ft.Fname = data["fname"]
- ft.Id = data["id"]
- sort, err := strconv.ParseInt(data["sort"], 10, 64)
- if err != nil {
- log.Println("PostDataByName-error-2: ", err)
- return err
- }
- ft.Sort = sort
- ftList = append(ftList, ft)
- }
- if surplus == "日粮" {
- for _, ft := range ftList {
- tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
- }
- _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
- values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
- params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
- fmt.Println(err)
- } else {
- var sort int64
- for _, ft := range ftList {
- if ft.Fname == surplus {
- sort = ft.Sort
- break
- }
- }
- if sort == 0 {
- for _, ft := range ftList {
- ft.Sort = ft.Sort + 1
- }
- } else {
- for _, ft := range ftList {
- if ft.Sort >= sort {
- ft.Sort = ft.Sort + 1
- }
- }
- }
- for _, ft := range ftList {
- tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
- }
- _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
- values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
- params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
- if err != nil {
- log.Println("PostDataByName-error-1: ", err)
- fmt.Println(err)
- return errors.New("配方修改失败!")
- }
- }
- }
- return nil
- }
- func FeedSurplus(fasion *gofasion.Fasion) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- params := fasion.Get("parammaps")
- feedId := params.Get("id").ValueStr()
- tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
- tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
- }
- func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
- // params := fasion.Get("parammaps")
- // surplus := params.Get("surplus").ValueStr()
- // surplusId := params.Get("surplusId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
- if surplusId != "0" {
- dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
- if err != nil {
- log.Println("PostDataByName-error-1: ", err)
- return errors.New("配方修改失败!")
- }
- type ftdetail struct {
- Id string
- Fname string
- Sort int64
- }
- ftList := make([]*ftdetail, 0)
- for _, data := range dataList {
- ft := new(ftdetail)
- ft.Fname = data["fname"]
- ft.Id = data["id"]
- sort, err := strconv.ParseInt(data["sort"], 10, 64)
- if err != nil {
- log.Println("PostDataByName-error-2: ", err)
- return err
- }
- ft.Sort = sort
- ftList = append(ftList, ft)
- }
- if surplus == "日粮" {
- for _, ft := range ftList {
- tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
- }
- _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
- values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
- pastureId, id, surplusId, surplusId, surplusId)
- fmt.Println(err)
- } else {
- var sort int64
- for _, ft := range ftList {
- if ft.Fname == surplus {
- sort = ft.Sort
- break
- }
- }
- if sort == 0 {
- for _, ft := range ftList {
- ft.Sort = ft.Sort + 1
- }
- } else {
- for _, ft := range ftList {
- if ft.Sort >= sort {
- ft.Sort = ft.Sort + 1
- }
- }
- }
- for _, ft := range ftList {
- tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
- }
- _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
- values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
- id, surplusId, surplusId, sort, surplusId, pastureId)
- if err != nil {
- log.Println("PostDataByName-error-1: ", err)
- fmt.Println(err)
- return errors.New("配方修改失败!")
- }
- }
- }
- return nil
- }
- func GetLanguageStatus() string {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
- if err != nil {
- log.Println(err)
- return "0"
- }
- return dataList[0]["inforvalue"]
- }
- func EditLanguage(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- language := fsions.Get("language").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- if language == "0" {
- _, err := tx.Exec(`delete from dictlist `)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
- select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- } else {
- _, err := tx.Exec(`delete from dictlist `)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
- select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,ifnull(fpd.weight,0)weight ,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- for _, dataexcel := range barList {
- // dataexcel := make(map[string]interface{}, 0)
- // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
- // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
- // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
- // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
- // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
- // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
- // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // return
- // }
- // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // return
- // }
- if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
- continue
- }
- // dataexcel["1"] = barFsions.Get("times1").ValueStr()
- // dataexcel["2"] = barFsions.Get("times2").ValueStr()
- // dataexcel["3"] = barFsions.Get("times3").ValueStr()
- // dataexcel["4"] = barFsions.Get("times4").ValueStr()
- // dataexcel["5"] = barFsions.Get("times5").ValueStr()
- // dataexcel["6"] = barFsions.Get("times6").ValueStr()
- // /*
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- // */
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- fmt.Println(err)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- fmt.Println(err)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- fmt.Println(err)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- fmt.Println(err)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- fmt.Println(err)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- fmt.Println(err)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,ifnull(weight,0)weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
- if err != nil {
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
- }
- }
- func AddXxwFtdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- xxwFtdetailList := make([]*models.XXWFtdetail, 0)
- c.Bind(&xxwFtdetailList)
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.Exec(` delete from xxw_feedtemplet `)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- _, err = tx.Insert(xxwFtdetailList)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func AddXxwFeedtemplet(c *gin.Context) {
- appG := app.Gin{C: c}
- xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
- c.Bind(&xxwFeedtempletList)
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
- WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- for _, ft := range xxwFeedtempletList {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
- values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
- ft.RecipeobjName, ft.RecipeobjName)
- if err != nil {
- logs.Error(err)
- return
- }
- count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
- _, err = tx.Exec(` insert into feedtemplet(pastureid,tcode,tname,xxwTempletCode,ccid,ccname,owner,fttype,fttypeid,source,sort,xxwTempletCode)values(?,(concat(DATE_FORMAT(now(),'%Y%m%d'),'640247041')),
- ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
- pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
- if err != nil {
- logs.Error(err)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func ProcessExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fasion := gofasion.NewFasion(string(dataByte))
- params := fasion.Get("parammaps")
- pastureid := params.Get("pastureid").ValueStr()
- startTime := params.Get("startTime").ValueStr()
- stopTime := params.Get("stopTime").ValueStr()
- iscompleted := params.Get("iscompleted").ValueStr()
- lpplantype := params.Get("lpplantype").ValueStr()
- error := params.Get("error").ValueStr()
- hlwc1 := params.Get("hlwc1").ValueStr()
- hlwc2 := params.Get("hlwc2").ValueStr()
- slwc1 := params.Get("slwc1").ValueStr()
- slwc2 := params.Get("slwc2").ValueStr()
- hlzq1 := params.Get("hlzq1").ValueStr()
- hlzq2 := params.Get("hlzq2").ValueStr()
- slzq1 := params.Get("slzq1").ValueStr()
- slzq2 := params.Get("slzq2").ValueStr()
- fclassid := params.Get("fclassid").ValueStr()
- minproesstime := params.Get("minproesstime").ValueStr()
- maxproesstime := params.Get("maxproesstime").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- planList, err := tx.SQL(`SELECT
- d.id,d.tmrtname,d.projname,date_format(d.mydate ,'%Y-%m-%d') mydate ,date_format(d.intime ,'%Y-%m-%d') intime,p.pasture_name pastureName
- FROM downloadedplan d
- join pasture p on p.pastureid = d.pastureid
- WHERE d.pastureid= ? and d.intime IS NOT NULL
- AND mydate >= ? AND mydate <= ?
- AND (iscompleted=? or ?='')
- AND (lpplantype = ? or ? = '')
- and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
- and ABS(d1.lweight- d1.actualweightminus) > d1.feedallowratio and d1.feedallowratio != 0 ) >0,"有误差","无误差") = ? or if((select count(1) from downloadplandtl2 d1 where d1.pid = d.id
- and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
- and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
- and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
- and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
- and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
- and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
- and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
- and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
- and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
- and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
- join feed f on f.feedcode = d1.feedcode and f.pastureid = d1.pastureid where f.fclassid = ? and d1.pid = d.id) > 0) and (round(TIMESTAMPDIFF(SECOND,
- concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
- concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
- WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
- (SELECT MAX(intime) FROM downloadplandtl1_exec d2
- WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
- ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
- or (?= '' and ? = '' ))
- `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
- error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
- hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
- maxproesstime, minproesstime, maxproesstime).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- planExecList, err := tx.SQL(`SELECT
- IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
- WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
- , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
- WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
- ) proesstime,
- TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
- WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
- WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
- sumproesstime, d1.pid,
- d1.sort,
- d1.fname,
- d1.lweight,
- d1.actualweightminus,
- ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
- ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
- round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
- if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
- if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
- 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
- if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
- DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
- d1.begintime stoptime,
- d1.lastactualweight,
- d1.actualweight,
- if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
- case d1.buttontype
- when 1 then '自动'
- when 2 then '手动'
- when 3 then '手动'
- end,
- case d1.buttontype
- when 1 then 'Automatic'
- when 2 then 'Manual'
- when 3 then 'Manual'
- end
- ) buttontype
- FROM
- downloadplandtl1_exec d1
- WHERE d1.date between ? and ?
- ORDER BY sort
- `, startTime, stopTime).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- planExec2, err := tx.SQL(`SELECT
- IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
- WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
- , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
- WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
- ) proesstime,
- TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
- WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
- WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
- d1.sort,
- d1.fname,
- d1.lweight,
- d1.actualweightminus,
- if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
- ABS(d1.lweight- d1.actualweightminus) diff,
- round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,if(abs(d1.actualweightminus - d1.lweight) <=d1.allowratio , 100,if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - d1.allowratio)/d1.actualweightminus , 1-(abs(d1.actualweightminus - d1.lweight) - d1.allowratio)/d1.lweight )* 100) ,if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
- DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
- d1.begintime stoptime,
- d1.lastactualweight,
- d1.actualweight,d1.pid
- FROM
- downloadplandtl2 d1
- WHERE d1.date between ? and ?
- ORDER BY sort`, startTime, stopTime).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- // 创建一个新的 Excel 文件
- f := excelizexuri.NewFile()
- // 创建工作表名称
- sheetName := "Sheet1"
- border := []excelizexuri.Border{
- {Type: "left", Color: "000000", Style: 1},
- {Type: "right", Color: "000000", Style: 1},
- {Type: "top", Color: "000000", Style: 1},
- {Type: "bottom", Color: "000000", Style: 1},
- }
- // 创建新的样式
- style := &excelizexuri.Style{
- // Border: border,
- Alignment: &excelizexuri.Alignment{
- Vertical: "center",
- Horizontal: "center",
- ShrinkToFit: true,
- WrapText: true,
- },
- }
- styleTitle := &excelizexuri.Style{
- // Border: border,
- Font: &excelizexuri.Font{
- Bold: true, // 加粗
- Size: 24, // 字体大小
- // Name: "宋体", // 字体名称
- // WrapText :true,
- Color: "000000", // 字体颜色(黑色)
- },
- Alignment: &excelizexuri.Alignment{
- Vertical: "center", // 垂直居中
- Horizontal: "center", // 水平居中
- ShrinkToFit: true,
- WrapText: true,
- },
- }
- // 创建样式 ID
- styleTitleId, err := f.NewStyle(styleTitle)
- if err != nil {
- c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
- return
- }
- // 创建样式 ID
- styleID, err := f.NewStyle(style)
- if err != nil {
- c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
- return
- }
- // 合并单元格并设置内容
- f.MergeCell(sheetName, "A1", "K1")
- f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
- f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
- // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
- planExecMap := make(map[string][]map[string]string, 0)
- for _, planExec := range planExecList {
- planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
- }
- plan2Map := make(map[string][]map[string]string, 0)
- for _, plan2 := range planExec2 {
- plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
- }
- num := 2
- var notBorder []int
- for _, plan := range planList {
- fmt.Println(plan)
- headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
- f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
- f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
- for i, header := range headers {
- // 从 A2 开始
- if header == "开始日期" {
- cell := "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+i+1)
- f.SetCellValue(sheetName, cell, header)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- continue
- }
- cell := "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+i)
- f.SetCellValue(sheetName, cell, header)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- num += 1
- // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
- cell := "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+0)
- f.SetCellValue(sheetName, cell, plan["pastureName"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
- cell = "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+1)
- f.SetCellValue(sheetName, cell, plan["tmrtname"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
- cell = "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+2)
- f.SetCellValue(sheetName, cell, plan["projname"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+3)
- f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
- f.SetCellValue(sheetName, cell, plan["mydate"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'A'+6)
- f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
- f.SetCellValue(sheetName, cell, plan["intime"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- num += 1
- headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
- for i, header := range headers1 {
- cell = "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'C'+i)
- f.SetCellValue(sheetName, cell, header)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- // maxWidth := len(header)
- // colName := string('C' + i)
- // f.SetColWidth(sheetName, colName, colName, 20)
- f.SetColWidth(sheetName, header, header, 40)
- }
- num += 1
- for _, planExec := range planExecMap[plan["id"]] {
- cell := fmt.Sprintf("C%d", num) // 从 A2 开始
- sort, _ := strconv.Atoi(planExec["sort"])
- f.SetCellValue(sheetName, cell, sort)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("D%d", num)
- lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
- f.SetCellValue(sheetName, cell, lweight)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("E%d", num)
- if _, ok := planExec["actualweightminus"]; ok {
- actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
- f.SetCellValue(sheetName, cell, actualweightminus)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("F%d", num)
- f.SetCellValue(sheetName, cell, planExec["fname"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("G%d", num)
- if _, ok := planExec["diff"]; ok {
- diff, _ := strconv.ParseFloat(planExec["diff"], 64)
- f.SetCellValue(sheetName, cell, diff)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, planExec["diff"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("H%d", num)
- if _, ok := planExec["diffRate"]; ok {
- diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
- f.SetCellValue(sheetName, cell, diffRate)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, planExec["diffRate"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("I%d", num)
- f.SetCellValue(sheetName, cell, planExec["intime"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("J%d", num)
- if _, ok := planExec["lastactualweight"]; ok {
- lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
- f.SetCellValue(sheetName, cell, lastactualweight)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("K%d", num)
- if _, ok := planExec["actualweight"]; ok {
- actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
- f.SetCellValue(sheetName, cell, actualweight)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, planExec["actualweight"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- num += 1
- }
- headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
- for i, header := range headers2 {
- cell := "%" + fmt.Sprintf("c%d", num)
- cell = fmt.Sprintf(cell, 'C'+i)
- f.SetCellValue(sheetName, cell, header)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- maxWidth := len(header)
- f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
- }
- num += 1
- for _, plan2 := range plan2Map[plan["id"]] {
- cell := fmt.Sprintf("C%d", num) // 从 A2 开始
- sort, _ := strconv.Atoi(plan2["sort"])
- f.SetCellValue(sheetName, cell, sort)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("D%d", num)
- f.SetCellValue(sheetName, cell, plan2["fname"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("E%d", num)
- lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
- f.SetCellValue(sheetName, cell, lweight)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("F%d", num)
- if _, ok := plan2["actualweightminus"]; ok {
- actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
- f.SetCellValue(sheetName, cell, actualweightminus)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("G%d", num)
- if _, ok := plan2["diff"]; ok {
- diff, _ := strconv.ParseFloat(plan2["diff"], 64)
- f.SetCellValue(sheetName, cell, diff)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, plan2["diff"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("H%d", num)
- if _, ok := plan2["diffRate"]; ok {
- diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
- f.SetCellValue(sheetName, cell, diffRate)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, plan2["diffRate"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("I%d", num)
- f.SetCellValue(sheetName, cell, plan2["intime"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- cell = fmt.Sprintf("J%d", num)
- if _, ok := plan2["lastactualweight"]; ok {
- lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
- f.SetCellValue(sheetName, cell, lastactualweight)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- cell = fmt.Sprintf("K%d", num)
- if _, ok := plan2["lastactualweight"]; ok {
- actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
- f.SetCellValue(sheetName, cell, actualweight)
- f.SetCellStyle(sheetName, cell, cell, styleID)
- } else {
- f.SetCellValue(sheetName, cell, plan2["actualweight"])
- f.SetCellStyle(sheetName, cell, cell, styleID)
- }
- num += 1
- }
- num += 1
- notBorder = append(notBorder, num)
- }
- for i := 2; i < num; i++ {
- exist := false
- for _, n := range notBorder {
- if i+1 == n {
- exist = true
- break
- }
- }
- if !exist {
- // 为 A-K 列设置边框
- for col := 'A'; col <= 'K'; col++ {
- cellName := fmt.Sprintf("%c%d", col, i)
- style, _ := f.NewStyle(&excelizexuri.Style{
- Border: border, Alignment: &excelizexuri.Alignment{
- Vertical: "center",
- Horizontal: "center",
- ShrinkToFit: true,
- WrapText: true,
- },
- })
- f.SetCellStyle(sheetName, cellName, cellName, style)
- }
- }
- }
- for col := 'A'; col <= 'K'; col++ {
- colName := string(col)
- switch colName {
- case "A", "B": // 牧场名称、TMR列
- f.SetColWidth(sheetName, colName, colName, 10)
- case "C": // 操作编号列
- f.SetColWidth(sheetName, colName, colName, 10)
- case "D", "E": // 计划重量、实际重量列
- f.SetColWidth(sheetName, colName, colName, 12)
- case "F": // 代表成分/投料位置列
- f.SetColWidth(sheetName, colName, colName, 20)
- case "G", "H": // 误差数、准确率列
- f.SetColWidth(sheetName, colName, colName, 12)
- case "I": // 完成时间列
- f.SetColWidth(sheetName, colName, colName, 15)
- case "J", "K": // 起始读数重量、完成读数重量列
- f.SetColWidth(sheetName, colName, colName, 15)
- }
- }
- // 设置响应头
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
- c.Header("Content-Transfer-Encoding", "binary")
- // 写入 Excel 文件到响应
- if err := f.Write(c.Writer); err != nil {
- c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
- return
- }
- }
- func RestartMqtt(c *gin.Context) {
- appG := app.Gin{C: c}
- // 发送 GET 请求到 MQTT 重启接口
- resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
- if err != nil {
- logging.Error("RestartMqtt request failed:", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
- return
- }
- defer resp.Body.Close()
- // 读取响应内容f
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- logging.Error("RestartMqtt read response failed:", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
- return
- }
- // 检查响应状态码
- if resp.StatusCode != http.StatusOK {
- logging.Error("RestartMqtt failed with status:", resp.StatusCode)
- appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, string(body))
- }
- func FpdBatchEditByWeight(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- barList := fsions.Get("barList").Array()
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- for _, barFsions := range barList {
- dataexcel := make(map[string]interface{}, 0)
- dataexcel["barname"] = barFsions.Get("barname").ValueStr()
- dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
- dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
- dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
- dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
- if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
- continue
- }
- // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
- // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
- // barFsions.Get("times3").ValueDefaultFloat64(0) +
- // barFsions.Get("times4").ValueDefaultFloat64(0) +
- // barFsions.Get("times5").ValueDefaultFloat64(0) +
- // barFsions.Get("times6").ValueDefaultFloat64(0))
- // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
- // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
- // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
- // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
- // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
- // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
- dataexcel["1"] = barFsions.Get("times1").ValueStr()
- dataexcel["2"] = barFsions.Get("times2").ValueStr()
- dataexcel["3"] = barFsions.Get("times3").ValueStr()
- dataexcel["4"] = barFsions.Get("times4").ValueStr()
- dataexcel["5"] = barFsions.Get("times5").ValueStr()
- dataexcel["6"] = barFsions.Get("times6").ValueStr()
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- // upFeedpSql += `,ftweight = ? `
- // feedpargs = append(feedpargs, weight)
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- // if _, ok := dataexcel["ptsfname"]; ok {
- // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- // } else {
- // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- // }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
- alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
- dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func FtImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- //importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- tx := restful.Engine.NewSession()
- ftNameList := make(map[string]interface{})
- var ftNames []interface{}
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- fmt.Println(outentry, entry)
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- err := tx.Begin()
- if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
- tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
- ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
- }
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- ftNames = append(ftNames, outentry["配方名称"])
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- go ftSync(ftNames, pastureid)
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func ftSync(ftNameList []interface{}, pastureId string) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- for _, ftName := range ftNameList {
- values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
- ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
- ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
- ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
- ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
- ),0) as '6' from feedp fp join bar b on b.id = fp.barid
- join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
- FpdBatchEditGrfd(pastureId, values1)
- }
- }
- func CopyFeedtemplet(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- pastureid := fsion.Get("pastureid").ValueStr()
- newName := fsion.Get("newName").ValueStr()
- id := fsion.Get("id").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- if count > 0 {
- appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
- return
- }
- type ftCode struct {
- Tcode string `xorm:"tcode"`
- }
- code := new(ftCode)
- err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
- (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
- (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- if code.Tcode == "" {
- appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
- return
- }
- _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
- remark,enable,sort,volume,autozone)
- select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
- remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
- return
- }
- _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
- autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
- select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
- autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
- from ftdetail where ftid = ? `, code.Tcode, id)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func Test(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
- }
- func GetPlanDry(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- date := fsion.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`SELECT
- t.feedtempletName,
- ifnull(t.feedtempletPrice,0)feedtempletPrice,
- ifnull(t.feedtempletWeight,0)feedtempletWeight,
- ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
- t.tmrno,
- t.bname,
- t.barid,
- t.dry,
- t.actualweightminus,
- t.mydate,
- t.pasturename,
- t.endDate,
- t.startDate,
- t.times,
- -- 计算startDate和endDate的中间时间
- ifnull(DATE_FORMAT(
- DATE_ADD(
- t.startDate,
- INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
- ),
- '%Y-%m-%d %H:%i:%s'
- ),'') AS midTime
- FROM (
- SELECT
- (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
- b.bname,
- b.id barid,
- ROUND(IF(IFNULL(d2.actualweightminus,0) < 0, d2.lweight/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) , d2.actualweightminus/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) )*((SELECT IFNULL(AVG(dry),0) FROM downloadedplan dd
- JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
- JOIN feednur fn ON fn.fid = dd1.fid
- WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
- IF(IFNULL(d2.actualweightminus,0) < 0, d2.lweight/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) , d2.actualweightminus/(select sum(actualweightminus) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) ) actualweightminus,
- DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
- p.pasture_name pastureName,
- DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
- DATE_FORMAT(IFNULL(
- (SELECT MAX(intime) FROM downloadplandtl2 d1
- WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
- (SELECT MAX(intime) FROM downloadplandtl1_exec de
- WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
- ), '%Y-%m-%d %H:%i:%s') startDate,
- d.times ,
- ( SELECT
- round(SUM(
- IF(ftd.preftid<>0,
- ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
- JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
- WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
- ftd.fweight*f.dry/100)) ,2)
- dryweight
- FROM ftdetaildate ftd
- LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
- WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
- select
- sum(ftd.fweight)
- FROM ftdetaildate ftd
- WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
- ( SELECT
- round(SUM(
- IF(ftd.preftid<>0,
- IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
- JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
- WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
- ftd.fweight*f.uprice)) ,2)
- dryweight
- FROM ftdetaildate ftd
- LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
- WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
- feedtempletPrice,d.templetname feedtempletName
- FROM downloadedplan d
- JOIN downloadplandtl2 d2 ON d.id=d2.PID
- JOIN bar b ON b.id = d2.fbarid
- JOIN pasture p ON p.pastureid = d.pastureid
- WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
- AND d2.type = 0
- AND d.havebutton = 1
- ) t
- WHERE 1=1 `, date).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "查询失败")
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- func GetBar(c *gin.Context) {
- appG := app.Gin{C: c}
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
- WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "查询失败")
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- func GetHomepage(c *gin.Context) {
- appG := app.Gin{C: c}
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(` SELECT
- ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
- FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
- AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
- (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
- FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
- AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) )monRateHL , -- 近30日混料准确率
-
- ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
- FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
- AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
-
- (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
- FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
- AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) )monRateSL, -- 进30日撒料准确率
- ifnull((SELECT CONCAT(ROUND(IF(COUNT(de.id)>0,SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio,1,0))/COUNT(de.id),0)*100,2),'%') -- 正确率
- FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
- WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
- (SELECT CONCAT(ROUND(IF(COUNT(de.id)>0,SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio,1,0))/COUNT(de.id),0)*100,2),'%') -- 正确率
- FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
- WHERE dt.pastureid = d.pastureid
- AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')) monRateSLR, -- 近30日正确率
- (SELECT COUNT(*)FROM downloadedplan dt WHERE dt.pastureid= d.pastureid AND dt.mydate = d.mydate and dt.iscompleted=1 and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) )) doneTimes,
- (SELECT COUNT(*)FROM downloadedplan dt WHERE dt.pastureid= d.pastureid AND dt.mydate = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ) planTimes,
- ifnull((SELECT SUM(dc.actualweightminus) FROM downloadplandtl1_exec dc join downloadedplan dt on dt.id = dc.pid WHERE dc.pastureid = 0 AND dc.date = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ),0) doneWeight,
- ifnull((SELECT SUM(dc.lweight ) FROM downloadplandtl1_exec dc join downloadedplan dt on dt.id = dc.pid WHERE dc.pastureid = 0 AND dc.date = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ),0) planWeight,
- ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
- ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
- FROM
- (SELECT (select column_default as pastureid from information_schema.COLUMNS
- WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid') as pastureid,date_format(now(),'%Y-%m-%d') mydate) d `, setting.DatabaseSetting.Name).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "查询失败")
- return
- }
- dataList1, err := tx.SQL(`select
- ifnull(round(sum(if(d1.feedcode = '-1', d1.actualweightminus * (ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.ftid = d1.fid ))* f.uprice,f.uprice * d1.actualweightminus )) / (select sum(ccount) from downloadplandtl2 d2 join bar b on b.id = d2.fbarid join feedp fp on fp.barid = b.id where date = d1.date),2),0) cost , ifnull(round(sum(if(d1.feedcode = '-1', d1.actualweightminus * (ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.ftid = d1.fid ))* f.uprice,f.uprice * d1.actualweightminus )),2),0) totalCost from downloadplandtl1 d1
- LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
- join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "查询失败")
- return
- }
- for _, data := range dataList {
- for _, data1 := range dataList1 {
- data["totalCost"] = data1["totalCost"]
- data["cost"] = data1["cost"]
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- func GetFeedingManagement(c *gin.Context) {
- appG := app.Gin{C: c}
- typea := c.Query("typea") // 0 栏舍 1 日期
- startDate := c.Query("startdate")
- endDate := c.Query("enddate")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- if typea == "0" {
- dataList, err := tx.SQL(`select t.bname typea ,round(t.actualweightminus,2) actualweightminus ,round(t.dryweight,2) dryweight ,round(t.priceweight,2) totalcost ,round(t.priceweight / t.ccount,2) cost,t.ccount from (SELECT
- SUM(
- if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
- d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
-
- d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
- )
- )actualweightminus ,
- SUM(
- if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
- d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
-
- d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
- ) * ifnull(fn.dry,0)
- ) dryweight , SUM(
- if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
- d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
-
- d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
- ) * ifnull(f.uprice,0)
- ) priceweight
- ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
-
- FROM
- downloadedplan d
- JOIN downloadplandtl2 d2
- ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
- JOIN downloadplandtl1 d1
- ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
- left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
- LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = ftd1.id AND d1.feedcode = '-1' AND ftd.date =d1.date AND ftd.version = ftd1.version
- left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
- join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
- left join feednur fn on fn.fid = f.id
- WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "查询失败")
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- } else {
- dataList, err := tx.SQL(`select date_format(t.date ,'%Y-%m-%d') typea ,round(t.actualweightminus,2) actualweightminus ,round(t.dryweight,2) dryweight ,round(t.priceweight,2) totalcost ,round(t.priceweight / (select sum(ccount) from feedpdate fp where fp.date = t.date and fp.barid in(select fbarid from downloadplandtl2 where date = t.date and type = 0) ) ,2) cost,(select sum(ccount) from feedpdate fp where fp.date = t.date and fp.barid in(select fbarid from downloadplandtl2 where date = t.date and type = 0) ) ccount from (SELECT
- SUM(
- if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
- d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
-
- d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
- )
- )actualweightminus ,
- SUM(
- if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
- d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
-
- d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
- ) * ifnull(fn.dry,0)
- ) dryweight , SUM(
- if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
- d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
-
- d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
- d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
- ) * ifnull(f.uprice,0)
- ) priceweight
- ,(select sum(ccount) from feedpdate fp join downloadplandtl2 dd2 on dd2.fbarid = fp.barid where fp.date = d2.date and dd2.date = d2.date ) ccount,d2.date
-
- FROM
- downloadedplan d
- JOIN downloadplandtl2 d2
- ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
- JOIN downloadplandtl1 d1
- ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
- left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
- LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = ftd1.id AND d1.feedcode = '-1' AND ftd.date =d1.date AND ftd.version = ftd1.version
- left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
- join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
- left join feednur fn on fn.fid = f.id
- WHERE d.mydate BETWEEN ? AND ?
- GROUP BY d.mydate) t `, startDate, endDate).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "查询失败")
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- }
- // doneTimes 完成计划
- // doneWeight 完成重量
- // monRateHL 近三十天混料准确率
- // monRateSL 近三十天撒料准确率
- // monRateSLR 近30天撒料正确率
- // montime 近30天撒料偏差
- // planTimes 计划车次
- // planWeight 计划重量
- // temtime 撒料偏差
- // yesRateHL 混料准确率
- // yesRateSL 撒料准确率
- // yesRateSLR 撒料正确率
|